// Este fichero contendra todas aquellas funciones javascript de uso general.
document.oncontextmenu = function(){return false}

//begin desabilitar teclas
document.onkeydown = function(){
//116->f5
//122->f11
//8 -> backspace
if (window.event && (window.event.keyCode == 122 || window.event.keyCode == 116)){
window.event.keyCode = 505;
}

if (window.event && window.event.keyCode == 505){
return false;
}

if (window.event && (window.event.keyCode == 8))
{
valor = document.activeElement.value;
if (valor==undefined) { return false; } //Evita Back en página.
else
{
if (document.activeElement.getAttribute('type')=='select-one')
  { return false; } //Evita Back en select.
if (document.activeElement.getAttribute('type')=='button')
  { return false; } //Evita Back en button.
if (document.activeElement.getAttribute('type')=='radio')
  { return false; } //Evita Back en radio.
if (document.activeElement.getAttribute('type')=='checkbox')
  { return false; } //Evita Back en checkbox.
if (document.activeElement.getAttribute('type')=='file')
  { return false; } //Evita Back en file.
if (document.activeElement.getAttribute('type')=='reset')
  { return false; } //Evita Back en reset.
if (document.activeElement.getAttribute('type')=='submit')
  { return false; } //Evita Back en submit.
else //Text, textarea o password
{
  if (document.activeElement.value.length==0)
      { return false; } //No realiza el backspace(largo igual a 0).
  else
      {
	  if(document.activeElement.disabled || document.activeElement.getAttribute('readonly')) {
		  return false;
	  } else {
		  document.activeElement.value.keyCode = 8;
	  }

      } //Realiza el backspace.
}
}
}
}
//Comprobamos si el proceso al que queremos acceder esta bloqueado
var callingURL = document.URL;
if(callingURL.indexOf('bloqueado=si',0) != -1){
alert('El proceso al que intenta acceder ya esta siendo utilizado por otro usuario');
}

//Petici?n de Url
function crearXMLRequest()
{
   var req;
       try {
           // for Mozilla
             req = new XMLHttpRequest();
             req.overrideMimeType("text/html");
       } catch (e) {
         // for IE5+
         req = new ActiveXObject("MSXML2.XMLHTTP");
               }
   return req;
}
function ejecutarUrl(ruta)
{
try {
       var req = crearXMLRequest();
       req.open("GET", ruta,false);
       req.send(ruta);
           if(navigator.appName != "Microsoft Internet Explorer"){
           //alert(req.responseText);
           return req.responseXML;
       		}
       var valor = new ActiveXObject("MSXML2.DomDocument");
       valor.loadXML(req.responseText);
       return valor;
} catch(e) {}
}


//Funcionalidad: Nos dira si una determinada fila de un listado esta marcada o no.
//Parametro 1 "fila": Nuevo elemento seleccionado (sera un tr con su identificador correspondiente)
//Parametro 2 "filaSeleccionada": Campo oculto (hidden) que contendra el valor del elemento marcado actualmente.
//Parametro 3 "valor": Si especificamos este parametro cogeremos este valor para guardar y en el campo oculto y no el id del tr.
//					Necesario para valores con espacios o con valores no v??lidos para un id.
function estaSeleccionado()
{
	var fila,filaSeleccionada,valor;
	fila=arguments[0];
	filaSeleccionada=arguments[1];
	if (arguments.length==3)
		valor=arguments[2];
	else if (arguments.length==2)
		valor=fila.id;

	if (filaSeleccionada.value==valor)
		return true;
	else
		return false;
  }

