/* Biblioteca de funciones en Javascript para la aplicación Juba en línea */

/*
	Function valida(cadena)

	Verifica que todos los caracteres en cadena sean válidos.
*/
function valida(cadena) {
	var resultado = cadena;
	var cbusca = "ñÑáéíóúÁÉÍÓÚü";
	var creemp = "nNaeiouAEIOUu";
	var nlon = cbusca.length;
	var npos = 0;
	while (npos < nlon) {
		var cbusca_char = cbusca.substring(npos, npos + 1);
		var creemp_char = creemp.substring(npos, npos + 1);
		var re = new RegExp(cbusca_char, "g")
		resultado = resultado.replace(re, creemp_char);
		npos = npos + 1;
	}
	return resultado;
}
/*
	Function validaoper(cadena)

	Verifica que todos los operadores en la cadena sean válidos.
	*+^& deben agregarse espacios antes y después
	.. y ... deben llevar espacios antes, entre y depués
	@ reemplazar por /( y )
*/
function validaoper(cadena) {
	var resultado = "";
	var cbusca = "*+^&.@"; /* Comandos en los que hay que agregar espacios */
	var creemp = "";
	var nlon = cadena.length;
	var npos = 0;
	var nres = 0;
	var nros = "0123456789";
	while (npos < nlon) {
		var cbusca_char = cadena.substring(npos, npos + 1);
		nres = cbusca.indexOf(cbusca_char);
		if (nres == 5) { /* @ */
			resultado = resultado + "/(";
			npos++;
			cbusca_char = cadena.substring(npos, npos + 1);
			while ((nros.indexOf(cbusca_char) != -1) && (npos < nlon)) {
				resultado = resultado + cbusca_char;
				npos++;
				cbusca_char = cadena.substring(npos, npos + 1);
			}
			resultado = resultado + ")";
			if ((cadena.charAt(npos+1) != " ") && (npos < nlon)) {
				resultado = resultado + " ";
			}
		} else {
			if (nres == 4) { /* art. e inc. */
				creemp = cadena.substring(npos-3,npos).toUpperCase();
				if ((creemp == "ART") || (creemp == "INC")) {
					nres = -1;
				}
			}
			if (nres != -1) {
				if ((cadena.charAt(npos - 1) != " ") && (resultado.charAt(resultado.length -1) != " ")) {
					resultado = resultado + " ";
				}
				resultado = resultado + cbusca_char;
				if (cadena.charAt(npos + 1) != " ") {
					resultado = resultado + " ";
				}
			} else {
				resultado = resultado + cbusca_char;
			}
			npos = npos + 1;
		}
	}
	/* Busca otros caracteres especiales */
	if (resultado.indexOf(" & ") != -1) {
		var re = new RegExp(" & ", "g")
		resultado = resultado.replace(re, " (F) ");
	}
	return resultado;
}
/*
	Function verifica(texto : objeto)

	Chequea que el valor del texto no sea nulo. Después verifica 
	que los caracteres sean válidos (llama a valida()).
*/
function verifica(texto) {
	if (texto.value == "")  {
	alert("Debe escribir primero la expresión de búsqueda.")
	return false;
	}
	else {
	texto.value = valida(texto.value);
	texto.value = validaoper(texto.value);
	return true;
	}
}

/*
	Function chequea

	Verifica que en la selección de términos del diccionario
	se halla indicado al menos uno
*/
function chequea() {
	var Retorna = 0;
	var I = 0;
	var Tope = document.forma1.elements.length;
        while (Tope > I) {
		if (document.forma1.elements[I].name == "a201") {
			if (document.forma1.elements[I].checked) {
				Retorna = 1;
			}
		}
		if (document.forma1.elements[I].name == "a204") {
			Retorna = 1
		}
		I++;
	}
	if (Retorna == 1) {
		return true;
	} else {
		alert("Para poder buscar debe seleccionar al menos una palabra.");
		return false;
	}
}
/*
	Function Sumario(forma : objeto)

	Solicita el ingreso de un sumario para buscar la página 
	donde se encuentre.
*/
function sumario(forma) {
	var resp = "";
	var res = true;
	var seite = 0;
	var perseite = 0;
	var top = 1;
	var temp = 0;
	

	resp = prompt("Ingrese el número de sumario a mostrar (de 1 a " + forma.a301.value + "):", "");
	while (resp.indexOf(" ") > -1) {
		temp = temp.substring(0, temp.indexOf(" ")) +
		  temp.substring(temp.indexOf(" ")+1, temp.length);
	}
	temp = parseInt(resp, 10);
	top = parseInt(forma.a301.value, 10)
	if ((temp >= 1) && (temp <= top)) {
		perseite = parseInt(forma.a209.value, 10);
		if ((temp % perseite) == 0) {
			temp = temp - perseite + 1;
		} else {
			temp = temp - (temp % perseite) + 1;
		}
		forma.a205.value = temp.toString();
		res = true;
	} else {
		alert("El valor ingresado no es válido");
		res = false;
	}

	return res;
}
/*
	MuestraDoc: abre una ventana popup y muestra el documento
*/
function muestradoc(organismo, archivo, dia, mes, anio, inter, consulta) {
	var cons = "/busqueda/prueba.asp?o=";
	cons = cons + organismo;
        cons = cons + "&i=" + inter;
        cons = cons + "&a=" + archivo + "&d=" + dia;
        cons = cons + "&m=" + mes + "&n=" + anio;
	cons = cons + "&c=" + consulta;
	win1 = window.open(cons, "Documento", "allwaysRaised=yes, dependent=yes, resizable=yes, scrollbars=yes, height=500, width=700"); 
	win1.focus();
}

