function cert_click(ref) {
  //alert(ref.id);
  var s=new String(ref.id);
  //alert(s.lastIndexOf("_"));
  var n_s=s.substring(s.lastIndexOf("_")+1,s.length);
  var n=parseInt(n_s,10);
  var pref=s.substring(0,s.lastIndexOf("_"));
  if (!window.signers) {
    window.signers=new Object();
  }
  if (window.signers[pref]) {
    document.getElementById("info_"+pref+"_"+window.signers[pref]).style.display="none"; 
    document.getElementById(pref+"_"+window.signers[pref]).style.borderWidth=0;
    document.getElementById(pref+"_"+window.signers[pref]).style.backgroundColor="transparent";
    document.getElementById(pref+"_"+window.signers[pref]).style.color="#000000";
  }
  //alert("Mostrando info_"+pref+"_"+n);
  document.getElementById("info_"+pref+"_"+n).style.display="block"; 
  document.getElementById(pref+"_"+n).style.borderWidth=1;
  document.getElementById(pref+"_"+n).style.backgroundColor="#000080";
  document.getElementById(pref+"_"+n).style.color="#FFFFFF";
  window.signers[pref]=n;
  
  //alert(n);
  //alert(pref);
}

function ver_cadena(lnk,ref) {
  if (!window.cadena_status) {
    window.cadena_status=new Object();
  }
  if (!window.cadena_status[ref]) {
    window.cadena_status[ref]=0;
  }
  var cad=new String(lnk.innerHTML);
  var ndisplay="";
  if (window.cadena_status[ref]==0) {
    window.cadena_status[ref]=1;
    cad=cad.replace(/Ver/,"Ocultar");
    ndisplay="block";
  } else {
    window.cadena_status[ref]=0;
    cad=cad.replace(/Ocultar/,"Ver");
    ndisplay="none";
  }
  document.getElementById(ref).style.display=ndisplay;
  lnk.innerHTML=cad;
  return false;
}

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function reevaluate(url) {
  document.getElementById("submit_reevaluate").disabled=true;
  document.getElementById("loading").style.display="block";
  var http=new XMLHttpRequest();
  http.open("GET","/cgi-bin/verificadorfirma/reevaluate.php?url="+escape(url)+
            "&amp;rand="+Math.random());
  http.onreadystatechange=function() {
    if (http.readyState==4) {
      document.getElementById("loading").style.display="none";
      //alert("Cargó");
      //alert(http.responseText);
      try {
      data=JSON.decode(http.responseText);
      //alert(dump(data));
      hash_bin_v=new String(document.getElementById("hash_bin").innerHTML);
      coincidente_v=0;
      if ((hash_bin_v==data["hashes"]["md5"])
          ||(hash_bin_v==data["hashes"]["sha1"])) {
        coincidente_v=1;
      }
      document.getElementById("namefile").innerHTML=data["name"];
      document.getElementById("namefile2").innerHTML=data["name"];
      hash_alg_v=new String(document.getElementById("hash_alg").innerHTML);
      hash_alg_v=hash_alg_v.toLowerCase();
      if (data["hashes"][hash_alg_v]!='') {
        document.getElementById("hash_file_bin").innerHTML=data["hashes"][hash_alg_v];

      }
      if (data["hashes"][hash_alg_v+"_b64"]!='') {
        document.getElementById("hash_file_b64").innerHTML=data["hashes"][hash_alg_v+"_b64"];

      }
      if (coincidente_v) {
        document.getElementById("no_coincidente").style.display="none";
        document.getElementById("coincidente").style.display="block";
      } else {
        document.getElementById("coincidente").style.display="none";
        document.getElementById("no_coincidente").style.display="block";
      }
      document.getElementById("warn_cached").style.display="none";
      alert("La comprobación ha finalizado.\nLos datos se han actualizado según los archivos disponibles en la red.");
      } catch (e) {
      alert(e);
      alert(http.responseText);
      alert("Hubo algún problema en la obtención de los datos actualizados.");

      }
    }
  }
  http.send(null);

  //alert("reevaluate");
}

function is_numeric (mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') 
             && mixed_var !== '' && !isNaN(mixed_var);
}