//Funcionalidad: Seleccionar una fila de un listado.
//Parametro "fila": elemento seleccionado (sera un tr con su identificador correspondiente)
//Parametro "filaSeleccionada": Campo oculto (hidden) que contendra el valor del elemento marcado actualmente.
//Parametro "valor": Si especificamos este parametro cogeremos este valor para guardar y en el campo oculto y no el id del tr.
//					Necesario para valores con espacios o con valores no validos para un id.
//(jmmoguer@isotrol.com)
function seleccionaFila()
{
	var fila,filaSeleccionada,valor;
	var fila_antigua;
	var idFilaSeleccionada;

	fila=arguments[0];
	filaSeleccionada=arguments[1];
	if (filaSeleccionada.value!='') {
		//Deselecionamos el que estuviera seleccionado
		if (arguments.length==3) {
			idFilaSeleccionada=filaSeleccionada.id;
			idFilaSeleccionada=idFilaSeleccionada.substr(0,idFilaSeleccionada.length-2);//Obtenemos el id correspondiente al tr antiguo quitando el "hd" final
			fila_antigua=document.getElementById(idFilaSeleccionada);
		} else if (arguments.length==2)
			fila_antigua=document.getElementById(filaSeleccionada.value);

		fila_antigua.className=filaSeleccionada.tag;
	}

	//Guardamos el identificador del profesional seleccionado y la clase a la que pertenece.
	if (arguments.length==3) {
		valor=arguments[2];
		filaSeleccionada.value=valor;
		filaSeleccionada.id=fila.id+"hd";
	} else if (arguments.length==2)
		filaSeleccionada.value=fila.id;

	filaSeleccionada.tag=fila.className;
	//Cambiamos la clase de la fila
	fila.className='colorfondoSeleccionado';
}

//Funciones para mostrar, ocultar y tratamiento de capas
var nc = (document.layers) ? true:false;
var ie = (document.all) ? true:false;
var n6 = (document.getElementById) ? true:false;

/* funcion para mostrar la capa */
function muestracapa()
{
	var id = arguments[0];
  	var ventana=null;
	if (arguments.length>1)
		ventana=arguments[1];
	else
		ventana=window;

    if(ie) {
    	if(ventana.document.getElementById(id) != null)
			ventana.document.getElementById(id).style.display="block";
    }else if(nc) {
    	if(ventana.document.principal.document.fondo.document.layers[id] != null)
			ventana.document.principal.document.fondo.document.layers[id].style.display="block";
    }else if(n6) {
    	if(ventana.document.getElementById(id) != null)
			ventana.document.getElementById(id).style.display="block";
	}
}

function muestracapa2()
{
	var id = arguments[0];
  	var ventana=null;
	if (arguments.length>1)
		ventana=arguments[1];
	else
		ventana=window;

    if(ie) {
      ventana.document.getElementById(id).style.visibility="visible";
    }else if(nc){
      ventana.document.principal.document.fondo.document.layers[id].visibility="show";
    }else if(n6){
      ventana.document.getElementById(id).style.visibility="visible";
	}
}

/* funcion para esconder la capa */
function escondecapa () {
	var id = arguments[0];
	var ventana=null;
	if (arguments.length>1)
		ventana=arguments[1];
	else
		ventana=window;

	if (document.all){
		if(ventana.document.all[id] != null)
			ventana.document.all[id].style.display="none";
	}else if (document.layers) {
		if(ventana.document.layers[id] != null)
			ventana.document.layers[id].style.display="none";
	}else if (document.getElementById) {
		if(ventana.document.getElementById(id) != null)
			ventana.document.getElementById(id).style.display="none";
	}
}

function escondecapa2()
{
	var id = arguments[0];
	var ventana=null;
	if (arguments.length>1)
		ventana=arguments[1];
	else
		ventana=window;

	if (document.all){
		ventana.document.all[id].style.visibility="hidden";
	}else if (document.layers) {
		ventana.document.layers[id].visibility="hide";
	}else if (document.getElementById) {
		ventana.document.getElementById(id).style.visibility="hidden";
	}
}

//Funcion que nos dira si una capa esta oculta o no
function estaOculta (id)
{
	var oculta=false;
	if (document.all) {
		if (document.all[id].style.visibility=="hidden") oculta=true;
	} else if (document.layers) {
		if (document.layers[id].visibility=="hide") oculta=true;
	} else if (document.getElementById) {
		if(document.getElementById(id).style.visibility=="hidden") oculta=true;
	}

	return oculta;
}
//Fin de funciones para capas

//Funciones para obtener la posicion real de un elemento cualquiera
function getElement(id)
{
	return document.getElementById ? document.getElementById(id) : document.all ? document.all(id) : null;
}