/*
	Variables globales
*/
var slinea; /* Usado en preHistoria. */
/*
	PreHistoria: 
	Ordena variables ocultas en función del botón presionado en "búsquedas anteriores"
*/
function prehistoria() {
	var temp1, temp2;

	temp1 = eval("document.historia.a21" + slinea);
	temp2 = eval("document.historia.a201");
	Swap( temp1, temp2);

	temp1 = eval("document.historia.a22" + slinea);
	temp2 = eval("document.historia.a208");
	Swap( temp1, temp2);

	temp1 = eval("document.historia.a23" + slinea);
	temp2 = eval("document.historia.a261");
	Swap( temp1, temp2);

        var j = Number(slinea);
	for (var i = j; i > 0; i--) {
		j = i - 1;
		temp1 = eval("document.historia.a21" + i);
		temp2 = eval("document.historia.a21" + j);
		Swap( temp1, temp2);
		temp1 = eval("document.historia.a22" + i);
		temp2 = eval("document.historia.a22" + j);
		Swap( temp1, temp2);
		temp1 = eval("document.historia.a23" + i);
		temp2 = eval("document.historia.a23" + j);
		Swap( temp1, temp2)
	}

	return true;
} 
/*
	Swap
*/
function Swap(arg1, arg2) {
	var temp = arg1.value;
	arg1.value = arg2.value;
	arg2.value = temp;
}

/*
	Ayuda
	Despliega la ventana de ayuda tanto para juba como para fana.
*/
function Ayuda(donde) {
	if (donde == 'juba') {
		ayuda = window.open("/ayuda/frame.asp?prod="+donde,"ayuda","allwaysraised=yes,height=400,width=500,location=no,menubar=no,scrollbars=yes,toolbar=no");
//		ayuda = window.open("/ayuda/frame.asp?prod="+donde,"ayuda","allwaysraised=yes,dependent=yes,height=400,width=500,location=yes,menubar=no,scrollbars=yes,toolbar=no");
	} else {
		ayuda = window.open("/ayuda/frame.asp?prod="+donde,"ayuda","allwaysraised=yes,height=400,width=500,location=no,menubar=no,scrollbars=yes,toolbar=no");
//		ayuda = window.open("/ayuda/frame.asp?prod="+donde,"ayuda","allwaysraised=yes,dependent=yes,height=400,width=500,location=yes,menubar=no,scrollbars=yes,toolbar=no");
	}
	ayuda.focus();
}

/*
	ActualizaIngreso
	Desde la ventana de ayuda actualiza el dato pedido para buscar.
*/
function ActualizaIngreso() {
	var Tope = document.opciones.elements.length;
	var Texto = "";
	var I = 0;
        while (Tope > I) {
		if (document.opciones.elements[I].name == "a201") {
			if (document.opciones.elements[I].checked) {
				if (Texto.length == 0) {
					Texto = document.opciones.elements[I].value;
				} else {
					Texto = Texto + "+" + document.opciones.elements[I].value;
				}
			} 
		}
		I++;
	}
	if (Texto.length == 0) {
		alert("Debe seleccionar por lo menos una opción");
	} else {
		top.opener.document.ingreso.a201.value = Texto;
		top.close();
	}
}

