/* CLASES PARA GESTIONAR LAS ACCIONES A REALIZAR DURANTE EL PROCESO DE FIRMA */
var TEXT_NO_CERT = "Para acceder a la aplicación debe seleccionar un certificado digital";
var SIGN_ERROR = "Se ha producido un error al firmar el documento";

/**
  * Esta función se ejecutará en la página donde se incruste el Applet, justo después
  * de finalizar la carga.
  * La acción por defecto es ocultar el mensaje de carga del Applet
  */
//function init() {}
/**
  * Esta función se ejecutará justo antes de las acciones propieas de cada botón del
  * applet. Se debe utilizar para configurar el proceso de firma y pasar los datos
  * a firmar.
  * @param idButton código del botón que se ha presionado (int)
  * @rtn siempre es '0'
  * @return false si se desea interrumpir la ejecución del botón
  */
//function beforeButtonClickManager(idButton, rtn) {}
/**
  * Esta función se ejecutará justo después de las acciones propias de cada botón del
  * applet. Se debe utilizar para procesar el resultado de la firma y recuperar los
  * datos firmados.
  * @param idButton código del botón que se ha presionado (int)
  * @rtn código del resultado del proceso del applet. '0' si correcto
  */
/*function afterButtonClickManager(idButton, rtn) {
	alert("Debe configurar las acciones a realizar tras la firma");
	return false;
}*/

/* CLASE WEBSITEAPPLET */

/**
  * Clase WebsiteApplet
  * Clase para configurar y mostrar en una página web el Applet de firma electrónica
  * eSigna Website.
  * Para crear este objeto hay que especificar las dimensiones deseadas para el applet.
  * @author Indenova S.L.
  * @version 1.0
  */

function WebsiteApplet(width, heigth, appletID) {
	this.objeto = "";
	this.jars = new Array();
	this.vers = new Array();
	this.bgcolor = "#FFF";
	this.toolbarType = "1";
	this.internalParam = "";
	this.websiteClass = "";
	this.lfwin = false;
        this.version = "";
        this.baseurl = "";
	
	this.showApplet = showApplet;
	this.showSignTextApplet = showSignTextApplet;
        this.showSignHMFormApplet = showSignHMFormApplet;
	this.setBasicJars = setBasicJars;
	this.setVerifyJars = setVerifyJars;
	this.setWSJars = setWSJars;
	this.setPDFJars = setPDFJars;
	this.setSMIMEJars = setSMIMEJars;
        this.setTSPJars = setTSPJars;
	this.setWSTeSignaJars = setWSTeSignaJars;
	this.showWebSecureApplet = showWebSecureApplet;
	this.setBgColor = setBgColor;
	this.setToolbarType = setToolbarType;
	this.setWinLookAndFeel = setWinLookAndFeel;
	this.buildParam = buildParam;
	this.setCustomParams = setCustomParams;
        this.setCustomJars = setCustomJars;
        this.setVersion = setVersion;
        this.setBaseUrl = setBaseUrl;
	
        if (appletID == undefined) {
		appletID = "eSignaApplet";
	}
        //alert(appletID);

	this.OBJECT = '<OBJECT WIDTH="' + width + '" HEIGHT="' + heigth + '" ' + 
				  'ALIGN="center" ' + 'ID="'+appletID+'" onmouseover="this.focus();"  ' +
				  'classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"  ' +
				  'codebase="' + location.protocol + '//' + 
				  'java.sun.com/update/1.5.0/jinstall-1_5_0_03-windows-i586.cab#Version=1,5,0,03">';
	this._OBJECT = '</OBJECT>';
	this.PARAM_CONF = '<PARAM NAME="type" VALUE="application/x-java-applet">' +
					  '<PARAM NAME="mayscript" VALUE="true">' +
					  '<PARAM NAME="scriptable" VALUE="true">';
        
                                          
	this.APPLET = '<COMMENT><APPLET WIDTH="' + width + '" HEIGHT="' + heigth + '" ' + 
				  'ALIGN="center" ' + 'ID="'+appletID+'2" mayscript="true" code="';
	this.APPLET2 = '">';
	this.WARNING = '<span>Necesita instalar J2SE. Pulse en la barra superior.</span>';
	this._APPLET = '</APPLET></COMMENT>';
}