function getRealLeft(id)
{
	var el = getElement(id);
	if (el) {
		xPos = el.offsetLeft;
		tempEl = el.offsetParent;
		while (tempEl != null) {
			xPos += tempEl.offsetLeft;
			tempEl = tempEl.offsetParent;
		}

		return xPos;
	}
}

function getRealTop(id)
{
	var el = getElement(id);
	if (el) {
		yPos = el.offsetTop;
		tempEl = el.offsetParent;
		while (tempEl != null) {
			yPos += tempEl.offsetTop;
			tempEl = tempEl.offsetParent;
		}

		return yPos;
	}
}

function getRealRight(id)
{
	return getRealLeft(id) + getElement(id).offsetWidth;
}

function getRealBottom(id)
{
	return getRealTop(id) + getElement(id).offsetHeight;
}

function move_to_bot_center(mover_id, fixer_id)
{
	var el = getElement(mover_id);
	if (el) {
		var fix_bot = getRealBottom(fixer_id);
		var fix_lt = getRealLeft(fixer_id);
		el.style.left = (fix_lt + getElement(fixer_id).offsetWidth/2) - (el.offsetWidth/2);
		el.style.top = fix_bot;
	}
}

function move_to_rt_center(mover_id, fixer_id)
{
	var el = getElement(mover_id);
	if (el) {
		var fix_top = getRealTop(fixer_id);
		var fix_rt = getRealRight(fixer_id);
		el.style.left = fix_rt;
		el.style.top = (fix_top + getElement(fixer_id).offsetHeight/2) - (el.offsetHeight/2);
	}
}

// Carga el select de los dias y se?ala el adecuado si viene dado
function cambiaNumDias(elmes, dias, diasel){
	var tamfor;
	var numdias=document.getElementById(dias);
	var p =numdias.childNodes.length;
	for(j=0; j<p; j++) {
		numdias.removeChild(numdias.childNodes[0]);
	}
	if(elmes==1 || elmes==3 || elmes==5 || elmes==7|| elmes==8 || elmes==10 || elmes==12) {
		tamfor=31;
	} else if(elmes==4 || elmes==6 || elmes==9 || elmes==11) {
		tamfor=30;
	} else if(elmes==2) {
		tamfor=29;
	}

	for(i=1;i<=tamfor;i++) {
		var texto=document.createTextNode(i);
		var opcion=document.createElement("option");
		opcion.appendChild(texto);
		opcion.value=i;
		if(i==diasel){
			opcion.selected=true;
		}
		numdias.appendChild(opcion);
	}
}

// Esta funcion nos devuelve el listado a?adiendo el nombre completo formateado
function dameNombreCompleto(nombre,ape1,ape2)
{
	var nombreCompleto="";
	if(nombre!="") {
		if(ape1!="" || ape2!="") {
			nombreCompleto = nombreCompleto + ape1;
			nombreCompleto = nombreCompleto + " ";
			nombreCompleto = nombreCompleto + ape2;
			nombreCompleto = nombreCompleto + ",";
			nombreCompleto = nombreCompleto + " ";
			nombreCompleto = nombreCompleto + nombre;
		} else
			nombreCompleto = nombreCompleto + nombre;
	} else {
		nombreCompleto = nombreCompleto + ape1;
		nombreCompleto = nombreCompleto + " ";
		nombreCompleto = nombreCompleto + ape2;
	}

	return nombreCompleto;
}

//####################################################
function tabActiva(numTab)
{
	var tabAct=1;
    var enc=false;
    for (var i=1;(i<=numTab) && !enc;i++) {
		if (document.getElementById('contentblock'+i).style.display=='block') {
			tabAct=i;
			enc=true;
		}
	}

	return tabAct;
}

function tabActivaGeneral(nombreDiv,numTab)
{
	var tabAct=1;
    var enc=false;
    var elem;
    for (var i=1;(i<=numTab) && !enc;i++) {
		elem=document.getElementById(nombreDiv+""+i);
		if (elem && elem.style.display=="block") {
			tabAct=i;
			enc=true;
	     }
    }

	return tabAct;
}

