//------------------------------------------------------------------------------
function AbrirEnVentana(url)
{
	window.location.href = url;
}
//------------------------------------------------------------------------------
function AbrirVentanaTarget(url, ancho, alto, target)
{
	if (ancho == null)
		ancho = 400;

	if (alto == null)
		alto = 300;

	if(ancho>=screen.width)
    ancho=screen.width*0.9;

	if(alto>=screen.height)
    alto=screen.height*0.9;

		window.open(url, target, 'toolbar=no, location=no, directories=no, status=no, scrollbars=auto, resizable=no, copyhistory=no, width=' + ancho + ', height=' + alto + ', top=0');
}
//-----------------------------------------------------------------------
	//Abrimos ventana modal pero con scroll
	function AbrirVentanaModalScroll(url, ancho, alto)
	{
		var lns4 = (document.layers)? true:false;
		var lie4 = (document.all)? true:false;

		if (ancho == null)
			ancho = 400;

		if (alto == null)
			alto = 300;

	      if (url.indexOf("?") >= 0)
        	   window.open(url+'&flotante=1', '_blank', 'toolbar=no, location=no, directories=no, status=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + ancho + ', height=' + alto + ', top=0, alwaysRaised=no');
	      else
        	   window.open(url+'?flotante=1', '_blank', 'toolbar=no, location=no, directories=no, status=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + ancho + ', height=' + alto + ', top=0, alwaysRaised=no');
	}
//------------------------------------------------------------------------------
function AbrirVentanaXY(url, ancho, alto, xPos, yPos)
{
	if (ancho == null)
		ancho = 400;

	if (alto == null)
		alto = 300;
	window.open(url, '_blank', 'toolbar=no, location=no, directories=no, status=no, scrollbars=no, resizable=no, copyhistory=no, width=' + ancho + ', height=' + alto + ', left=' + xPos + ',top=' + yPos);
}
//------------------------------------------------------------------------------
function AbrirVentana(url, ancho, alto)
{
	if (ancho == null)
		ancho = 400;

	if (alto == null)
		alto = 300;

	if(ancho>=screen.width)
    ancho=screen.width*0.9;

	if(alto>=screen.height)
    alto=screen.height*0.9;

		window.open(url, '_blank', 'toolbar=no, location=no, directories=no, status=no, scrollbars=auto, resizable=no, copyhistory=no, width=' + ancho + ', height=' + alto + ', top=0');
}
//------------------------------------------------------------------------------
function AbrirVentana2(url, ancho, alto)
{
	if (ancho == null)
		ancho = 400;

	if (alto == null)
		alto = 300;

	if(ancho>=screen.width)
    ancho=screen.width*0.9;

	if(alto>=screen.height)
    alto=screen.height*0.9;

	if (url.indexOf("?") >= 0)
		window.open(url + '&emergente=true', '_blank', 'toolbar=no, location=no, directories=no, status=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + ancho + ', height=' + alto + ', left=0, top=0');
	else
		window.open(url +'?emergente=true', '_blank', 'toolbar=no, location=no, directories=no, status=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + ancho + ', height=' + alto + ', left=0, top=0');
}
//------------------------------------------------------------------------------
function AbrirVentanaRedimensionable(url, ancho, alto)
{
	var url2 = UrlDecode(url);
	if (ancho == null)
		ancho = 400;

	if (alto == null)
		alto = 300;

	if(ancho>=screen.width)
    ancho=screen.width*0.9;

	if(alto>=screen.height)
    alto=screen.height*0.9;

	if (url2.indexOf("?") >= 0)
		window.open(url2 + '&emergente=true', '_blank', 'toolbar=no, location=no, directories=no, status=no, scrollbars=yes, resizable=yes, copyhistory=no, width=' + ancho + ', height=' + alto + ', left=0, top=0');
	else
		window.open(url2 +'?emergente=true', '_blank', 'toolbar=no, location=no, directories=no, status=no, scrollbars=yes, resizable=yes, copyhistory=no, width=' + ancho + ', height=' + alto + ', left=0, top=0');
}
//------------------------------------------------------------------------------
function Cerrar()
{
	self.close();
}
//------------------------------------------------------------------------------
function BorrarCampos()
{
	document.getElementById('formulario').reset();
	BorrarCamposVisiblesFormulario();
}
function Borrar()
{
  	document.getElementById('formulario').reset();
	BorrarCamposVisiblesFormulario();

}
//------------------------------------------------------------------------------
function BorrarCamposVisiblesFormulario()
{
	for (i = 0; i < document.getElementById('formulario').length; i++)
	{
		var elemento = document.getElementById('formulario').elements[i];
		if(elemento.type != 'hidden' && elemento.type != 'button')
		{	
			elemento.value= '';
              	if(elemento.type == 'checkbox')
                      	elemento.checked = false;
        }
	}
}
//------------------------------------------------------------------------------
function AnadirEnte(ventana,clase,cla_relacion,relacion)
{
	//alert('ventana: '+ventana+' clase: '+clase+' cla_relacion:' + cla_relacion +' relacion: '+relacion);
	document.getElementById('accion').value = 'leer';
	if(document.getElementById('cla_padre').value != null && document.getElementById('cla_padre').value != '')
	{
		document.getElementById('clase').value = document.getElementById('cla_padre').value;
	}
	if(ventana.indexOf("?") >= 0)
		AbrirVentana2(ventana+'&clase='+clase+'&cla_padre='+cla_relacion+'&mos_formulario='+true+'&relacion='+relacion,800,600);
	else
		AbrirVentana2(ventana+'?clase='+clase+'&cla_padre='+cla_relacion+'&mos_formulario='+true+'&relacion='+relacion,800,600);
}
//------------------------------------------------------------------------------

function ReplaceAll(string, caracter, caracterNuevo)
{
	var temp = "";
	string = '' + string;
	splitstring = string.split(caracter);
	for(i = 0; i < splitstring.length; i++)
		temp += splitstring[i]+caracterNuevo;
	return temp.substring(0,temp.length-1);
}


//------------------------------------------------------------------------------
function AnadirEnteEnVentana(ventana,clase,cla_relacion,relacion)
{
	if(document.getElementById('cla_padre').value != null && document.getElementById('cla_padre').value != '')
	{
		document.getElementById('clase').value = document.getElementById('cla_padre').value;
	}
	if(ventana.indexOf("?") >= 0)
		AbrirEnVentana(ventana+'&clase='+clase+'&cla_padre='+cla_relacion+'&mos_formulario='+true+'&relacion='+relacion);
	else
		AbrirEnVentana(ventana+'?clase='+clase+'&cla_padre='+cla_relacion+'&mos_formulario='+true+'&relacion='+relacion);
}
//------------------------------------------------------------------------------
function AsociarEnte(ventana,relacion)
{
  	if(document.getElementById('cla_padre').value != null && document.getElementById('cla_padre').value != '')
	{
		document.getElementById('clase').value = document.getElementById('cla_padre').value;
	}
	AbrirVentana2('busqueda_' + ventana+'&relacion='+relacion,500,500);
}
//------------------------------------------------------------------------------
function AsociarEnteEnVentana(ventana,relacion)
{
  	if(document.getElementById('cla_padre').value != null && document.getElementById('cla_padre').value != '')
	{
		document.getElementById('clase').value = document.getElementById('cla_padre').value;
	}
	AbrirEnVentana('busqueda_' + ventana+'&relacion='+relacion,500,500);
}
//------------------------------------------------------------------------------
function EliminarEnte(nom_ente, nom_input, cla_padre, paginacion)
{
	var elemento;
	var campo;
	var confirmar;
	campo = eval('document.formulario.' + nom_input);
	campo.value = '';

	for (i = 0; i < document.getElementById('formulario').length; i++)
	{
			elemento = document.getElementById('formulario').elements[i];
			//alert(elemento.name+' '+campo.name);
			if (elemento.name.length > campo.name.length)
			{
				if (elemento.name.substring(0, campo.name.length) == campo.name && elemento.checked)
					campo.value = campo.value + '/~/' + elemento.value;
			}
        }
        if (campo.value.length > 0)
        {
            		var mensaje;
			mensaje = '¿Está seguro de eliminar el(los) objeto(s)?';
			confirmar = confirm(mensaje);
			if (confirmar == true)
			{
				campo.value = campo.value.substring(3, campo.value.length);
				document.getElementById('accion').value = 'eliminar';
                                document.getElementById('clase').value = nom_ente;
                                document.getElementById('cla_padre').value = cla_padre;
				document.getElementById(nom_input).value = campo.value;
                                document.getElementById(paginacion).value = 0;
				document.formulario.submit();
			}
          }
          else
          {
          	alert('Debe seleccionar un objeto');
          }

}
//----------------------------------------------------------------------------------------
function AnadirEnteRelacionado( cod_ente, nom_ente, cla_relacion)
{
	window.opener.document.getElementById('cla_padre').value=window.opener.document.formulario.clase.value;
	window.opener.document.getElementById('clase').value=cla_relacion;
	window.opener.document.getElementById('accion').value='crear';
	window.opener.document.getElementById(nom_ente).value = cod_ente;
	if(window.opener.document.getElementById('fil_pintadas'+window.opener.document.getElementById('cla_lis_pintar').value)!=null)
		window.opener.document.getElementById('fil_pintadas'+window.opener.document.getElementById('cla_lis_pintar').value).value = 0;	
	window.opener.document.formulario.submit();
	self.close();

}
//----------------------------------------------------------------------------------------
function AnadirEnteRelacionadoVentanaPadre( cod_ente, nom_ente, cla_relacion)
{
	//alert('cod_ente:'+cod_ente+' ;nom_ente: '+nom_ente+' :cla_relacion: '+cla_relacion);
	document.getElementById('cla_padre').value=document.formulario.clase.value;
	document.getElementById('clase').value=cla_relacion;
	document.getElementById('accion').value='crear';
	document.getElementById(nom_ente).value = cod_ente;
	if(document.getElementById('fil_pintadas'+document.getElementById('cla_lis_pintar').value)!=null){
		document.getElementById('fil_pintadas'+document.getElementById('cla_lis_pintar').value).value = 0;
		}
	document.formulario.submit();
	//self.close();
    // alert ('clase ' + window.opener.document.getElementById('clase').value + ', cla_padre =' + window.opener.document.getElementById('cla_padre').value);
}
//------------------------------------------------------------------------------------------
function Paginacion(nom_input,val_input,accion)
{
	if(document.getElementById('cla_padre').value != null && document.getElementById('cla_padre').value != '')
	{
		document.getElementById('clase').value = document.getElementById('cla_padre').value;
	}
	window.document.getElementById('accion').value = accion;
	window.document.getElementById(nom_input).value=val_input;
	document.formulario.submit();
}
//------------------------------------------------------------------------------------------
function RellenarCampo(nom_campo,valor)
{
  var campo = window.document.getElementById(nom_campo);
  if(campo != null)
  {
  	if(campo.type.toString().indexOf('select') >= 0)
        {
          try{
        	campo.options[campo.length] = new Option(valor ,valor,true,true);
          }
          catch(error)
          {
            try
            {
              	var newOpt = document.createElement("option");
		newOpt.text = valor;
		newOpt.value= valor;
		campo.add(newOpt, campo.length);
            }
            catch(e)
            {
           	/*alert(e + e.name + e.message);
                alert(e.description);
                alert(e.toString());
                alert(e.number  & 0xffff);
                alert(e.prototype);*/
                alert('No se ha podido actualizar la lista, recarge la p?gina');
            }
          }
        }
        else
        {
        	campo.value = valor;
        }
  }
}

//------------------------------------------------------------------------------------------
function Visibilidad(obj, visible)
{
  //alert(obj);
//  if (document.all)
  //{
    if(visible)
    {
      obj.style.visibility = 'visible';
    }
    else
    {
      obj.style.visibility = 'hidden';
   }
/*  }
  else
  {
    if(visible)
    {
      obj.visibility = 'show';
    }
    else
    {
      obj.visibility = 'hide';
    }
  }*/
}
//-------------------------------------------------------------------------------------------
function UrlEncode(value)
	{
		var newvalue;
		newvalue = value;
		newvalue = Reemplazar(newvalue, "?", "%3F");
		newvalue = Reemplazar(newvalue, "=", "%3D");
		newvalue = Reemplazar(newvalue, "&", "%26");
		newvalue = Reemplazar(newvalue, "+", "%2B");
		newvalue = Reemplazar(newvalue, "<", "%3c");
		newvalue = Reemplazar(newvalue, ">", "%3e");
		newvalue = Reemplazar(newvalue, "/", "%2f");
		newvalue = Reemplazar(newvalue, ".", "%2e");
		newvalue = Reemplazar(newvalue, " ", "+");
		newvalue = Reemplazar(newvalue, "#", "%23");
        newvalue = Reemplazar(newvalue, "'", "%27");
		return newvalue;
	}

	function UrlDecode(value)
	{
		var newvalue;

		newvalue = value;
		newvalue = Reemplazar(newvalue, "%3F", "?");
		newvalue = Reemplazar(newvalue, "%3D", "=");
		newvalue = Reemplazar(newvalue, "%26", "&");
		newvalue = Reemplazar(newvalue, "%2B", "+");
		newvalue = Reemplazar(newvalue, "%3c", "<" );
		newvalue = Reemplazar(newvalue, "%3e", ">");
		newvalue = Reemplazar(newvalue, "%2f", "/");
        newvalue = Reemplazar(newvalue, "%27", "'");
		newvalue = Reemplazar(newvalue, "%2e", ".");
        newvalue = Reemplazar(newvalue, "+", " ");
        newvalue = Reemplazar(newvalue, "%2d", "-");


		return newvalue;
	}
//-------------------------------------------------------------
function Reemplazar(origen, reemplazar, reemplazo)
{
	var index;

	index = -1;
	resultado = origen;

	while ((index = resultado.indexOf(reemplazar, index)) > -1)
	{
		resultado = resultado.substring(0, index) + reemplazo + resultado.substring(index + reemplazar.length, resultado.length);
		index = index + reemplazo.length;
	}

	return resultado;
}
//--------------------------------------------------------------
function ObtenerCadenaAleatoria(longitud, extra, numero, minuscula, mayuscula, otra)
{
  var cadena = "";

  for (var i = 0; i < longitud; ++i)
  {
    cadena = cadena + ObtenerCaracterAleatorio(numero, minuscula, mayuscula, otra, extra);
  }

  return cadena;
}
//--------------------------------------------------------------
function ObtenerNumeroAleatorio(minimo, maximo)
{
  return (Math.floor(Math.random() * (maximo - minimo)) + minimo);
}
//--------------------------------------------------------------
function ObtenerCaracterAleatorio(numero, minuscula, mayuscula, otro, extra)
{
  var numeros = "0123456789";
  var letrasMinusculas = "abcdefghijklmnopqrstuvwxyz";
  var letrasMayusculas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var otras = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? ";
  var caracter = extra;

  if (numero == true)
    caracter += numeros;

  if (minuscula == true)
    caracter += letrasMinusculas;

  if (mayuscula == true)
    caracter += letrasMayusculas;

  if (otro == true)
    caracter += otras;

  return caracter.charAt(ObtenerNumeroAleatorio(0, caracter.length));
}
//--------------------------------------------------------------
function Volver()
{
  self.history.back();
}
//--------------------------------------------------------------
function VaciarCampo(nom_campo)
{
  window.document.getElementById(nom_campo).value = '';
}

//--------------------------------------------------------------
function ComprobarEsFloat(nom_campo)
{
	
	var i;
	var c;
	var numDec = 0;
	var s = document.getElementById(nom_campo).value;
	
	if (s.length == 0)
		return false;

	for (i = 0; i<s.length; i++){
      	c = s.charAt(i);
        if (!isDigit(c) && c !='.' && c !=',')
        {
			alert('El formato del campo es incorrecto');
			document.getElementById(nom_campo).value = '';
			return false;
		}
		else if(c=='.'||c==','){
			numDec++;
			
			if(numDec>1){
				alert('El formato del campo es incorrecto');
				document.getElementById(nom_campo).value = '';
				return false;
			}
		}
	}
	return true;	
}
//--------------------------------------------------------------
function ComprobarEsDigito(campo)
{
	var n = document.getElementById(campo).value;
	var nPuntos = 0;
	for(i=0;i<n.length;i++)
	if (!isDigit(n.charAt(i)))
	{
		alert('El valor introducido no es correcto. Introduzca digitos del 0 al 9.');
		document.getElementById(campo).value='';
		return false;	
	}
}
//--------------------------------------------------------------	
function isDigit(c)
{
	return((c >= "0")&&(c <= "9"));
}
//--------------------------------------------------------------	
function validarNif(n)
{
	var nifChars1 = "ABCDEFGHPQSKLXabcdefghpqsklx";
	var nifChars2 = "ABCDEFGHTabcdefght";
	var nifChars3 = "TRWAGMYFPDXBNJZSQVHLCKE";
	var i;
	var longitud;
	var cero = false;
	var ss = '';
	var s = '';

	for(i=0;i<n.length;i++)
		if (isDigit(n.charAt(i)) || isLetter(n.charAt(i)))
			s = s + n.charAt(i);

	for(i=0;i<s.length;i++)	{
		if(s.charAt(i) != '0' || cero){
			ss = ss + s.charAt(i);
			cero = true;
			}
		}

	s = ss;

	if(s.length==0) {
			return '';
		}
	if(s.length > 9) {
			return '';
		}

	for(i=1;i<s.length-2;i++)	{
		if(!isDigit(s.charAt(i))){
			return '';
			}
	}

	// Si el primero y el último son numeros, el formato no es correcto
	if((isDigit(s.charAt(0))) && (isDigit(s.charAt(s.length-1)))) {
		return '';
	}

	// Si el primero es un numero, el ultimo seguro que es una letra
	if(isDigit(s.charAt(0))) {
		// VALIDAR FORMATO #3
		baseStr = s.substring(0,s.length-1);
		letra=s.charAt(s.length-1);
		letra=letra.toUpperCase();
	} else {
		// VALIDAR FORMATO #2
		baseStr = s.substring(1,s.length);
		letra=s.charAt(0);
		letra=letra.toUpperCase();
	}

	if(!isInteger(baseStr)) { return false; }
	baseInt = parseInt(baseStr);
	indice = baseInt % 23;

	if(letra==nifChars3.charAt(indice)) {
		return baseStr+letra;
	} else {
		return '';
	}
}