function setBaseUrl(baseurl) {
    if (baseurl != '') {
        if (baseurl.lastIndexOf("/") != baseurl.length - 1) {
            this.baseurl = baseurl + "/";
        } else {
            this.baseurl = baseurl;
        }
    }
}

function setVersion(ver) {
    this.version = ver;
}

/**
  * Especifica el color de fondo para el applet.
  * @param bgcolor color en formato web, por ejemplo #FFFFFF
  */
function setBgColor(bgcolor) {
	this.bgcolor = bgcolor;
}

function setWinLookAndFeel(lfwin) {
	this.lfwin = lfwin;
}

/**
  * Especifica el tipo de barra de botones deseado.
  * @param toolbarType '1' para botones normales
  * 				   '2' para estilo de barra de herramientas
  */
function setToolbarType(toolbarType) {
	this.toolbarType = toolbarType;
}

function showSignTextApplet(layer, debug, slabel) {
	if (slabel == undefined) {
		slabel = "Firmar";
	}
	this.internalParam = "";
	this.internalParam += this.buildParam("btSign", "1");
	this.internalParam += this.buildParam("labelSignBt", slabel);
	this.showApplet(layer, debug);
}

function showSignHMFormApplet(layer, debug, slabel) {
	if (slabel == undefined) {
		slabel = "Firmar";
	}
	this.showApplet(layer, debug);
}

function showWebSecureApplet(layer, debug, sessionid, remoteip, crl, type, slabel, automatic, always) {
	if (type == 'php') {
		this.websiteClass = "com.indenova.esigna.web.applets.WebSecureAppletSM.class";
		this.setSMIMEJars();
	} else {
		this.websiteClass = "com.indenova.esigna.web.applets.WebSecureApplet.class";
	}
	if (debug == undefined) {
		debug = false;
	}
	if (slabel == undefined) {
		slabel = "Acceso con certificado digital";
	}
	if (automatic == undefined) {
		automatic = "0";
	} else if (automatic) {
		automatic = "1";
	} else {
		automatic = "0";
	}
	if (always == undefined) {
		always = "0";
	} else if (always) {
		always = "1";
	} else {
		always = "0";
	}
	if (crl == undefined) {
		crl = "1";
	} /*else if (crl) {
		crl = "1";
	} else {
		crl = "0";
	}*/
	if ((sessionid == undefined) || (remoteip == undefined)) {
		alert("Error de configuración. Imposible acceder al sistema con certificado digital");
		return;
	}
	
	this.internalParam = "";
	this.internalParam += this.buildParam("btLogin", "1");
	this.internalParam += this.buildParam("label", slabel);
	this.internalParam += this.buildParam("automatic", automatic);
	this.internalParam += this.buildParam("always", always);
	this.internalParam += this.buildParam("crl", crl);
	this.internalParam += this.buildParam("sessionid", sessionid);
	this.internalParam += this.buildParam("remoteip", remoteip);
	this.showApplet(layer, debug);
}

/**
  * Configura el Applet con un único botón para firmar un texto
  * @param layer atributi 'id' del elemento HTML donde se desea mostrar el applet.
  * @param debug true para iniciar el Applet en modo depuración.
  */
function showApplet(layer, debug) {
	if (this.websiteClass == "") {
		this.websiteClass = "com.indenova.esigna.web.applets.website.WebSiteApplet.class";
	}
	
        this.setWSTeSignaJars();
	this.setBasicJars();
        this.setVerifyJars();
	this.objeto = this.OBJECT; 
	
	this.objeto += this.buildParam("code", this.websiteClass);
	auxcache = "";
	cache = ""
           
	for (i = 0; i < this.jars.length; i++) {
		if (i > 0) {
			auxcache += ',';
		}
		auxcache += this.jars[i];
	}
	cache += this.buildParam("cache_archive", auxcache);
	auxcache = "";
	for (i = 0; i < this.vers.length; i++) {
		if (i > 0) {
			auxcache += ',';
		}
		auxcache += this.vers[i];
	}
	cache += this.buildParam("cache_version", auxcache);

	cache += this.PARAM_CONF;
	cache += this.buildParam("bgcolor", this.bgcolor);
	cache += this.buildParam("toolbarType", this.toolbarType);
	if (debug) {
		cache += this.buildParam("debug", "1");
	}
	if (this.lfwin) {
		cache += this.buildParam("lfWIN", "1");
	}
	
	cache += this.internalParam;
	cache += this.setCustomParams();
	
	this.objeto += cache;
	
	this.objeto += this.APPLET;
	this.objeto += this.websiteClass;
	this.objeto += this.APPLET2;
	this.objeto += cache;
	
	this.objeto += this.WARNING;
	this.objeto += this._APPLET;
	this.objeto += this._OBJECT;
	var divAux = document.getElementById(layer);
        //alert(this.objeto);
        
	divAux.innerHTML = this.objeto;
}