function muestraTodasTab(numTab)
{
	for (var i=1;i<=numTab;i++) {
		document.getElementById('contentblock'+i).style.display='block';
    }
}

//Le pasamos los nombre de los listados separados por dos puntos y el numero de pesta?as que tenemos
function redimensionarListados(listados,numTab)
{
	var arrayListados=listados.split(':');
	var tabAct=tabActiva(numTab);
	muestraTodasTab(numTab);
	for (var i=0;i<arrayListados.length;i++)
		eval(arrayListados[i]+".redimensionar()");
	domTab1(tabAct,numTab);
}

//Muestra el calendario
function muestraCalendario()
{
	var campoTexto=arguments[0];//obligatorio
	var campoBoton=arguments[1];//obligatorio
	var muestraHora=false;
	var formato="%d/%m/%Y";

	if (arguments.length>2){
		if (arguments[2]==true) muestraHora=true;
	} //Indicamos si mostramos Hora y minutos
	if (arguments.length>3){
		formato=arguments[3];
	}//Indicamos el formato del campo de texto
	if (arguments.length>2) {
		var alineacion=arguments[2];
		Calendar.setup({
			inputField     :    campoTexto.id,	// id del campo de texto
			ifFormat       :    formato,		// Formato del campo de texto
			showsTime      :    muestraHora,	// Mostrar selector de hora
			button         :    campoBoton.id,	// id del bot??n para abrir el calendario.
			singleClick    :    true,			// Modo click
			weekNumbers : false,
			align : alineacion
		});
	} else {
		Calendar.setup({
			inputField     :    campoTexto.id,	// id del campo de texto
			ifFormat       :    formato,		// Formato del campo de texto
			showsTime      :    muestraHora,	// Mostrar selector de hora
			button         :    campoBoton.id,	// id del bot??n para abrir el calendario.
			singleClick    :    true,			// Modo click
			weekNumbers : false
		});
	}
}

// Esta funcion posiciona la ventana popup en el centro de la pantalla
function abreVentanaCentrada()
{
	var url=arguments[0];
	var nombre=arguments[1];
	var anchoVentana=arguments[2];
	var altoVentana=arguments[3];
	var configuracion = arguments[4];
	var anchoPantalla = screen.width;
	var altoPantalla = screen.height;
	var estilo ="";
	var altoVentanaPadre = top.screenTop;
	var anchoVentanaPadre = top.screenLeft;

	if(arguments.length < 3) {
		anchoVentana=screen.width;
		altoVentana=screen.height;
	}

	if(arguments.length <5)
		estilo = "titlebar=no,menubar=no,location=no,status=no,directories=no,toolbar=no,border=no,resizable=yes,width="+anchoVentana+",height="+altoVentana;
	else
		estilo = configuracion + ",width="+anchoVentana+",height="+altoVentana;

	if(anchoPantalla==800 && altoPantalla==600) {
		if (navigator.appName.toLowerCase() == "navigator")
			estilo = estilo + ",screenY=0,screenX=0";
		else
			estilo = estilo + ",top=0,left=0";
	} else {
		if(altoVentanaPadre==0 && anchoVentanaPadre==0) {
			var distanciaArriba = (altoPantalla/2)-(altoVentana/2);
			var distanciaLateral = (anchoPantalla/2)-(anchoVentana/2);
			if (navigator.appName.toLowerCase() == "navigator")
				estilo = estilo + ",screenY="+distanciaArriba+",screenX="+distanciaLateral;
			else
				estilo = estilo + ",top="+distanciaArriba+",left="+distanciaLateral;
		} else {
			if (navigator.appName.toLowerCase() == "navigator") {
				var distanciaArriba = (altoPantalla/2)-(altoVentana/2);
				var distanciaLateral = (anchoPantalla/2)-(anchoVentana/2);
				estilo = estilo + ",screenY="+distanciaArriba+",screenX="+distanciaLateral;
			} else {
/*				var altoVentanaPadre = top.screenTop;
				var anchoVentanaPadre = top.screenLeft;
				var anchuraPadre=top.document.body.offsetWidth;
				var alturaPadre=top.document.body.offsetHeight;
				var distanciaArriba = (altoVentanaPadre+(alturaPadre/2))-(altoVentana/2);
				var distanciaLateral = (anchoVentanaPadre+(anchuraPadre/2))-(anchoVentana/2);*/

				distanciaArriba = (screen.height - altoVentana)/2;
				distanciaLateral = (screen.width - anchoVentana)/2;

				estilo = estilo + ",top="+distanciaArriba+",left="+distanciaLateral;
			}
		}
	}

	return window.open(url,nombre,estilo);
}