/*
	Cambia
	En el formulario de navegación de juba, actualiza la próxima página.
*/
function cambia(cuanto) {
	var desplaz = ((typeof(cuanto)=="string") ? Number(cuanto) : cuanto); 
	var tope = Number(document.ira.a301.value); // Tope de sumarios
	var cant = Number(document.ira.a209.value); // Cantidad por página
	var resp = Number(document.ira.a205.value); // Próximo inicio
	tope = parseInt((tope - 1)/cant, 10)  * cant + 1;
	resp += desplaz;
	resp = ((resp < 1) ? 1 : resp);
	resp = ((resp > tope) ? tope : resp);
	document.ira.a205.value = resp.toString();
	return true;
}

/*
	porDefecto
	Pone el cursor en el diálogo de texto adecuado
	Usado en consulta.pft
*/
function porDefecto() {
	if (typeof(eval("document.ingreso.a201")) == "object") {
		document.ingreso.a201.focus();
	} else {
		if (typeof(eval("document.ingreso.a202")) == "object") {
			document.ingreso.a202.focus();
		} else {
			if (typeof(eval("document.ingreso.a252")) == "object") {
				document.ingreso.a252.focus();
			}
		}
	}
}


/*
    Funcion muestraSumario(nroSumario)
*/
function muestraSumario(nroSumario, base) {
	var texto = '/jubanuevo/elsum.is?q201=' + nroSumario + '&q208=' + base;
	win1 = window.open(texto, "Sumario", "menubar=yes,dependent=yes,scrollbars,height=300,width=600,screenX=0,screenY=0"); 
	win1.focus();
}


/*
	acumulaSumario
	Agrega un sumario a la lista de acumulados.
	Usado por integral.pft
*/
function acumulaSumario(unSumario) {
	if (acumulados.length > 0) {
		if (acumulados.indexOf(unSumario) < 0) {
			acumulados = acumulados + ';' + unSumario;
			alert("Fue acumulado el sumario " + unSumario);
		} else {
			alert("El sumario " + unSumario + " ya se encuentra entre los acumulados.");
		}
	} else {
		acumulados = unSumario;
		alert("Fue acumulado el sumario " + unSumario);
	}
}

/*

	muestraAcumulados
	Muestra los sumarios acumulados
	usado por integral.pft
*/
function muestraAcumulados() {
  if (acumulados != "")
  {
    var texto = '/busqueda/acumulados.asp?sumarios='+acumulados;
    win1 = window.open(texto, "Acumulados", "allwaysRaised=yes,location=yes,menubar=yes,dependent=yes,scrollbars,height=350,width=550,screenX=0,screenY=0"); 
    win1.focus();
  }
  else
  {
    alert("No hay sumarios acumulados!");
  }
}

/*
	borrarSumarios
	Borra alguno de los sumarios acumulados
*/
function borrarSumarios() 
{
}

/*
    Function marcaTodos()
*/
function marcarTodos(bMarca)
{
  var tope = document.actualiza.elements.length;
  var I = 0;
  while (tope > I)
  {
    document.actualiza.elements[I].checked = bMarca;
    I++;
  }
}

/*

*/
function verificaSumario()
{
  var tope = document.actualiza.elements.length;
  var I = 0;
  var marcado = FALSE;
  while (tope > I && !marcado)
  {
    marcado = document.actualiza.elements[I].checked;
    I++;
  }
  return marcado;
}

/*

  Nuevo JUBA

*/
function verificaSeleccion()
{
  var tope = document.voces.elements.length;
  var I = 0;
  var marcado = '';
  while (tope > I)
  {
    if (document.voces.elements[I].checked)
    {
      marcado = document.voces.elements[I].value;
      marcado = marcado.substr(0, marcado.search(" - "));
    }
    I++;
  }
  return marcado; 
}

/*

*/
function ingresarVoz(cual)
{
  if (cual == 1)
  {
    var temp = verificaSeleccion();
  }
  else
  {
    var temp = document.lista.a254.value;
    var tope = document.lista.elements.length;
    var I = 0;
    var marcado = '';
    while (tope > I)
    {
      if (document.lista.elements[I].checked)
      {
        marcado = (marcado.length > 0) ? marcado + " + " + document.lista.elements[I].value : document.lista.elements[I].value;
      }
      I++;
    }
    temp = (marcado.length > 0) ? "(" + temp + ") * (" + marcado + ")" : temp;
  }
  if (temp.length > 0)
  {
    re = new RegExp(/ and /gi);
    temp = temp.replace(re, " * ");
    if ( top.opener.document.ingreso.avanzada.value == 0 ) {
    top.opener.document.ingreso.a201.value = temp}
    else {
    top.opener.document.formulario.actual.value = temp};
    top.close();
  }
  else
  {
    alert("Debe seleccionar una VOZ");
  }
}