function buildParam(name, value) {
	line = '<PARAM NAME="' + name + '" VALUE="' + value + '">';
	return line;
}

function setWSTeSignaJars() {
        if (this.version == "") {
            eSignaVersion = '0.0.0.0';
        } else {
            eSignaVersion = this.version;
        }
	this.jars[this.jars.length++] = this.baseurl + 'eswst-jars/SeSignaUtil.jar';
	this.vers[this.vers.length++] = eSignaVersion;
	this.jars[this.jars.length++] = this.baseurl + 'eswst-jars/SeSignaCrypto.jar';
	this.vers[this.vers.length++] = eSignaVersion;
	this.jars[this.jars.length++] = this.baseurl + 'eswst-jars/SeSignaCryptoApp.jar';
	this.vers[this.vers.length++] = eSignaVersion;
	this.jars[this.jars.length++] = this.baseurl + 'eswst-jars/Sylib.jar';
	this.vers[this.vers.length++] = eSignaVersion;
}

function setBasicJars() {
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/SjceB.jar';
	this.vers[this.vers.length++] = '1.3.1.142';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/SjceW.jar';
	this.vers[this.vers.length++] = '1.3.0.2';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/SXMLApacheSecAssembla.jar';
	this.vers[this.vers.length++] = '1.2.1.304';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Scommons-logging.jar';
	this.vers[this.vers.length++] = '2.1.1.2';
	
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/SxercesImpl.jar';
	this.vers[this.vers.length++] = '2.6.0.9262';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Sxalan.jar';
	this.vers[this.vers.length++] = '2.6.0.2';
    this.jars[this.jars.length++] = this.baseurl + 'es-jars/Sswing-layout-1.0.jar';
	this.vers[this.vers.length++] = '2.6.0.2';
}



function setVerifyJars() {
   
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Sjmimemagic-0.0.4a.jar';
	this.vers[this.vers.length++] = '0.0.4.2';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Sjakarta-oro.jar';
	this.vers[this.vers.length++] = '0.0.4.2';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Slog4j.jar';
	this.vers[this.vers.length++] = '0.0.4.2';
}

function setWSJars() {
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Saxis.jar';
	this.vers[this.vers.length++] = '0.1.0.2';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Sjaxrpc.jar';
	this.vers[this.vers.length++] = '0.1.0.2';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Scommons-discovery.jar';
	this.vers[this.vers.length++] = '0.1.0.2';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Ssaaj.jar';
	this.vers[this.vers.length++] = '0.1.0.2';
}

function setPDFJars() {
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Sit.jar';
	this.vers[this.vers.length++] = '1.4.0.1';
}

function setSMIMEJars() {
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Smail.jar';
	this.vers[this.vers.length++] = '1.3.2.1';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/SjceBM.jar';
	this.vers[this.vers.length++] = '1.3.0.141';
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/Sactivation.jar';
	this.vers[this.vers.length++] = '1.0.2.1';
}

function setTSPJars() {
	this.jars[this.jars.length++] = this.baseurl + 'es-jars/SjceBT.jar';
	this.vers[this.vers.length++] = '1.3.1.151';
}

function setCustomParams() {
	return "";
}

function setCustomJars() {
    alert("FF");
}

/* FUNCIONES AUXILIARES */

function xGetElementById(e) {    
  if(typeof(e)!='string') return e;
  if(document.getElementById){ 
        
        if(document.getElementById(e) != null){
            e=document.getElementById(e);
        }else{
            e = document.getElementsByName(e)[0];            
        }        

    }
  else if(document.all) e=document.all[e];
  else e=null;
  return e;
}

function isIE() {
    var browserName=navigator.appName; 
    if (browserName=="Microsoft Internet Explorer"){  
        return true;
    }
    return false;
}