var arrayMensajesError;
var focusField;
//parametro 1: url del jsp que muestra los errores. (obligatorio)
//parametro 2: array de errores. (obligatorio)
//parametro 3: campo que tendra el foco tras el aviso. (opcional)
function muestraErrores()
{
	var url=arguments[0];
	var errores=arguments[1];
	if (arguments.length>2 && arguments[2]!=null) arguments[2].focus();
	arrayMensajesError = errores;
	abreVentanaCentrada(url,'error',400,200);
}

function formateaNombreCompleto(nombre,primerApellido,segundoApellido)
{
	var listado = '';
	if(nombre!="") {
		if(primerApellido !="" || segundoApellido !="") {
			listado = listado + primerApellido;
			listado = listado + " ";
			listado = listado + segundoApellido;
			listado = listado + ",";
			listado = listado + " ";
			listado = listado + nombre;
		}
	} else {
		listado = listado + primerApellido;
		listado = listado + " ";
		listado = listado + segundoApellido;
	}

	return listado;
}

function deshabilitarBotones(tar,botonesStr)
{
	if(botonesStr!="") {
		var botones=botonesStr.split(",");
		for(var i=0;i<botones.length;i++) {
			var boton = tar.document.getElementById(botones[i]);
			if (boton) {
				var clase=boton.className;
				clase=reemplazaTodo(clase,"Habilitado","Deshabilitado");
				boton.className=clase;
				boton.disabled=true;
			}
		}
	}
}

function habilitarBotones(tar,botonesStr)
{
	if(botonesStr!="") {
		var botones=botonesStr.split(",");
		for(var i=0;i<botones.length;i++) {
			var boton = tar.document.getElementById(botones[i]);
			if (boton) {
				var clase=boton.className;
				clase=reemplazaTodo(clase,"Deshabilitado","Habilitado");
				boton.className=clase;
				boton.disabled=false;
			}
		}
	}
}

// Estra funcion reemplaza todas las instancias de findStr en oldStr con repStr.
function reemplazaTodo(oldStr,findStr,repStr) {
	var srchNdx = 0;
	var newStr = "";
	while (oldStr.indexOf(findStr,srchNdx) != -1) {
		newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
		newStr += repStr;
		srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
	}
	newStr += oldStr.substring(srchNdx,oldStr.length);

	return newStr;
}

function cambiaCaracterHTMLporASCII(str)
{
	//minusculas
	str=reemplazaTodo(str,"&aacute;",String.fromCharCode(225));
	str=reemplazaTodo(str,"&eacute;",String.fromCharCode(233));
	str=reemplazaTodo(str,"&iacute;",String.fromCharCode(237));
	str=reemplazaTodo(str,"&oacute;",String.fromCharCode(243));
	str=reemplazaTodo(str,"&uacute;",String.fromCharCode(250));
	str=reemplazaTodo(str,"&nacute;",String.fromCharCode(241));
	//mayusculas
	str=reemplazaTodo(str,"&Aacute;",String.fromCharCode(193));
	str=reemplazaTodo(str,"&Eacute;",String.fromCharCode(201));
	str=reemplazaTodo(str,"&Iacute;",String.fromCharCode(205));
	str=reemplazaTodo(str,"&Oacute;",String.fromCharCode(211));
	str=reemplazaTodo(str,"&Uacute;",String.fromCharCode(218));
	str=reemplazaTodo(str,"&??acute;",String.fromCharCode(209));

	return str;
}

