
var whitespace = " \t\n\r";

function Fecha(dateStr){
	// Checks for the following valid date formats:
	// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
	// Also separates date into month, day, and year variables
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

	// To require a 4 digit year entry, use this line instead:
	// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

	var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null) {
		return false;
	}
	month = matchArray[3]; // parse date into variables
	day = matchArray[1];
	year = matchArray[4];

	if (month < 1 || month > 12) { // check month range
		alert("El mes debe estar entre 1 y 12.");
		return false;
	}

	if (day < 1 || day > 31) {
		alert("El día debe estar entre 1 y 31.");
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert("El mes "+month+" no tiene 31 dias!")
		return false
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			alert("Febrero de " + year + " no tiene " + day + " dias!");
			return false;
	   }
	}
	return true;  // date is valid
}

function EnBlanco(s){
	var i;

    // Is s empty?
    if (Vacio(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
	// Check that current character isn't whitespace.
	var c = s.charAt(i);

	if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

function Vacio(s){
	return ((s == null) || (s.length == 0))
}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

// función para manejar errores
// para usarla, incluir 'onerror=handleErr' en la pagina
function handleErr(msg,url,l)
{
   var txt = "There was an error on this page.\n\n";
   txt += "Error: " + msg + "\n";
   txt += "URL: " + url + "\n";
   txt += "Line: " + l + "\n\n";
   alert(txt);
   return true;
}


// Inicializa objeto ajax XMLHttpRequest
var peticion = false;

function iniciaAjax(numObj){
   eval("peticion" + numObj + " = false;");
   try {
      eval("peticion" + numObj + " = new XMLHttpRequest();");
   } catch (trymicrosoft) {
      try {
         eval("peticion" + numObj + " = new ActiveXObject('Msxml2.XMLHTTP');");
      } catch (othermicrosoft) {
         try {
            eval("peticion" + numObj + " = new ActiveXObject('Microsoft.XMLHTTP');");
         } catch (e) {
            alert("Error al inicializar objeto.\n" +e.description);
         }
      }
   }
}

//---------------------------------------------------------------------------
// Adaptar el nombre del fichero a los existentes
//  path = path del fichero terminado en /
//  fichero = nombre del fichero incluido la extension , pero sin path
// Notas: el fichero no puede terner mas de 1 punto (el de la extension)
//---------------------------------------------------------------------------
function AdaptaNombreFich(path, fichero)
{
   var fso = new ActiveXObject("Scripting.FileSystemObject");
   var partes;
   var nombre;
   var extension;
   var posic;
   var ind=0;
   var nomFich="";

   while (fso.FileExists(path + "\\" + fichero))
   {
     partes = fichero.split(".");
     //Obtenemos el nombre del fichero sin extension
     nombre = partes[0];
     //Obtenemos la extension
     extension = partes[1];
     //Obtenemos el numero si es que tiene
     posic = nombre.lastIndexOf("_");	//Encuentra la ultima ocurrencia
     if (posic >= 0)
     {
         partes = nombre.split("_");
         ind = partes[partes.length-1];
         parseInt(ind); //Si no es numerico devolvera un 0
         if (ind) //Es un numero mayor que 0 (no vamos a tener el caso xxx_0.ext). Tb se podria usar la funcion is_numeric()
         {
             nombre= nombre.substring(0, posic);
         }
         else
         {
             ind=0;
         }
     }
     if (ind==0)
     {
         ind=1;
     }
     else
     {
         ind++;
     }
     fichero = nombre + "_" + ind + "." + extension;
   }
   return fichero;
}

function volver(){
   history.go(document.referrer);
}

function abrirArchivoLocal(sRuta){
   try{
      window.open(sRuta);
   }
   catch(e){
      alert(e.description);
   }
}

// muestra el texto del mensaje y devuelve si hay que parar la ejecución por el error
function gestionErrores(x){
   var tipoError = x[0].childNodes[0].firstChild.nodeValue;
   var txtError = x[0].childNodes[1].firstChild.nodeValue;

   if (tipoError == 3){
      alert(txtError);
      return true;
   }else if (tipoError == 1){
      alert(txtError);
      return false;
   }else if (tipoError == 2){
      return !(confirm(txtError + " ¿Desea seguir con la ejecución?"));
   }
}

function abrirDocumento(ruta,idDocumentoEnviado){
   window.open(ruta);
   iniciaAjax("");
   peticion.onreadystatechange = function() {
     if (peticion.readyState == 4) {
         if (peticion.status != 200) {
            alert("El documento no ha podido ser marcado como leído.");
         }
     }
   }
   peticion.Open("POST", "/intranet/firma/p_marcarLeido.php", true);
   peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   peticion.send("idDocumentoEnviado=" + idDocumentoEnviado);
}

/***********************************************************************************
NOMBRE: abrirNotificacion
DESCRIPTION: abre una notificacion y la marca como leida
INPUT:
 idNotificacion: notificacion que se desea abrir
 bLeido: dice si está leída previamente, para no volver a marcar con fecha posterior
***********************************************************************************/
function abrirNotificacion(idNotificacion,bLeido,bCifrado){

    if (bCifrado){
        var sFicheroBase64 = getFicheroFromServer(idNotificacion,true,0);

        var datosCifrados = decryptFile(sFicheroBase64);
        if ( (datosCifrados!=null) && (datosCifrados!="") ){
            var strRuta = grabaArchivoTemporal(datosCifrados,idNotificacion);
            if (window.open(strRuta) && (bLeido==0)){
                marcarLecturaNotificacion(idNotificacion,bLeido,bCifrado);
            }
        }else{
            txtError = "No tiene permiso para acceder al archivo cifrado " + idNotificacion + '.';
            alert(txtError);
            registrarError(txtError);
        }
    }else{
        marcarLecturaNotificacion(idNotificacion,bLeido,bCifrado);
    }
}

function grabaArchivoTemporal(datosCifrados,idNotificacion){
    var strRuta;
    var xmlhttp2 = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp2.onreadystatechange = function(){
        if (xmlhttp2.readyState == 4) {
            if (xmlhttp2.status == 200) { // OK response
                strRuta = xmlhttp2.responseText;
            } else{
                txtError = "Error " + xmlhttp2.status + " desencriptando archivo.";
                alert(txtError);
                registrarError(txtError);
            }
        }
    };
    xmlhttp2.Open("POST", "/intranet/firma/descripto.php?idNotificacion="+idNotificacion, false);
    xmlhttp2.send(datosCifrados);
    return strRuta;
}


function marcarLecturaNotificacion(idNotificacion,bLeido,bCifrado){
    iniciaAjax("");
    peticion.onreadystatechange = function() {
        if (peticion.readyState == 4) {
            if (peticion.status != 200) {
                alert("El documento no ha podido ser marcado como leído.");
            }
            else{
                if(peticion.responseText=='OK'){
                    if(!bCifrado)
                        window.open(strRuta);
                    window.location.replace(window.location.href);
                } else if (peticion.responseText == "6"){
                    alert("Sesión expirada.  Introduzca de nuevo su usuario y contraseña.");
                    document.location.reload();
                } else {
                    txtError = 'Error abriendo documento.'+peticion.responseText;
                    alert(txtError);
                    registrarError(txtError);
                }
            }
        }
    }
    peticion.Open("POST", "/intranet/firma/p_marcarLeido.php", false);
    peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    peticion.send("esNotificacion=1&idDocumentoEnviado=" + idNotificacion + "&leido=" + bLeido + "&cifrado=" + bCifrado);
}

function registrarError(error){
   iniciaAjax("");
   peticion.open("POST", "/intranet/lib/ferrores.php", true);
   peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   peticion.send("errorJS=" + error);
}

// almacena el Certificado del firmante actua en un archivo .cer, en formato PEM en base64
function almacenaCertificado(sRuta,cert){
   var fso = new ActiveXObject("Scripting.FileSystemObject");
   var objStream = fso.OpenTextFile(calculaRuta(sRuta), ForWriting, true);
   objStream.Write('-----BEGIN CERTIFICATE-----\r\n'+cert+'-----END CERTIFICATE-----\r\n');
   objStream.Close();
}

// renombra el archivo .cer si existe uno anterior
function calculaRuta(sRuta){
   var fso = new ActiveXObject("Scripting.FileSystemObject");
   var i = 1;
   while (fso.FileExists(sRuta+'.'+i+'.cer')){
      i++;
   }
   return sRuta+'.'+i+'.cer';
}

// elimina los saltos de linea de una cadena
function eliminaSaltos(c){
   var entra=new Array('\n','\r');
   var sale =new Array('','');
   var oc=c;
   var nt=new String("");
   var nc;
   for(var q=0;q<oc.length;q++){
      nc=oc.charAt(q)
      for(var w=0;w<entra.length;w++){
         if(oc.charAt(q)==entra[w]){
            nc=sale[w];
            break;
         }
      }
      nt+=nc;
   }
   return nt;
   delete oc,nt;
}