function revocation(rev,name) {
  for ( var i in rev ) {
    rev[i]['status']=new Object();
    rev[i]['status']['crlnode']=-1;
  }
  this.rev=rev;
  this.name=name;
  this.selfbutton=document.getElementById("crl_button_"+name);
  this.selfbutton.disabled=true;
  this.info_div=document.getElementById("crl_status_info_"+name);
  this.info_div.style.display="block";
  this.start=function () {
    //alert("Comenzando");
    this.position=1;
    this.crl_pos=0;
    this.nextstep();
  }

  this.end=function () {
      this.selfbutton.disabled=false;
      for (var i in this.rev) {
        if (!is_numeric(i)) continue;
        var position=parseInt(i,10);
        var rev=this.rev[position];

        var has_good=false;
        var has_unknown=false;
        var has_revoked=false;
        var time_revoked='';

        for (var i2 in rev["crl"]) {
          if (!is_numeric(i2)) continue;
          var crl_pos=parseInt(i2,10);
          var crl=this.rev[position]["crl"][crl_pos];
          if (crl['result']) {
            if (crl['result']['status']=="REVOKED") {
              has_revoked=true;
              time_revoked=crl['result']['time'];
            } else
            if (crl['result']['status']=="UNKNOWN") {
              has_unknown=true;
            } else
            if (crl['result']['status']=="GOOD") {
              has_good=true;
            }
          }
        }
        /* **************************************** 
           Código de evaluación para un certificado 
           **************************************** */
        rev["result"]=new Object();
        if (has_revoked) {
          rev["result"]["status"]="REVOKED";
          rev["result"]["time"]=time_revoked;
        } else 
        if (has_good) {
          rev["result"]["status"]="GOOD";
        } else
        if (has_unknown) {
          rev["result"]["status"]="UNKNOWN";
        } else {
          rev["result"]["status"]="NOT_CRL";
        }
      }
      var has_good=false;
      var has_unknown=false;
      var has_revoked=false;
      var has_not=false;
      var cert_good=false;
      var cert_unknown=false;
      var cert_revoked=false;
      var cert_not=false;
      var time_revoked='';
      for (var i in this.rev) {
        if (!is_numeric(i)) {
           continue;
        }
        var position=parseInt(i,10);
        var rev=this.rev[position];
        var status=rev["result"]["status"];
        if (status=="REVOKED") {
          has_revoked=true;
        } else if (status=="UNKNOWN") {
          has_unknown=true;
        } else if (status=="GOOD") {
          has_good=true;
        } else if (status=="NOT_CRL") {
          has_not=true;
        }
        if (position==1) {
          cert_revoked=has_revoked;
          cert_good=has_good;
          cert_unknown=has_unknown;
          cert_not=has_not;
        }
        if (cert_revoked) break;
      }

      /* ***********************************************************
         Ya dispongo de toda la información. Ahora las conclusiones.
         *********************************************************** */
      var mode;
      if (cert_revoked) {
        mode="alert";
      } else if (has_revoked) {
        mode="warning";
      } else if (cert_unknown) {
        mode="warning";
      } else if (has_unknown) {
        mode="ok_q";
      } else if (cert_not) {
        mode="ok_q";
      } else  {
        mode="ok";
      }
      //alert(dump(this.rev));
      //alert(mode);
      var anuncio="";
      if (cert_revoked) {
        anuncio="El certificado del firmante ha sido revocado<br />";
      } else {
        if (cert_unknown) {
          anuncio="La comprobación del certificado del firmante no ha podido realizarse en este momento.<br/>";
        } else if (cert_not) {
          anuncio="El certificado del firmante no dispone de mecanismos de comprobación de estado en línea.<br/>";
        }
        if (has_revoked) {
          anuncio+="Algunos certificados de la cadena ha sido revocado<br/>";
        }
        if (has_unknown&&!cert_unknown) {
          anuncio+="No se ha podido realizar la comprobación de algunos certificados de la cadena en este momento.<br/>";
        }
        if (mode=="ok") {
          anuncio="La comprobación en linea es correcta.<br/>";
        }
      }
      //document.getElementById("crl_info_"+this.name).style.display="block";
      //document.getElementById("crl_info_img_"+this.name).innerHTML=
      //     '<img src="/cgi-bin/verificadorfirma/img/'+mode+'.gif" />';
      document.getElementById("crl_info_data_"+this.name).innerHTML=
           anuncio;
      document.getElementById("crl_info_"+this.name).className=mode;
      document.getElementById("crl_status_"+this.name).style.display="none";
      //alert("Se acabó");
  }

  this.nextstep=function () {
    if (this.rev[this.position] !== undefined) { 
      //alert(dump(this.rev[this.position]));
      if (this.rev[this.position]["crl"][this.crl_pos]!==undefined) {
        this.step();
      } else {
        this.crl_pos=0; this.position++;
        this.nextstep();
      }
    } else {
      this.end();
    }
  }

  function rawurlencode (str) {
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
   }

  this.step=function () {
    //alert("Estamos en el certificado "+this.rev[this.position]["name"]+
    //      " y vamos a comprobar la lista "+dump(this.rev[this.position]["crl"][this.crl_pos]));
    var http=new XMLHttpRequest();
    var params="";
    var rev=this.rev[this.position];
    var crl=this.rev[this.position]["crl"][this.crl_pos];
    this.info_div.innerHTML="Comprobando revocación para '"+
          rev["name"]+"'.<br/>Conectando por "+
          crl["type"]+" a '"+
          crl["value"]+"'";
    //alert(dump(rev));
    //alert(dump(crl));
    params+="sn="+rawurlencode(rev["sn"]);
    params+="&issuer="+rawurlencode(rev["issuer"]);
    params+="&key="+rawurlencode(rev["key"]);
    params+="&alg="+rawurlencode(rev["alg"]);
    params+="&type="+rawurlencode(crl["type"]);
    params+="&protocol="+rawurlencode(crl["protocol"]);
    params+="&uri="+rawurlencode(crl["value"]);
    http.open("POST","/cgi-bin/verificadorfirma/check_crl.php");
    try {
     http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     http.setRequestHeader("Content-length", params.length);
     http.setRequestHeader("Connection", "close");
    } catch (e) {

    }
    var ref=this;
    http.onreadystatechange=function() {
      if (http.readyState==4) {
        //document.getElementById("loading").style.display="none";
        try {
          data=JSON.decode(http.responseText);
          // TODO:
          //alert(dump(data));
          pass=false;
          ref.rev[ref.position]["crl"][ref.crl_pos]["result"]=data;
          try {
            if (data&&(data["status"]=="REVOKED")) {
              pass=true;
            }
          } catch(e) {
          }
          if (pass) {
            ref.crl_pos=0; ref.position++;
          } else {
            ref.crl_pos++;
          }
        } catch (e) {
            alert(e);
            alert(http.responseText);
            ref.crl_pos++;
        }
        ref.nextstep();
      }
    }
    http.send(params);
  }
}


function check_revocation(rev,name) {
  var pcert;
  var l=new revocation(rev,name);
  l.start();
/*
  for ( var i in rev ) {
    alert(i);
    alert(dump(rev[i]));
    if (i==1) {
      pcert=1;
    } else {
      pcert=0;
    }
    
  }
*/
}