/*
 * Funcion que valida (!='') una determinada cantidad(atributo cantidad)
 * de listas desplegables donde el identificador de cada una de ellas
 * esta compuesto por el atributo raizId y la concatenacion de un valor
 * numerico a partir de la unidad hasta alcanzar el atributo cantidad.
 */
function validaConjuntoSelectById(raizId,cantidad)
{
	var i = 1;
	var cad="";
	for (i=1;i<=cantidad;i++) {
		cad = raizId + i;
		if (document.getElementById(cad).value=='')
			return false;
	}
	return true;
}

/* Funciones necesarias para limpiar select, insertar opciones, comprobar opciones repetidas */
function estaRepetido(campoSelect,clave)
{
	var enc=false;
	for (var i=0;i<campoSelect.length && !enc;i++) {
		if (campoSelect.options[i].value==clave) {
			enc=true;
		}
	}

	return enc;
}

function insertaOpcion(campoSelect,clave,valor)
{
	var nuevaopcion = new Option;
	if (!estaRepetido(campoSelect,clave)) {
		nuevaopcion.text=valor;
		nuevaopcion.value=clave;
		campoSelect.options[campoSelect.options.length]=nuevaopcion;
	}
}

//campoSelect: Select a limpiar.
//indiceComienzo: indice a partir del cual se borraran las opciones del select. (Opcional)
function limpiaSelect()
{
	var campoSelect=arguments[0];
	var indiceComienzo=0;
	if (arguments.length>1)
		indiceComienzo=arguments[1];
	for (var x = campoSelect.length; x >= indiceComienzo; x--) {
		campoSelect[x] = null;
	}
}

//Efecto borde para los botones
function efectoBoton()
{
	var acc=arguments[0];
	var elem=arguments[1];
	var nombre=arguments[2];
	var coletilla="Habilitado";
	if (arguments.length>3)
		coletilla=arguments[3];
	if(acc=='bordeBotonOver') {
		if (elem.disabled==false)
			elem.className="botonOver "+nombre+coletilla;
	} else if(acc=='bordeBotonOut') {
		if (elem.disabled==false)
			elem.className="botonOut "+nombre+coletilla;
	}
}

/* Funcion para mostrar la capa */
function muestracapa2()
{
	var id=arguments[0];
	var ventana=null;
	if (arguments.length>1)
		ventana=arguments[1];
	else
		ventana=window;

	if(ie)
		ventana.document.all[id].style.visibility="visible";
	else if(nc)
		ventana.document.principal.document.fondo.document.layers[id].visibility="show";
	else if(n6)
		ventana.document.getElementById(id).style.visibility="visible";
}

/* funcion para esconder la capa */
function escondecapa2 ()
{
	var id=arguments[0];
	var ventana=null;
	if (arguments.length>1)
		ventana=arguments[1];
	else
		ventana=window;

	if (ventana.document.all)
		ventana.document.all[id].style.visibility="hidden";
	else if (ventana.document.layers)
		ventana.document.layers[id].visibility="hide";
	else if (ventana.document.getElementById)
		ventana.document.getElementById(id).style.visibility="hidden";
}

// Funcion que compara dos fechas. Devuelve true si la primera es mayor o igual que la segunda
// y false en caso contrario
function comparaFecha(fecha1,fecha2) {
	datos1 = fecha1.split('/')
	datos2 = fecha2.split('/')

	fechaEntera1 = datos1[2] + datos1[1] + datos1[0]
	fechaEntera2 = datos2[2] + datos2[1] + datos2[0]
	fechaEntera1 = parseInt(fechaEntera1);
	fechaEntera2 = parseInt(fechaEntera2);

	return (fechaEntera1 >= fechaEntera2);
}

// Funci0n que compara dos fechas. Devuelve true si la primera es mayor que la segunda
// y false en caso contrario
function comparaFechaEstricto(fecha1,fecha2) {
	datos1 = fecha1.split('/')
	datos2 = fecha2.split('/')

	fechaEntera1 = datos1[2] + datos1[1] + datos1[0]
	fechaEntera2 = datos2[2] + datos2[1] + datos2[0]
	fechaEntera1 = parseInt(fechaEntera1);
	fechaEntera2 = parseInt(fechaEntera2);

	return (fechaEntera1 > fechaEntera2);
}