function verRelacionadas()
{
  var temp = verificaSeleccion();
  if (temp.length > 0)
  {
    document.movim.action = "/jubanuevo/despliega.is";

    var tope = document.voces.elements.length;
    var I = 0;
    var marcado = '';
    while (tope > I)
    {
      if (document.voces.elements[I].checked)
      {
        marcado = document.voces.elements[I].value;
        I += tope;
      }
      I++;
    }

    document.movim.a253.value = marcado.substr(marcado.search(" - ") + 3);
    document.movim.a254.value = marcado.substr(0, marcado.search(" - "));
    document.movim.submit();
  }
  else
  {
    alert("Debe seleccionar una VOZ");
  }
}

function verRelacionadas2()
{
  var temp = verificaSeleccion();
  if (temp.length > 0)
  {
    document.movim.action = "/fananuevo/despliega.is";

    var tope = document.voces.elements.length;
    var I = 0;
    var marcado = '';
    while (tope > I)
    {
      if (document.voces.elements[I].checked)
      {
        marcado = document.voces.elements[I].value;
        I += tope;
      }
      I++;
    }

    document.movim.a253.value = marcado.substr(marcado.search(" - ") + 3);
    document.movim.a254.value = marcado.substr(0, marcado.search(" - "));
    document.movim.submit();
  }
  else
  {
    alert("Debe seleccionar una VOZ");
  }
}

function desplaza(donde)
{
  var temp = '';
  document.movim.a254.value = donde;
  switch (donde) 
  {
    case '<<' :
      document.movim.a252.value = '';
      break;
    case '<' :
      document.movim.a252.value = document.voces.pri.value;
      break;
    case '>' :
      document.movim.a252.value = document.voces.ult.value;
      break;
    case '>>' :
      document.movim.a252.value = 'zzz';
      break;
  } 
  if (document.URL.search(/muestradicc.is/))
  {
    var tope = document.voces.elements.length;
    var I = 0;
    var marcado = '';
    while (tope > I)
    {
      if (document.voces.elements[I].checked)
      {
        marcado = (marcado.length > 0) ? marcado + " + " + document.voces.elements[I].value : document.voces.elements[I].value;
      }
      I++;
    }
    if (temp.length > 0)
    {
      temp = (marcado.length > 0) ? temp + " + " + marcado : temp;
    }
    else
    {
      temp = (marcado.length > 0) ? marcado : temp;
    }
    if (temp.length > 0)
    {
      temp = (document.movim.a398.value.length > 0) ? document.movim.a398.value + " + " + temp : temp;
    }
    else
    {
      temp = (document.movim.a398.value.length > 0) ? document.movim.a398.value : temp;
    }
    document.movim.a398.value = temp;
  }
  document.movim.submit();
}

function ingresarPalabras() 
{
  var temp = (document.movim.a398.value.length == 0) ? '' : document.movim.a398.value;
  var tope = document.voces.elements.length;
  var I = 0;
  var marcado = '';
  while (tope > I)
  {
    if (document.voces.elements[I].checked)
    {
      marcado = (marcado.length == 0) ? document.voces.elements[I].value : marcado + " + " + document.voces.elements[I].value;
    }
    I++;
  }
  if (marcado.length > 0)
  {
    temp = (temp.length == 0) ? marcado : temp + " + " + marcado; 
  }
  if (temp.length > 0)
  {
    re = new RegExp(/ or /gi);
    temp = temp.replace(re, " + ");
    if ( top.opener.document.ingreso.avanzada.value == 0 ) {
    top.opener.document.ingreso.a201.value = temp}
    else {
    top.opener.document.formulario.actual.value = temp};
    top.close();
  }
  else
  {
    alert('Vd. no señaló ninguna palabra.');
    return false;
  }
}

// Sets cookie values. Expiration date is optional
//
   function setCookie(name, value) {
   if (document.ingreso.a260.checked) {
   var expires = new Date()
   expires.setTime(expires.getTime() + 1000*60*60*24*365)
   document.cookie = name + "=" + escape(value) + 
     "; expires=" + expires.toGMTString();
  }
}

