
function gInicio() {
	var sAux=top.location.href
	if (sAux!=this.parent.location.href) top.location.href=this.parent.location.href
	else {
		top.gT=top
		gT=top.gT
		gT.aZs=new Array(3)
		var nPos=sAux.indexOf('/',sAux.indexOf('//')+2)+1
		gT.sURL=sAux.substring(0,nPos)
		gT.sURLWeb=gT.sURL+'Web/'
		gT.sURLApp=gT.sURL+sAux.substring(nPos,sAux.indexOf('/',nPos)+1)
		gT.sURLSrvls=gT.sURLApp+'servlet/'
		gT.bZS=1
	}
}

function siCond(e,f,t) {
	eval('if (typeof '+e+'=="undefined") setTimeout("siCond(\''+e+'\',\''+f+'\','+t+')",'+t+');else{'+f+'}')
}

function esIdentificador(t) {
	return /^(\w+)$/.test(t)
}

function esNatural(t) {
	return /^(0|[1-9]\d*)$/.test(t)
}

function esReal(t) {
   return /^(0|[1-9]\d*)+[,.]+([0-9]\d*)$/.test(t)||/^(0|[1-9]\d*)$/.test(t)
}

function esImagen(t) {
	if (!(/^.*[\/\*\?"<>\|].*$/.test(t.toLowerCase())))
		return /^([a-z]:\\([^\\]+\\)*[^\\]+.(gif|jp[e]?g))$/.test(t.toLowerCase())
	return false
}

function esGIF(t) {
	return /(\.gif)$/.test(t.toLowerCase())
}

function esFecha(t) {
	if (/^((0?[1-9]|[12]\d|3[01])\/(0?[1-9]|1[012])\/\d{4})$/.test(t)) {
		var asPs=t.split(/\//)
		if (asPs[2]<1752 || asPs[2]>9999) return false
		if (asPs[1]==2 && (asPs[0]>29 || (asPs[0]==29 && !(asPs[2]%4==0 && (asPs[2]%100!=0 || asPs[2]%400==0))))) return false
		if ((asPs[1]==4 || asPs[1]==6 || asPs[1]==9 || asPs[1]==11) && asPs[0]>30) return false
		return true
	}
	return false
}

function aFecha(t) {
	if (esFecha(t)) {
	   var fecha= new Date()
		var asPs=t.split(/\//)
		if (asPs.length>0){
		  fecha.setFullYear(asPs[2],eval(asPs[1]+'-1'),asPs[0]);
		  fecha.setHours(23)
		  fecha.setMinutes(59)
		  fecha.setSeconds(59)
		 return  fecha
//		 eval('new Date('++','++','++',23,59,59)')
	    }
	}
	else return null
}

// Retorna un objeto de tipo Date a partir de los parámetros fecha y hora.
//la fecha debe tener el formato dd/mm/aaaa ó dd\mm\aaaa y la hora hh:mm o hh:mm:ss
function aFechaHoraMinuto(fecha, hora) {
	if (esFecha(fecha) && esHora(hora)) {
	    var fechaNueva= new Date()
		var asPs=fecha.split(/\//)
		var asPh=hora.split(":")
		if (asPs.length>0 && asPh.length>0){
          fechaNueva.setFullYear(asPs[2],eval(asPs[1]+'-1'),asPs[0]);
		  fechaNueva.setHours(asPh[0])
		  fechaNueva.setMinutes(asPh[1])
		  //si vienen los segundos (hh:mm:ss) se ponen los que vienen, sino se ponen por defecto 59
		  if(hora.length==8 && asPh[2]!=undefined) fechaNueva.setSeconds(asPh[2])
		  else fechaNueva.setSeconds(59)
		 return  fechaNueva
//		return eval('new Date('+asPs[2]+','+eval(asPs[1]+'-1')+','+asPs[0]+','+asPh[0]+','+asPh[1]+',59)')
		}
	}
	else return null
}

function esHora(h)
{
  if(h.length==8 && /^(0[0-9]|1\d|2[0-3]):([0-5]\d):([0-5]\d)$/.test(h))
  {//si viene en formato hh:mm:ss
    return true
  }
  else if (h.length==5 && /^(0[0-9]|1\d|2[0-3]):([0-5]\d)$/.test(h))
  {//si viene en formato hh:mm
		return true
	}
    	return false
}

function nChequeados(c) {
	var nCs=0
	if (eval('typeof '+c+'!="undefined"')) {
		if (eval('typeof '+c+'.length=="undefined"')) {
			if (eval(c+'.checked')) nCs=1
		}
		else {
			var nL=eval(c+'.length')
			for (var i=0;i<nL;i++) if (eval(c+'[i].checked')) nCs++
		}
	}
	return nCs
}

function saCheckboxes(c,v) {
	if (eval('typeof '+c+'!="undefined"'))
		if (eval('typeof '+c+'.length=="undefined"')) eval(c+'.checked='+v)
		else {
			var nL=eval(c+'.length')
			for (var i=0;i<nL;i++) eval(c+'[i].checked='+v)
		}
}

String.prototype.trim=function() {
	var i=0
	var j=this.length-1
	while (i<this.length && (this.charAt(i)==' ' || this.charCodeAt(i)==10 || this.charCodeAt(i)==13)) i++
	while (j>i && (this.charAt(j)==' ' || this.charCodeAt(j)==10 || this.charCodeAt(j)==13)) j--
	if (j>=i) return this.substring(i,j+1)
	return ''
}

Array.prototype.contains=function(element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
}

function addElemento (etiqueta, valor, elemento)
{
    var optionNuevo = new Option(etiqueta, valor)
    elemento.options[elemento.length] = optionNuevo
}

function addElemento (etiqueta, valor, elemento, bObsoleto)
{
    var optionNuevo = new Option(etiqueta, valor)
    elemento.options[elemento.length] = optionNuevo
    if(bObsoleto==1) optionNuevo.className='obsoleto'
}

function removeElements (elemento)
{
    for (i=0; i<elemento.length; i++)      {
       elemento.options[i] = null
       i--;
    }
}

function lopd(u)
{
window.open(u,'Lopd','width=371,height=380,resizable = yes')
}

function ayuda(u)
{
window.open(u,'Ayuda','width=486,height=350,scrollbars = yes,resizable = yes')
}

function ayuda2(u, w, h)
{
window.open(u,'Ayuda','width='+w+',height='+h+', scrollbars = yes, resizable = yes')
}

function ayudaInicial(u, w, h)
{
window.open(u,'Ayuda','width='+w+',height='+h+', scrollbars = yes,resizable = yes,top=10')
}

function formateaFecha( input ){
    fecha = input.value
    if(!esFecha(fecha))
        if(fecha.length == 8){
            var fechaBarras=fecha.substr(0,2)+'/'+fecha.substr(2,2)+'/'+fecha.substr(4,4)
            if(esFecha(fechaBarras))
                input.value=fechaBarras
        } else if(fecha.length == 4){
            var fechaBarras='01/01/'+fecha
            if(esFecha(fechaBarras))
                input.value=fechaBarras
        }
   return fecha
}

function confirmaSalir() {

    if(confirm('Está a punto de cerrar la ventana. ¿Desea continuar?')) {
        var ventana = top.self
        ventana.opener = top.self
        ventana.close()
    } else {
        history.go(0)
    }

}


function setValue(sNombre, sValor) {
    if(eval("Frm." + sNombre + ".disabled != false")) eval("Frm." + sNombre + ".disabled = false")
    eval("Frm." + sNombre + ".value = \"" + sValor + "\"")
}


/**
* completa un texto hasta el tamaño especificado.
* Parámetros:
* cadena: Texto origen
* caracterRelleno: el caracter que se usará de relleno
* longitudTotal: longitud a alcanzar por el texto
* detras: si es true añade detrás, sino añade delante
* Si la longitud que se pide es menor que el texto, lo retorna tal cual
*/
function completarTexto(cadena, caracterRelleno, longitudTotal, detras)
    {
        var resultado=''
        j = cadena.length
        if(j < longitudTotal)
        {
             k = parseInt(longitudTotal) - parseInt(j);
            if(detras)
            {
                resultado=cadena
                for( l = 0; l < k; l++)
                    resultado+=caracterRelleno;

            } else
            {
                for( i1 = 0; i1 < k; i1++)
                    resultado+=caracterRelleno;

                resultado+=cadena
            }
            return resultado
        } else
        {
            return cadena;
        }
    }


/**
*  Quita ceros delante para poder validar el número con la función esNatural
*
*
**/
function quitarCerosDelante(valorElemento)
{
  var hayCaracteres= valorElemento.length>0?true:false;
  var comienzaPorCero= valorElemento.charAt(0) == '0'?true:false;
  while(hayCaracteres && comienzaPorCero)
    {
      valorElemento = valorElemento.substring(1, valorElemento.length)
      hayCaracteres= valorElemento.length>0?true:false;
      comienzaPorCero= valorElemento.charAt(0) == '0'?true:false;
    }
  return valorElemento
}

function checkemail(e)
{
	ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";

	for(i=0; i < e.length ;i++){
		if(ok.indexOf(e.charAt(i))<0){
			return (false);
		}
	}

	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(e))
   return (true)
  else
   return (false);

}


/***********************************************
* Textarea Maxlength script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
//es para los textareas
function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}


// Funciones para comprobar la validez de los datos introducidos en las pantallas de detalle de CV

// Comprueba si el campo cuyo nombre se pasa como parámetro cumple el tipo de comprobación que se pasa como 2º parámetro
//El parámetro "Campo" será el nombre del nodo del Campos XML o nombre de la tabla CV_A_CAMPOS ("FK_SOCIEDAD")
//El parámetro "tipoComprobacion" será: 0 - > para campos de texto libre; 1 -> números enteros; 2 -> números reales; 3 -> Cualquier tipo de Fecha; 4 -> Fechas que no pueden ser futuras
function compruebaValor(Campo, tipoComprobacion)
{
     if(document.getElementById(Names[Campo]) != undefined){

        if (tipoComprobacion == 0 )
        {//si tipo es de texto (0) se mira si supera la longitud máxima (atributo maxlength). Esto no debería suceder nunca ya que el navegador no deja escribir más que el maxlength, pero por si acaso...
            if(document.getElementById(Names[Campo]).maxlength != undefined && document.getElementById(Names[Campo]).value.trim().length > document.getElementById(Names[Campo]).maxlength )
            {
                document.getElementById(Names[Campo]).focus();
                alert(getMensajeValorInvalido(Campo, tipoComprobacion));
                return false;
            }
        }else if (tipoComprobacion == 1 &&
            document.getElementById(Names[Campo]).disabled == false &&
            document.getElementById(Names[Campo]).value.length>0
           )
           {//si es tipo número natural, se mira si es un número natural.
             if(!esNatural(document.getElementById(Names[Campo]).value))
             {
                document.getElementById(Names[Campo]).focus();
                alert(getMensajeValorInvalido(Campo, tipoComprobacion));
                return false;
             }else if(document.getElementById(Names[Campo]).min_value != undefined &&
                      (parseInt(document.getElementById(Names[Campo]).value) < parseInt(document.getElementById(Names[Campo]).min_value))
                      )
             {//se comprueba el valor mínimo
                document.getElementById(Names[Campo]).focus();
                alert(getMensajeErrorValorMin(Campo,document.getElementById(Names[Campo]).min_value));
                return false;
             }
             else if(document.getElementById(Names[Campo]).max_value != undefined
                     && (parseInt(document.getElementById(Names[Campo]).value) > parseInt(document.getElementById(Names[Campo]).max_value))
                     )
             {//se comprueba el valor máximo
                document.getElementById(Names[Campo]).focus();
                alert(getMensajeErrorValorMax(Campo,document.getElementById(Names[Campo]).max_value));
                return false;
             }
           }else if (tipoComprobacion == 2 &&
            document.getElementById(Names[Campo]).disabled == false &&
            document.getElementById(Names[Campo]).value.length>0
           )
           {//si es tipo número real, se mira si es un número real.
            document.getElementById(Names[Campo]).value = document.getElementById(Names[Campo]).value.replace(',','.')
             if(!esReal(document.getElementById(Names[Campo]).value))
             {
                document.getElementById(Names[Campo]).focus();
                alert(getMensajeValorInvalido(Campo, tipoComprobacion));
                return false;
             }else if(document.getElementById(Names[Campo]).min_value != undefined
                      && (parseFloat(document.getElementById(Names[Campo]).value) < parseFloat(document.getElementById(Names[Campo]).min_value))
                      )
             {//se comprueba el valor mínimo


                document.getElementById(Names[Campo]).focus();
                alert(getMensajeErrorValorMin(Campo,document.getElementById(Names[Campo]).min_value));
                return false;
             }
             else if(document.getElementById(Names[Campo]).max_value != undefined
                    && (parseFloat(document.getElementById(Names[Campo]).value) > parseFloat(document.getElementById(Names[Campo]).max_value))
                    )
             {//se comprueba el valor máximo
                document.getElementById(Names[Campo]).focus();
                alert(getMensajeErrorValorMax(Campo,document.getElementById(Names[Campo]).max_value));
                return false;
             }

           }else if (tipoComprobacion == 3 &&
            document.getElementById(Names[Campo]).disabled == false &&
            document.getElementById(Names[Campo]).value.length>0 &&
            !esFecha(document.getElementById(Names[Campo]).value)
           )
           {//si es tipo fecha, se mira si es una fecha válida.
             document.getElementById(Names[Campo]).focus();
             alert(getMensajeValorInvalido(Campo, tipoComprobacion));
             return false;
           }else if (tipoComprobacion == 4 &&
            document.getElementById(Names[Campo]).disabled == false &&
            document.getElementById(Names[Campo]).value.length>0 &&
            (!esFecha(document.getElementById(Names[Campo]).value) ||
            (esFecha(document.getElementById(Names[Campo]).value) &&
            (aFecha(document.getElementById(Names[Campo]).value) > new Date())))
           )
           {//si es tipo fecha, se mira si es una fecha futura.
             document.getElementById(Names[Campo]).focus();
             alert(getMensajeValorInvalido(Campo, tipoComprobacion));
             return false;
           }else return true;
    }else return true;       
}

//Retorna un mensaje según el Campo y el tipo de comprobación.
//El parámetro "Campo" será el nombre del nodo del Campos XML o nombre de la tabla CV_A_CAMPOS ("FK_SOCIEDAD")
//El parámetro "tipoComprobacion" será: 0 - > para campos de texto libre; 1 -> números enteros; 2 -> números reales; 3 -> Cualquier tipo de Fecha; 4 -> Fechas que no pueden ser futuras
function getMensajeValorInvalido(nombreCampo, nTipoError)
{

   if(nTipoError==0)
  {
    return 'El campo '+Descripciones[nombreCampo]+' no debe exceder los'+document.getElementById(Names[nombreCampo]).maxlength+' caracteres.'
  }else if(nTipoError==1)
  {
    return 'El campo '+Descripciones[nombreCampo]+' debe ser un número natural.'
  }else if(nTipoError==2)
  {
    return 'El campo '+Descripciones[nombreCampo]+' debe ser un número real.'
  }else if(nTipoError==3)
  {
    return 'El campo '+Descripciones[nombreCampo]+' debe ser una fecha válida.'
  }else if(nTipoError==4)
  {
    return Descripciones[nombreCampo]+' debe ser una fecha válida y no puede ser una fecha posterior a la actual.'
  }

}


function getMensajeErrorValorMin(nombreCampo,valor)
{
    return 'El valor mínimo para el campo '+Descripciones[nombreCampo]+' debe ser '+valor
}

function getMensajeErrorValorMax(nombreCampo,valor)
{
    return 'El valor máximo para el campo '+Descripciones[nombreCampo]+' debe ser '+valor
}

//función que se usa para volver al listado desde las páginas de detalle del CV.
//Requiere que la página de Listado a la que se va se llame siempre Listado.jsp y se encuentre en la misma ruta,
//así como tener un hidden llamado "sVisualizar" con valor "true" (si se ha entrado en modo visualizar) y "false" si se ha entrado en modo editar
function atras()  {
    if (document.getElementById('sVisualizar').value != "true") {
    	if (confirm('¿Desea cambiar de pantalla sin guardar los cambios?')) {
		    	document.Frm.action='Listado.jsp'
		    	document.Frm.submit()
      }
	} else {

		    	document.Frm.action='Listado.jsp'
		    	document.Frm.submit()
	}
}


function realizar() {
        realizar('')
}

function realizar(sAcciones) {
        if (confirm('¿Desea guardar los cambios antes de cambiar de pantalla?'))
        {
	        if (sAcciones != undefined && sAcciones.length>0) eval(sAcciones)
	        document.Frm.submit()
	        }
}