// Funcion que remplaza todas las ocurrencias de findStr en oldStr por repStr y devuelve la cadena resultante
function replaceAll(oldStr,findStr,repStr)
{
	var srchNdx = 0;	// srchNdx will keep track of where in the whole line
						// of oldStr are we searching.
	var newStr = "";	// newStr will hold the altered version of oldStr.
	while (oldStr.indexOf(findStr,srchNdx) != -1) {
	// As long as there are strings to replace, this loop
	// will run.
		newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
		// Put it all the unaltered text from one findStr to
		// the next findStr into newStr.
		newStr += repStr;
		// Instead of putting the old string, put in the
		// new string instead.
		srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
		// Now jump to the next chunk of text till the next findStr.
	}

	newStr += oldStr.substring(srchNdx,oldStr.length);
	// Put whatever's left into newStr.

	return newStr;
}

// funcion que copia los valores de un select multiple en un campo hidden
function copiarSelectMultipleEnHidden(campoSelect, campoHidden)
{
	var l = campoSelect.length;
	var valor = ""
	for(i = 0; i < l; i++) {
		if(campoSelect.options[i].selected) {
			valor = valor + campoSelect.options[i].value;
			if(i != l-1) {
				valor = valor + ";";
			}
		}
	}
	campoHidden.value = valor;
}

// funcion que copia los valores de un importe en un campo hidden
function copiarImporteEnHidden(campoEntero, campoDecimal, campoHidden)
{
	var valorEntero = campoEntero.value;
	var valorDecimal = "";
	if(campoDecimal.value != "") {
		valorDecimal = ","+campoDecimal.value;
	} else {
		valorDecimal = ",00";
	}

	var valor = valorEntero+valorDecimal;
	if(valor.charAt(0) == ',') {
		valor = "0"+valor;
	}
	campoHidden.value = valor;
}

function seleccionarTodos(nombreSelect)
{
	var select = document.getElementById(nombreSelect);
	var l = select.length;
	for(var i = 0; i < l; i ++) {
		select.options[i].selected = true;
	}
}

function deseleccionarTodos(nombreSelect)
{
	var select = document.getElementById(nombreSelect);
	var l = select.length;
	for(var i = 0; i < l; i ++) {
		select.options[i].selected = false;
	}
}

function cambiarTituloPagina(titulo) {

	var index = titulo.indexOf(" ");
	var primero = titulo;
	var resto = "";
	if(index != -1) {
		primero = titulo.substr(0, index);
		resto = titulo.substr(index, titulo.length);
	}

	window.document.getElementById("tituloPag").innerHTML="<font>" + primero + "</font>" + resto;
}

function inArray(arr, elem){
	// Returns true if the passed value is found in the array.  Returns false if it is not.

    var i;
    for (i=0; i < arr.length; i++) {
        // Coincidencias similares (== ), no identicas (===)
        if (arr[i] == elem) {
            return true;
        }
    }
    return false;

}


// funcion que copia los valores de un nif en un campo hidden
function copiarNifEnHidden(campoNumero, campoLetra, campoHidden)
{
	var valorNumero = campoNumero.value;
	var valorLetra = "";
	if(campoLetra.value != "") {
		valorLetra = campoLetra.value;
	}

	var valor = valorNumero+valorLetra;

	campoHidden.value = valor;
}


// funcion que copia los valores de un cif en un campo hidden
function copiarCifEnHidden(campoNumero, campoLetra, campoHidden)
{
	var valorNumero = campoNumero.value;
	var valorLetra = "";
	if(campoLetra.value != "") {
		valorLetra = campoLetra.value;
	}

	var valor = valorNumero+valorLetra;

	campoHidden.value = valor;
}


