var gHFDAInstances = new Array();
function HFDAGetInstance(containerId)
{
for (var i = 0; i < gHFDAInstances.length; i++)
{
if (gHFDAInstances[i].containerId == containerId)
{
return gHFDAInstances[i].instance;
}
}
return null;
}
function HermesFDAPlugin(containerId, plugin)
{
this.containerId = containerId;
this.plugin = plugin;
this.lastError = "";
this.onPinReady = null;
this.CertificatesReady = null;
this.CertificateReady = null;
this.SignatureReady = null;
this.afterShowKeypad = function () { window.location.hash = "#keypad"; };
this.afterHideKeypad = null;
this.workingCallback = null;
this.faltaSmartcard = false;
this.usaFirmaRemota = plugin != null && FirmaRemotaActiva();
this.mostrarEnlaceFirmaRemota = true;
this.certificates = [];
var encontrado = false;
for (var i = 0; i < gHFDAInstances.length; i++)
{
if (gHFDAInstances[i].containerId == containerId)
{
gHFDAInstances[i].instance = this;
encontrado = true;
break;
}
}
if (!encontrado)
{
gHFDAInstances.push({ 'containerId': containerId, 'instance': this });
}
// Alambrar los eventos del plugin
if (this.plugin != null)
{
var outterThis = this;
this.plugin.onCertificateReady =
function (certificate) {
outterThis.showPluginError();
outterThis.updatePinMask();
if (outterThis.CertificateReady != null) {
outterThis.CertificateReady(certificate);
}
}
this.plugin.onCertificatesReady =
function (certificates) {
outterThis.showPluginError();
outterThis.updatePinMask();
if (outterThis.CertificatesReady != null) {
outterThis.CertificatesReady(certificates);
}
}
this.plugin.onSignatureReady =
function (signature) {
outterThis.showPluginError();
outterThis.updatePinMask();
if (outterThis.SignatureReady != null) {
outterThis.SignatureReady(signature);
}
}
}
}
function HFDAKeyPadClic(containerId,key)
{
var instance = HFDAGetInstance(containerId);
if (instance!= null)
{
instance.handleKey(key);
}
}
HermesFDAPlugin.prototype.updatePinMask = function ()
{
var pinLength = this.getPlugin().pinLength;
var pinMask = '';
for (var i = 0; i < pinLength; i++)
{
pinMask += '•';
}
var display = document.getElementById(this.getInternalId("display"));
if (display != null)
{
display.innerHTML = pinMask;
}
}
HermesFDAPlugin.prototype.handleKey = function (char)
{
var plugin = this.getPlugin();
if (plugin==null)
{
return;
}
if (char=='B')
{
plugin.deletePinChar();
}
else if (char=='E')
{
if (this.onPinReady != null)
{
this.onPinReady(this);
}
}
else
{
plugin.processPinChar(char);
}
this.updatePinMask();
}
HermesFDAPlugin.prototype.isPinMissing = function (char)
{
return this.getPlugin().isPinMissing;
}
HermesFDAPlugin.prototype.isPinInvalid = function (char)
{
return this.getPlugin().isPinInvalid;
}
HermesFDAPlugin.prototype.pinRetryCount = function (char)
{
return this.getPlugin().pinRetryCount;
}
HermesFDAPlugin.prototype.pinModuleName= function (char)
{
return this.getPlugin().pinModuleName;
}
HermesFDAPlugin.prototype.friendlyPinModuleName = function (char) {
var pinModuleName = this.pinModuleName();
for (var i = 0; i < this.certificates.length; i++)
{
if (this.certificates[i].certid == pinModuleName)
{
pinModuleName = this.certificates[i].subject;
break;
}
}
var x = pinModuleName.match(/(CN|cn)\s*=\s*([\w,\s,(,),-]+),/);
if (x == null) {
x = pinModuleName.match(/(CN|cn)\s*=\s*([\w,\s,(,),-]+)/);
}
if (x != null && x.length >= 3) {
pinModuleName = x[2];
}
if (this.isInternetExplorer() || (this.isChrome() && this.isWindows())) {
var i = pinModuleName.lastIndexOf("-");
if (i > 0) {
pinModuleName = pinModuleName.substr(0, i);
}
}
return pinModuleName;
}
HermesFDAPlugin.prototype.pinNeeded = function ()
{
return (this.isPinMissing() || this.isPinInvalid()) && this.getPlugin().pinLength < HFDAMinPinLength;
}
HermesFDAPlugin.prototype.isFirefox = function ()
{
return navigator.userAgent.toLowerCase().indexOf("firefox/")>-1;
}
HermesFDAPlugin.prototype.isChrome = function ()
{
return navigator.userAgent.toLowerCase().indexOf("chrome/") > -1 && navigator.userAgent.toLowerCase().indexOf("edge/") <= -1;
}
HermesFDAPlugin.prototype.isInternetExplorer = function ()
{
var userAgent = navigator.userAgent.toLowerCase();
return userAgent.indexOf(" msie ") > -1 || userAgent.indexOf("trident/7.0;") > -1;
}
HermesFDAPlugin.prototype.isSafari = function ()
{
return navigator.userAgent.toLowerCase().indexOf("safari/")>-1 && navigator.userAgent.toLowerCase().indexOf("edge/") <= -1;
}
HermesFDAPlugin.prototype.isMacOSX = function ()
{
return navigator.userAgent.toLowerCase().indexOf("intel mac os x 10")>-1;
}
HermesFDAPlugin.prototype.isMavericksOrSuperior = function () {
var result = false;
if (this.isMacOSX()) {
var userAgent = navigator.userAgent.toLowerCase().replace("_", ".");
var match = userAgent.match(/mac os x \d+\.\d+/)[0];
var version = match.match(/\d+/);
var subVersion = match.substring(match.indexOf(".") + 1);
result = version > 10 || (version == 10 && subVersion >= 9);
}
return result;
}
HermesFDAPlugin.prototype.isLinux = function ()
{
return navigator.userAgent.toLowerCase().indexOf("linux i686")>-1
|| navigator.userAgent.toLowerCase().indexOf("linux x86")>-1;
}
HermesFDAPlugin.prototype.isUbuntu = function ()
{
return navigator.userAgent.toLowerCase().indexOf("ubuntu")>-1;
}
HermesFDAPlugin.prototype.browserVersion = function () {
var version = "xxx/0.0";
if (this.isChrome()) {
version = navigator.userAgent.match(/Chrome\/\d+\.\d+/)[0];
}
else if (this.isFirefox()) {
version = navigator.userAgent.match(/Firefox\/\d+\.\d+/)[0];
}
else if (this.isSafari()) {
version = navigator.userAgent.match(/Version\/\d+\.\d+/)[0];
}
else if (this.isInternetExplorer()) {
var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf("trident/7.0;") > -1)
version = "11.0";
else
version = navigator.userAgent.match(/MSIE \d+\.\d+/)[0];
}
return version.match(/\d+\.\d+/)[0];
}
HermesFDAPlugin.prototype.isWindows = function ()
{
return navigator.userAgent.toLowerCase().indexOf("windows nt")>-1;
}
HermesFDAPlugin.prototype.contentType = function ()
{
return "application/x-hermes-soft-fda";
}
HermesFDAPlugin.prototype.isOperatingSystemSupported = function ()
{
return this.isMacOSX() || this.isWindows() || this.isUbuntu() || this.isLinux();
}
HermesFDAPlugin.prototype.isNavigatorSupported = function ()
{
return this.isFirefox() || this.isChrome() || this.isInternetExplorer() || this.isSafari();
}
HermesFDAPlugin.prototype.isPlatformSupported = function ()
{
if (this.usaFirmaRemota) {
return true;
}
return (this.isFirefox() && (this.isMacOSX() || this.isWindows() || this.isUbuntu() || this.isLinux()))
|| (this.isChrome() && (this.isMacOSX() || this.isWindows() || this.isLinux()))
|| (this.isInternetExplorer() && this.isWindows())
|| (this.isSafari() && this.isMacOSX());
}
HermesFDAPlugin.prototype.navigatorName = function ()
{
if (this.isInternetExplorer()) return "Internet Explorer " + this.browserVersion();
if (this.isFirefox()) return "Firefox "+this.browserVersion();
if (this.isChrome()) return "Chrome " + this.browserVersion();
if (this.isSafari()) return "Safari " + this.browserVersion();
return HFDAUnknownBrowser;
}
HermesFDAPlugin.prototype.operatingSystemName = function ()
{
if (this.isWindows()) return "Windows";
if (this.isMacOSX()) return "Mac OS X";
if (this.isUbuntu()) return "Ubuntu";
if (this.isLinux()) return "Linux";
return HFDAUnknownBrowser;
}
HermesFDAPlugin.prototype.supportedBrowserVersion = function ()
{
return (this.isFirefox() && this.browserVersion()>= HFDAMinFirefoxVersion )
|| (this.isChrome() && this.browserVersion()>=HFDAMinChromeVersion )
|| (this.isInternetExplorer() && this.browserVersion()>= HFDAMinInternetExplorerVersion)
|| (this.isSafari() && this.browserVersion()>= HFDAMinSafariVersion);
}
HermesFDAPlugin.prototype.formatMsg = function (msg, params)
{
for (var i = 0; i < params.length; i++)
{
msg = msg.replace("{"+i+"}",""+params[i]);
}
return msg;
}
HermesFDAPlugin.prototype.isInstalled =
function ()
{
if(this.usaFirmaRemota)
{
return true;
}
else if (this.isInternetExplorer())
{
var obj = null;
try
{
obj = new ActiveXObject("HermesSoft.HermesSoftFDA");
}
catch (e)
{
}
return obj != null;
}
else if (this.isChrome())
{
return this.getPlugin() != null && this.getPlugin().isInstalled();
}
else if (this.isFirefox() && this.browserVersion()>=52)
{
return this.getPlugin() != null && this.getPlugin().isInstalled();
}
else
{
var mimeType = navigator.mimeTypes[this.contentType()];
return mimeType != null && mimeType.enabledPlugin != null;
}
}
HermesFDAPlugin.prototype.isUpdated = function()
{
if (!this.isInstalled())
{
return false;
}
if (parseFloat(this.version()) < HFDAVersion )
{
return false;
}
else
{
return true;
}
}
HermesFDAPlugin.prototype.description = function ()
{
if (!this.isInstalled())
{
return "";
}
if (this.usaFirmaRemota) {
return this.plugin.description;
}
else if (this.isInternetExplorer())
{
var obj = null;
try
{
obj = new ActiveXObject("HermesSoft.HermesSoftFDA");
}
catch (e)
{
}
return "Hermes-Soft Firma Digital Avanzada " + obj.version;
}
else if (this.isChrome())
{
return this.getPlugin().description;
}
else if (this.isFirefox() && this.browserVersion()>=52)
{
return this.getPlugin().description;
}
else
{
var description = navigator.mimeTypes[this.contentType()].enabledPlugin.description;
if (description == null || description == "") {
description = navigator.mimeTypes[this.contentType()].description;
}
return description;
}
}
HermesFDAPlugin.prototype.version = function()
{
if (this.isChrome() && !this.usaFirmaRemota)
{
return this.getPlugin().version;
}
else if (this.isFirefox() && this.browserVersion() >= 52 && !this.usaFirmaRemota)
{
return this.getPlugin().version;
}
else
{
return this.description().match(/\d\.\d/)[0];
}
}
HermesFDAPlugin.prototype.minNavigatorVersion = function()
{
if (this.isInternetExplorer()) return HFDAMinInternetExplorerVersion;
if (this.isFirefox()) return HFDAMinFirefoxVersion;
if (this.isChrome()) return HFDAMinChromeVersion;
if (this.isSafari()) return HFDAMinSafariVersion;
return "---";
}
HermesFDAPlugin.prototype.getPlugin = function()
{
if (this.plugin==null)
{
if (this.isChrome() || (this.isFirefox() && this.browserVersion()>=52))
{
if (this.isChrome()) {
this.plugin = new HermesFDAChrome(true);
}
else
{
this.plugin = new HermesFDAChrome(false);
}
this.plugin.initialize(HermesFDASignature, HermesFDADomains, window.location.hostname, HermesFDACaSubjectNames);
var outterThis = this;
this.plugin.onCertificateReady =
function (hermesFDAChrome, certificate)
{
if (outterThis.CertificateReady != null)
{
outterThis.CertificateReady(certificate);
}
}
this.plugin.onCertificatesReady =
function (hermesFDAChrome, certificates)
{
if (outterThis.CertificatesReady != null)
{
outterThis.CertificatesReady(certificates);
}
}
this.plugin.onSignatureReady =
function (hermesFDAChrome, signature)
{
if (outterThis.SignatureReady != null) {
outterThis.SignatureReady(signature);
}
}
this.plugin.onUpdated =
function (hermesFdaChrome, command)
{
// no actualizar despliegue de error
// para los eventos del teclado numerico
if (command != 6 && command != 7)
{
outterThis.showPluginError();
}
outterThis.updatePinMask();
}
}
else
{
this.plugin = document.getElementById("HermesFDAPlugin");
}
}
return this.plugin;
}
HermesFDAPlugin.prototype.showError = function (errorCode, message)
{
if (errorCode != "" && message != "")
{
this.lastError = message;
var lastErrorCode = this.getPlugin().lastError;
if (lastErrorCode != HFDA_INVALID_PIN && lastErrorCode != HFDA_MISSING_PIN)
{
this.lastError += "\n" + errorCode;
}
}
else
{
this.lastError = "";
}
var keyPad = document.getElementById(this.keyPadId());
if (this.pinNeeded())
{
if (this.isInternetExplorer() && parseFloat(this.browserVersion()) < 8.0)
{
keyPad.style.display = "block";
}
else
{
keyPad.style.display = "table";
}
$("#" + this.containerId + " .HFDADiv").focus();
if (this.afterShowKeypad != null)
{
this.afterShowKeypad();
}
}
else if (keyPad != null)
{
keyPad.style.display = "none";
if (this.afterHideKeypad != null)
{
this.afterHideKeypad();
}
}
var error = document.getElementById(this.getInternalId("HFDAErrorMsg"));
if (error != null)
{
error.innerHTML = this.lastError.replace("\n", "
").replace("—", "ó");
}
this.setWorking("");
}
HermesFDAPlugin.prototype.showPluginError = function () {
var lastError = this.getPlugin().lastError;
this.faltaSmartcard = false;
if (lastError > 0) {
var error;
if (lastError <= HFDA_MISSING_PIN)
{
error = HermesFDAErrorMessages[lastError];
}
else
{
error = this.GetErrorMessageFromLowLevelError();
if (error == "")
{
error = HermesFDAUnknownError;
}
}
var lastErrorMsg = '';
try
{
lastErrorMsg = this.getPlugin().lastErrorMessage;
}
catch (e)
{
}
if (lastError == HFDA_INVALID_PIN)
{
pinModuleName = this.friendlyPinModuleName();
error = this.formatMsg(error, [this.pinRetryCount(), pinModuleName]);
}
else if (lastError == HFDA_MISSING_PIN)
{
pinModuleName = this.friendlyPinModuleName();
error = this.formatMsg(error, [pinModuleName]);
}
var errorCode = this.getPlugin().lastError + " " + this.getPlugin().lastLowLevelError;
if (lastErrorMsg != "" && lastError != HFDA_INVALID_PIN && lastError != HFDA_MISSING_PIN)
{
errorCode += " " + lastErrorMsg;
}
this.showError(errorCode, error);
}
else {
this.showError("", "");
}
}
HermesFDAPlugin.prototype.getDigitalSignatureCertificates = function(callback)
{
if (this.getPlugin()==null)
{
this.showError("---",HFDAMsgUnableToCreatePluginInstance);
callback("");
}
this.setWorking(HFDAWorking);
var result = '';
try
{
this.CertificatesReady = callback;
this.certificates = [];
result = this.getPlugin().getDigitalSignatureCertificates();
if (result != null)
{
var certs = result.split('|');
for (var i = 0; i < certs.length; i += 3)
{
var certificate = {
issuer: certs[i],
subject: certs[i + 1],
certid: certs[i + 2]
};
this.certificates.push(certificate);
}
this.showPluginError();
this.updatePinMask();
callback(result);
}
}
catch(e)
{
}
}
HermesFDAPlugin.prototype.getCertificate = function(certId, callback)
{
if (this.getPlugin()==null)
{
this.showError("---",HFDAMsgUnableToCreatePluginInstance);
return "";
}
this.setWorking(HFDAWorking);
this.CertificateReady = callback;
var result = this.getPlugin().getCertificate(certId);
if (result != null)
{
this.showPluginError();
this.updatePinMask();
callback(result);
}
return result;
}
HermesFDAPlugin.prototype.setPin = function(pin)
{
if (this.getPlugin()==null)
{
this.showError("---",HFDAMsgUnableToCreatePluginInstance);
return "";
}
this.getPlugin().pin = pin;
this.showPluginError();
this.updatePinMask();
}
HermesFDAPlugin.prototype.signPkcs1 = function(certId, digest, callback)
{
if (this.getPlugin()==null)
{
this.showError("---",HFDAMsgUnableToCreatePluginInstance);
return "";
}
this.setWorking(HFDAWorking);
this.SignatureReady = callback;
var result = this.getPlugin().signPkcs1(certId, digest);
if (result != null)
{
this.showPluginError();
this.updatePinMask();
callback(result);
}
return result;
}
HermesFDAPlugin.prototype.echo = function () {
if (this.getPlugin() == null) {
this.showError("---", HFDAMsgUnableToCreatePluginInstance);
return "";
}
var plugin = this.getPlugin();
var result = this.getPlugin().echo("prueba");
return result;
}
HermesFDAPlugin.prototype.fillSelectWithDigitalSignatureCertificates = function (certsStr, select)
{
select.options.length = 0;
var certs = new Array();
var i = 0;
while (certsStr != "")
{
var p = certsStr.indexOf("|");
var cn;
if (p > 0) {
cn = certsStr.substring(0, p);
certsStr = certsStr.substring(p + 1);
}
else {
cn = certsStr;
certsStr = "";
}
var x = cn.match(/(CN|cn)\s*=\s*([\w,\s,(,),-,\],\[]+),/);
if (x == null) {
x = cn.match(/(CN|cn)\s*=\s*([\w,\s,(,),-,\],\[]+)/);
}
if (x != null && x.length >= 3 && i != 2) {
certs.push(x[2]);
}
else {
certs.push(cn);
}
i++;
if (i == 3) i = 0;
}
for (var i = 0; i < certs.length; i += 3) {
select.options[select.options.length] = new Option(certs[i + 1] + " (" + certs[i] + ")", certs[i + 2]);
}
}
HermesFDAPlugin.prototype.getInternalId = function(sufix)
{
return this.containerId + "_" + sufix;
}
HermesFDAPlugin.prototype.keyPadId = function()
{
return this.getInternalId("KeyPad");
}
HermesFDAPlugin.prototype.renderKeyPad = function()
{
var keys = ["7","8","9", "4", "5", "6", "1", "2", "3", "B","0","E"];
var html = "
| " + this.renderKeyPad() + " | |||
| "; if (this.isMavericksOrSuperior()) { html += " | " + HFDAHelpLink("InstallMavericks") + " | "; } else if (this.isWindows()) { html += "" + HFDAHelpLink("InstallWindows") + " | "; } else if (this.isInternetExplorer()) { html += "" + HFDAHelpLink("InstallIE") + " | "; } else if (this.isFirefox()) { html += "" + HFDAHelpLink("InstallFirefox") + " | "; } else if (this.isChrome()) { html += "" + HFDAHelpLink("InstallChrome") + " | "; } else if (this.isSafari()) { html += "" + HFDAHelpLink("InstallSafari") + " | "; } } else { html += "" + cantInstallMsg + " | ";
html += "" + HFDAHelpLink("Compatibility") + " | "; } } html += ""; if (HDFAFirmaRemota && this.mostrarEnlaceFirmaRemota) { html += "
";
}
var gPasoFirma = 0; // 0 = Cargando lista de certificados, 1 = Preparando para firmar, 2 = Firmando
var gHermesFDAPlugin = null;
var gFormToSign = null;
var gSubmitButton = null;
var firmaDigitalDlg = null;
function HFDAInicializar(contenedorId, formToSign, submitButton, callback)
{
if (document.getElementById("FirmaDigitalDlg") == null) {
var result =
$.ajax({
type: "GET",
url: HermesFDABaseUrl + "FirmaDigitalDlg.htm",
dataType: "html",
async: true,
cache: false,
success:
function (data) {
$("#" + contenedorId).html(data);
$("#AyudaLector").html(HFDAHelpLink("AyudaLector"));
$("#FirmaDigitalDlg .ImagenHFDA").each(function () { $(this).attr("src", HermesFDABaseUrl + $(this).attr("src")) });
HFDAInicializarHermesFDAPlugin(formToSign, submitButton, null, callback);
}
});
return;
}
else {
HFDAInicializarHermesFDAPlugin(formToSign, submitButton, null, callback);
}
}
function HFDAInicializarHermesFDAPlugin(formToSign, submitButton, plugin, callback)
{
gFormToSign = formToSign;
gSubmitButton = submitButton;
var servicioId = ObtenerIdServicio(false);
if (servicioId != "" && servicioId != null && plugin == null) {
HFDAActivarFirmaRemota();
return;
}
gHermesFDAPlugin = new HermesFDAPlugin("hermesFDAPluginContainer", plugin);
gHermesFDAPlugin.render();
gHermesFDAPlugin.onPinReady = FirmarFormulario;
firmaDigitalDlg =
$("#FirmaDigitalDlg").dialog({
autoOpen: false,
height: 580,
width: 440,
modal: true,
title: "Solicitud de firma digital",
Cancel: function () { $(this).dialog("close"); },
position: ["center", "center"],
resizable: false,
buttons: { "Cancelar": CancelarFirma }
});
if (callback != null)
{
callback();
}
}
var gAfterSignatureCallback = null;
function HFDAPedirFirmaYEnviar(msg) {
return HFDAPedirFirma(msg, function () { gFormToSign.submit(); });
}
function HFDAPedirFirma(msg, callback)
{
gAfterSignatureCallback = callback;
if (gHermesFDAPlugin == null)
{
alert("No se ha inicializado el plugin de firma digital");
return false;
}
gPasoFirma = 0;
var select = document.getElementById("HFDACertificados");
select.options.length = 0;
if (msg == null || msg == "") {
$("#DescripcionFirma").html("");
$("#DescripcionFirma").hide();
}
else {
$("#DescripcionFirma").html(msg);
$("#DescripcionFirma").show();
}
if (firmaDigitalDlg != null)
{
try {
firmaDigitalDlg.dialog("open");
}
catch (e) {
}
}
return FirmarFormulario();
}
var HFDAMetodoControlador = FirmarFormulario;
function CargarCertificados(callback)
{
if (!gHermesFDAPlugin.isInstalled() || !gHermesFDAPlugin.isUpdated() || gHermesFDAPlugin.pinNeeded())
{
document.getElementById("HFDASeleccionCertificado").style.display = "none";
callback();
return;
}
gHermesFDAPlugin.getDigitalSignatureCertificates(
function (certsStr)
{
var select = document.getElementById("HFDACertificados");
gHermesFDAPlugin.fillSelectWithDigitalSignatureCertificates(certsStr, select);
if (gHermesFDAPlugin.lastError == 0 && select.options.length > 0)
{
document.getElementById("HFDASeleccionCertificado").style.display = "block";
if (firmaDigitalDlg != null)
{
firmaDigitalDlg.dialog("option",
"buttons",
{
"Cancelar": CancelarFirma,
"Firmar": function () { HFDAMetodoControlador(); }
}
);
}
}
else
{
document.getElementById("HFDASeleccionCertificado").style.display = "none";
}
callback();
}
);
}
function CancelarFirma() {
if (firmaDigitalDlg != null)
{
firmaDigitalDlg.dialog("close");
}
if (gSubmitButton != null)
{
gSubmitButton.disabled = false;
}
}
function FirmarFormulario()
{
try
{
if (!gHermesFDAPlugin.isInstalled())
{
alert("Primero tiene que instalar el plugin de firma\ndigital para poder firmar digitalmente");
return false;
}
if (!gHermesFDAPlugin.isUpdated())
{
alert("Primero tiene que actualizar el plugin de firma\ndigital para poder firmar digitalmente");
return false;
}
if (gHermesFDAPlugin.pinNeeded())
{
alert("Debe introducir el pin para '" + gHermesFDAPlugin.friendlyPinModuleName() + "'. Debe tener por lo menos " + HFDAMinPinLength + " digitos");
return false;
}
// llenar lista de certificados
if (gPasoFirma == 0)
{
CargarCertificados(
function ()
{
if (gHermesFDAPlugin.lastError == 0)
{
var select = document.getElementById("HFDACertificados");
if (select.options.length == 0)
{
$("#HFDANoHayCertificados").show();
}
gPasoFirma = 1; // preparando firma
}
else
{
if (gSubmitButton != null)
{
gSubmitButton.disabled = false;
}
}
}
);
return false;
}
if (gPasoFirma == 1)
{
var select = document.getElementById("HFDACertificados");
gHermesFDAPlugin.getCertificate(
select.value,
function ( certificate )
{
if (gHermesFDAPlugin.lastError != '')
{
return false;
}
// guardar el html del formulario en un campo
SaveFormBody(gFormToSign);
// cargar el formulario para preparar la firma digital
LoadPrepareSignatureForm(gFormToSign, certificate, $("#DescripcionFirma").html());
if (gSubmitButton != null)
{
gSubmitButton.disabled = true;
}
var formData = $("#" + gPrepareSignatureFormName).serialize();
var result = $.ajax(
{
type: "POST", url: HermesFDAPrepareSignaturePageURL, data: formData, dataType: "text",
async: true, cache: false, error: PrepareSignatureError, success: PrepareSignatureSuccess
}
);
}
);
}
if (gPasoFirma == 2)
{
return FirmarFormularioContinuacion();
}
return true;
}
catch (e) {
alert("Ocurrio un error al tratar de firmar:" + e);
return false;
}
}
function PrepareSignatureError(jqXHR, textStatus, errorThrown)
{
alert("Ocurrio un error al preparar los datos para firmar '" + textStatus + " " + errorThrown + "'");
if (gSubmitButton != null)
{
gSubmitButton.disabled = false;
}
gPasoFirma = 1;
}
function PrepareSignatureSuccess(result)
{
document.getElementById(HFDASignatureDataFieldId).value = result;
gPasoFirma = 2; // firmando ...
FirmarFormularioContinuacion();
}
function FirmarFormularioContinuacion()
{
if (gPasoFirma == 2)
{
var signatureData = document.getElementById(HFDASignatureDataFieldId).value;
var hash = "";
var p = signatureData.indexOf("
";
}
var gPasoFirma = 0; // 0 = Cargando lista de certificados, 1 = Preparando para firmar, 2 = Firmando
var gHermesFDAPlugin = null;
var gFormToSign = null;
var gSubmitButton = null;
var firmaDigitalDlg = null;
function HFDAInicializar(contenedorId, formToSign, submitButton, callback)
{
if (document.getElementById("FirmaDigitalDlg") == null) {
var result =
$.ajax({
type: "GET",
url: HermesFDABaseUrl + "FirmaDigitalDlg.htm",
dataType: "html",
async: true,
cache: false,
success:
function (data) {
$("#" + contenedorId).html(data);
$("#AyudaLector").html(HFDAHelpLink("AyudaLector"));
$("#FirmaDigitalDlg .ImagenHFDA").each(function () { $(this).attr("src", HermesFDABaseUrl + $(this).attr("src")) });
HFDAInicializarHermesFDAPlugin(formToSign, submitButton, null, callback);
}
});
return;
}
else {
HFDAInicializarHermesFDAPlugin(formToSign, submitButton, null, callback);
}
}
function HFDAInicializarHermesFDAPlugin(formToSign, submitButton, plugin, callback)
{
gFormToSign = formToSign;
gSubmitButton = submitButton;
var servicioId = ObtenerIdServicio(false);
if (servicioId != "" && servicioId != null && plugin == null) {
HFDAActivarFirmaRemota();
return;
}
gHermesFDAPlugin = new HermesFDAPlugin("hermesFDAPluginContainer", plugin);
gHermesFDAPlugin.render();
gHermesFDAPlugin.onPinReady = FirmarFormulario;
firmaDigitalDlg =
$("#FirmaDigitalDlg").dialog({
autoOpen: false,
height: 580,
width: 440,
modal: true,
title: "Solicitud de firma digital",
Cancel: function () { $(this).dialog("close"); },
position: ["center", "center"],
resizable: false,
buttons: { "Cancelar": CancelarFirma }
});
if (callback != null)
{
callback();
}
}
var gAfterSignatureCallback = null;
function HFDAPedirFirmaYEnviar(msg) {
return HFDAPedirFirma(msg, function () { gFormToSign.submit(); });
}
function HFDAPedirFirma(msg, callback)
{
gAfterSignatureCallback = callback;
if (gHermesFDAPlugin == null)
{
alert("No se ha inicializado el plugin de firma digital");
return false;
}
gPasoFirma = 0;
var select = document.getElementById("HFDACertificados");
select.options.length = 0;
if (msg == null || msg == "") {
$("#DescripcionFirma").html("");
$("#DescripcionFirma").hide();
}
else {
$("#DescripcionFirma").html(msg);
$("#DescripcionFirma").show();
}
if (firmaDigitalDlg != null)
{
try {
firmaDigitalDlg.dialog("open");
}
catch (e) {
}
}
return FirmarFormulario();
}
var HFDAMetodoControlador = FirmarFormulario;
function CargarCertificados(callback)
{
if (!gHermesFDAPlugin.isInstalled() || !gHermesFDAPlugin.isUpdated() || gHermesFDAPlugin.pinNeeded())
{
document.getElementById("HFDASeleccionCertificado").style.display = "none";
callback();
return;
}
gHermesFDAPlugin.getDigitalSignatureCertificates(
function (certsStr)
{
var select = document.getElementById("HFDACertificados");
gHermesFDAPlugin.fillSelectWithDigitalSignatureCertificates(certsStr, select);
if (gHermesFDAPlugin.lastError == 0 && select.options.length > 0)
{
document.getElementById("HFDASeleccionCertificado").style.display = "block";
if (firmaDigitalDlg != null)
{
firmaDigitalDlg.dialog("option",
"buttons",
{
"Cancelar": CancelarFirma,
"Firmar": function () { HFDAMetodoControlador(); }
}
);
}
}
else
{
document.getElementById("HFDASeleccionCertificado").style.display = "none";
}
callback();
}
);
}
function CancelarFirma() {
if (firmaDigitalDlg != null)
{
firmaDigitalDlg.dialog("close");
}
if (gSubmitButton != null)
{
gSubmitButton.disabled = false;
}
}
function FirmarFormulario()
{
try
{
if (!gHermesFDAPlugin.isInstalled())
{
alert("Primero tiene que instalar el plugin de firma\ndigital para poder firmar digitalmente");
return false;
}
if (!gHermesFDAPlugin.isUpdated())
{
alert("Primero tiene que actualizar el plugin de firma\ndigital para poder firmar digitalmente");
return false;
}
if (gHermesFDAPlugin.pinNeeded())
{
alert("Debe introducir el pin para '" + gHermesFDAPlugin.friendlyPinModuleName() + "'. Debe tener por lo menos " + HFDAMinPinLength + " digitos");
return false;
}
// llenar lista de certificados
if (gPasoFirma == 0)
{
CargarCertificados(
function ()
{
if (gHermesFDAPlugin.lastError == 0)
{
var select = document.getElementById("HFDACertificados");
if (select.options.length == 0)
{
$("#HFDANoHayCertificados").show();
}
gPasoFirma = 1; // preparando firma
}
else
{
if (gSubmitButton != null)
{
gSubmitButton.disabled = false;
}
}
}
);
return false;
}
if (gPasoFirma == 1)
{
var select = document.getElementById("HFDACertificados");
gHermesFDAPlugin.getCertificate(
select.value,
function ( certificate )
{
if (gHermesFDAPlugin.lastError != '')
{
return false;
}
// guardar el html del formulario en un campo
SaveFormBody(gFormToSign);
// cargar el formulario para preparar la firma digital
LoadPrepareSignatureForm(gFormToSign, certificate, $("#DescripcionFirma").html());
if (gSubmitButton != null)
{
gSubmitButton.disabled = true;
}
var formData = $("#" + gPrepareSignatureFormName).serialize();
var result = $.ajax(
{
type: "POST", url: HermesFDAPrepareSignaturePageURL, data: formData, dataType: "text",
async: true, cache: false, error: PrepareSignatureError, success: PrepareSignatureSuccess
}
);
}
);
}
if (gPasoFirma == 2)
{
return FirmarFormularioContinuacion();
}
return true;
}
catch (e) {
alert("Ocurrio un error al tratar de firmar:" + e);
return false;
}
}
function PrepareSignatureError(jqXHR, textStatus, errorThrown)
{
alert("Ocurrio un error al preparar los datos para firmar '" + textStatus + " " + errorThrown + "'");
if (gSubmitButton != null)
{
gSubmitButton.disabled = false;
}
gPasoFirma = 1;
}
function PrepareSignatureSuccess(result)
{
document.getElementById(HFDASignatureDataFieldId).value = result;
gPasoFirma = 2; // firmando ...
FirmarFormularioContinuacion();
}
function FirmarFormularioContinuacion()
{
if (gPasoFirma == 2)
{
var signatureData = document.getElementById(HFDASignatureDataFieldId).value;
var hash = "";
var p = signatureData.indexOf("