function getCookie(Name) {
   var search = Name + "="
   if (document.cookie.length > 0) { // if there are any cookies
      offset = document.cookie.indexOf(search) 
      if (offset != -1) { // if cookie exists 
         offset += search.length 
         // set index of beginning of value
         end = document.cookie.indexOf(";", offset) 
         // set index of end of cookie value
         if (end == -1) 
            end = document.cookie.length
         return unescape(document.cookie.substring(offset, end))
      } 
   }
   else
   {
     return '';
   }
}

function guardaAnt( busq, base, cant) {
  var temp = '';
  var a = new Array();
  var temp1 = busq + ";" + base + ";" + cant;
  temp = getCookie("Juba");
  if (typeof(temp) != "undefined") 
  {
     a = temp.split(':');
     var exito = false;
     for(var i = 0; i < a.length; i++)
     {
       if (a[i].toUpperCase() == temp1.toUpperCase())
       {
         exito = true;
       }
     }
     if (!exito)
     {
       temp = temp + ":" + temp1;
       setCookie("Juba", temp);
     }
  }
  else
  {
     temp = temp1;
     setCookie("Juba", temp);
  }
}

function recuperaAnt()
{
  var texto = "";
  var temp = getCookie("Juba");
  var a = new Array(); 
  var linea = new Array();
  texto += "<html>\n<head>\n";
  texto += "<link rel=\"stylesheet\" type=\"text/css\" href=\"/estilo.css\">\n";
  texto += "</head>\n<body onload=\"document.g.submit();\">\n<form name=\"g\" action=\"/jurisprudencia/juba/jn.asp\" method=\"post\">\n\n";
  if (typeof(temp) != "undefined") 
  {
    texto += "<input type=\"hidden\" name=\"ba\" value=\"" + temp + "\">\n";
    texto += "</form>\n</body>\n</html>\n";
    return texto;
  }
  else
  {
    alert("Las búsquedas anteriores fueron borradas o no existen.");
    return "";
  }
}

function muestraAnt()
{
  var texto = recuperaAnt();
  if (texto.length > 0)
  {
    newwin = window.open('',"", "width=600,height=400,status=yes,location=no,scrollbars=yes");
    newwin.document.write(texto);
    newwin.document.close();
    newwin.focus();
  }
}

function borraAnt()
{
  setCookie("Juba", '');
  alert("Todas las búsquedas fueron borrados.");
}

function verAnt()
{
  var temp = '';
  temp = getCookie("Juba");
  if (typeof(temp) != "undefined") 
  {
    document.verAnterior.ant.value = escape(temp);
    document.verAnterior.submit();
  }
  else
  {
    alert("No hay búsquedas anteriores");
  }
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
    obj.visibility=v; }
}

function mostrarcapa(abrecapa,datos1){
var elemento = document.getElementById(abrecapa); 
elemento.style.visibility = datos1;}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  nueva = window.open(theURL,winName,features);
  nueva.focus();
}

function MM_goToURL() { //v3.0
  var arrastre= document.ingreso.a201.value;
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+arrastre+"'");
}

function MM_busquedaAsistida (ande) {
  document.ingreso.a201.value = convertSpaces(document.ingreso.a201.value);
  var temp = (document.ingreso.a201.value.length > 0) ? "a201=" + document.ingreso.a201.value : "";
  if (document.ingreso.a260.checked)
  {
    temp = (temp.length > 0) ? temp + "&a260=s" : "a260=s";
  }
  temp = (temp.length > 0) ? "?" + temp + "&" : "";
  if (ande == 'tc') {
    MM_goToURL('self','/jurisprudencia/juba/busqueda3a.asp' + temp);
  } else {
    MM_goToURL('self','/jurisprudencia/juba/busqueda1a.asp' + temp);
  }
  return document.MM_returnValue
}

function MM_busquedaAsistida2 () {
  document.ingreso.a201.value = convertSpaces(document.ingreso.a201.value);
  var temp = (document.ingreso.a201.value.length > 0) ? "a201=" + document.ingreso.a201.value : "";
  if (document.ingreso.a260.checked)
  {
    temp = (temp.length > 0) ? temp + "&a260=s" : "a260=s";
  }
  temp = (temp.length > 0) ? "?" + temp + "&" : "";
  MM_goToURL('self','/jurisprudencia/juba/busqueda2a.asp' + temp);
  return document.MM_returnValue
}

function convertSpaces(str) {
var out = "", flag = 0;
for (i = 0; i < str.length; i++) 
{
  if (str.charAt(i) != " ") 
  {
    out += str.charAt(i);
    flag = 0;
  }
  else 
  {
    if(flag == 0) 
	{
      out += "";
      flag = 1;
    }
  }
}
return out;
}