// funcion que copia los valores de los componentes en un  campo hidden
function copiarValoresComponenteEnHidden(nombreCampoHidden, campoHidden)
{

	var valor =  "id=" + document.getElementById('id_'+nombreCampoHidden).value +
				 "#nombre=" + document.getElementById('nombre_'+nombreCampoHidden).value +
				 "#apellido=" + document.getElementById('apellidos_'+nombreCampoHidden).value +
				 "#nif=" + document.getElementById('nif_'+nombreCampoHidden).value +
				 "#domicilio=" + document.getElementById('domicilio_'+nombreCampoHidden).value +
			     "#municipio=" +  document.getElementById('municipio_'+nombreCampoHidden).value +
			     "#provincia=" + document.getElementById('provincia_'+nombreCampoHidden).value +
			     "#codpostal=" + document.getElementById('codpostal_'+nombreCampoHidden).value +
			     "#telefono=" + document.getElementById('telefono_'+nombreCampoHidden).value;

	campoHidden.value = valor;
}

// funcion que copia los valores de los municipios en un  campo hidden
function copiarMunicipioEnHidden(nombreCampoHidden, campoHidden)
{
	nombre_provincia = obtenerNombreProvincia();

	var valor =  "municipio=" + document.getElementById(nombreCampoHidden+'municipio').value +
				 ";;provincia=" + document.getElementById(nombreCampoHidden+'provincia').value +
				 ";;cpostal=" + document.getElementById(nombreCampoHidden+'cpostal').value+
				 //";;nombre_provincia=" + document.getElementById(nombreCampoHidden+'provincia').text;
				 ";;nombre_provincia=" + nombre_provincia;

	campoHidden.value = valor;
}

// Funcion que devuelve la diferencia en dias de dos fechas
function diasDiferencia(fechaMenor, fechaMayor) {
	var fMenor = new Date(document.getElementById("anyo"+fechaMenor).value,document.getElementById("mes"+fechaMenor).value,document.getElementById("dia"+fechaMenor).value);
	var fMayor = new Date(document.getElementById("anyo"+fechaMayor).value,document.getElementById("mes"+fechaMayor).value,document.getElementById("dia"+fechaMayor).value);

	var ms1 = (fMayor.getTime())*1;
	var ms2 = (fMenor.getTime())*1;
	var dif = (ms1-ms2)/86400000;

	if(dif > 0)
		return dif;
	else
		return -1*dif;
}

var diasMes = new Array("31","28","31","30","31","30","31","31","30","31","30","31");

// Funci?n qu pone puntos en un elemento HTML
function ponerPuntos(elemento) {
	var valor = elemento.value;

	var arrAux = new Array();
	var aux = "";
	arrAux = valor.split(".");

	for(i = 0; i < arrAux.length; i ++) {
		aux = aux+arrAux[i];
	}

	valor = "";
	var cont = 0;
	for(i = aux.length - 1; i >= 0; i--) {
		cont++;
		valor = aux.charAt(i)+valor;
		if(cont%3 == 0 && i != 0) {
			valor = "." + valor;
		}
	}

	elemento.value = valor;
}


function bloquearTarea(idtarea)
{
	return true;
}

function desbloquearTarea(idtarea)
{

	return true;
}

/* Inhabilita sustituyendo el evento onclick por un alert.
 */
function inhabilitar_boton(boton, mensaje)
{
	boton.onclick = function() {
		if (mensaje != null) {
			alert(mensaje);
		}
	}
}

/* Establece el evento onclick a la funcion pasada como parámetro
 */
function habilitar_boton(boton, funcion) {
	boton.onclick = funcion;
}



/* Formatea un número como un importe con puntos de
 * millares y dos decimales
 */
function formateaImporte(num)
{
	num = num.toString().replace(/\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0, num.length-(4*i+3)) + '.' + num.substring(num.length-(4*i+3));

	return (((sign)?'':'-') + num + ',' + cents);
}

function formateaCampoImporte(campo)
{
	if (campo.value != "")
	{
		var textoCampo = campo.value.replace(/\./g,'').replace(',','.');
		var valor = eval(textoCampo);

		campo.value = formateaImporte(valor);
	}
}

function existeOpcion(valor, select) {
	var existe = false;
	var l = select.options.length;
	for(var i = 0; i < l && !existe; i++) {
		if(select.options[i].value == valor) {
			existe = true;
		}
	}

	return existe;
}
