var i, index;
var jscriptURL, appletURL, jssURL;

for (i = 0; i < document.getElementsByTagName("script").length; i ++) {	
	if (document.getElementsByTagName("script")[i].src != null) {
		index = document.getElementsByTagName("script")[i].src.indexOf("WS.js");
		if (index != -1) {
			jscriptURL = document.getElementsByTagName("script")[i].src.substring(0, index);			
			if (jscriptURL == "" || jscriptURL.substring(jscriptURL.length - 1, jscriptURL.length ) != "/") {
				jscriptURL = jscriptURL + "/";
			}
			index = jscriptURL.substring(0, jscriptURL.length - 1).lastIndexOf("/");
			if (index != -1) {
				appletURL = jscriptURL.substring(0, index) + "/cab/";
				jssURL = jscriptURL.substring(0, index) + "/xpi/";
			}
			else {
				appletURL = "cab/";
				jssURL = "xpi/";
			}		
			break;
		}
	}
}

// Shared constants for certificate initialization
var ST_PRI_KEY="PRI";
var ST_PUB_KEY="PUB";
var ST_ALL_KEY="ALL";


var properties = new Object();
var _WEBSIGNER_LOCATION = appletURL;
var _WEBSIGNER_VERSION = '3,5,2,53';


var INSTALLATION_WINDOW_TITTLE = "XPI Installation window";
var INSTALLATION_WINDOW_MESSAGE = "Para la ejecución de ASF debe instalar el componente: ";

// Properties javascript


/* Nombre del elemento Applet. */
properties.initialLoadType = ST_ALL_KEY;

/* Nombre del elemento Applet. */
properties.appletName = "ASF";

/* Directorio donde se encuentra el JAR firmado con el applet de NetScape. */
/* Se supone que estará en un subdirectorio /applet que estará al mismo nivel que el directorio de los js's.*/
properties.appletCodebase		= _WEBSIGNER_LOCATION;
// "./applet"; 
// "https://dirac.tb-solutions.com:8889/asf/applet";
// "http://zaz-vallejod.tb-solutions.com:8080/asf/applet";

properties.appletCode = "com.tbsolutions.asf.websigner.signer.ASF";


/* Archivo con el applet para Netscape Navigator 6.x.  */
properties.appletArchivePlugin		= "ASF_Plugin.jar";

/* Versión requerida de ASF. Version actual del software a instalar. */
properties.appletVersion = "4.25.0.0";

// Si se autoregistra la dll
properties.isAutoInstall = true;

/* Idioma de ASF. */
properties.language = "es";

/* Titulo de la ventana de seleción de perfiles de ASF. */
properties.profileWinTitle = "Selection Profile Window";

var FINAL_REG_NAME = "plugins/@jss32.com/jss32";


// CRYPTOGRAPHIC MODES

var MT_PKCS7 = 1; /// Mode PKCS7
var MT_CMS = 2; /// Mode CMS
var MT_XMLDSIG = 3; /// Mode XMLDSig
var MT_SMIME = 4; /// Mode SMIME

// HASHING ALGORITHMS

var HASH_MD2 = "1.2.840.113549.2.2";
var HASH_MD4 = "1.2.840.113549.2.4";
var HASH_MD5 = "1.2.840.113549.2.5";
var HASH_SHA1 = "1.3.14.3.2.26";

//ASIMMETRIC ALGORITHMS
var RSA="1.2.840.113549.1.1.1";
var DH="1.2.840.10046.2.1";

// SIGNATURE ALGORITHMS
var RSA_ASYMMETRIC_ALGORITHM = 7;
var DSA_ASYMMETRIC_ALGORITHM = 8;
var DIFFIE_HELLMAN_ALGORITHM = 9;

// CERTIFICATE VERIFICATION
var SIGNING_CERT_NO_VERIFY = 0;
var SIGNING_CERT_VALIDITY = 1;
var SIGNING_CERT_FULL = 2;

// INCLUDE CERTS IN SIGNATURE
var NOT_INCLUDE_CERTS = 0;
var INCLUDE_SIGNING_CERT = 1;
var INCLUDE_FULL_PATH = 2;

// En caso de cms el tipo de identificador de certificados seleccionado
var PARAMETER_ISSUER_AND_SERIAL_NUMBER = "1";
var PARAMETER_SUBJECT_KEY_IDENTIFIER = "2";


// NAVIGATOR INFORMATION
var info = navigator.userAgent.toLowerCase();
var majorVersion = parseInt(navigator.appVersion); 
var minorVersion = parseFloat(navigator.appVersion); 

var opera = (info.indexOf("opera") > 0);
var ie = !opera && info.indexOf("msie") > 0 && info.indexOf("win") > 0;
var ie4 = ie && (majorVersion == 4) && (info.indexOf("msie 5")==-1) && (info.indexOf("msie 6")==-1) && (info.indexOf("msie 7")==-1);
var nn = !ie && !opera && (info.indexOf("netscape") >= 0 || info.indexOf("mozilla/4") >= 0 || majorVersion >= 4) && info.indexOf("win16") < 0;
var nn6 = nn && (info.indexOf("mozilla/5") >= 0 || info.indexOf("mozilla/6") >= 0 || info.indexOf("mozilla/7") >= 0  || majorVersion >= 5); //(6 o superior)
var esNN6 = nn && (info.indexOf("netscape6") >= 0  || info.indexOf("netscape/6") >= 0);
var esNN62 = esNN6 && info.indexOf("6.2") >= 0;
var esNN61 = esNN6 && info.indexOf("6.1") >= 0;
var esNN60 = esNN6 && info.indexOf("6.0") >= 0;
var esNN7 = nn && !esNN6 && info.indexOf("netscape/7") >= 0;
var esNN71 = esNN7 && info.indexOf("netscape/7.1") >= 0;
var esNN72 = esNN7 && info.indexOf("netscape/7.2") >= 0;

var esMoz1_4 = nn && nn6 && (info.indexOf("rv:1.4") >= 0 || info.indexOf("rv:1.5") >= 0 || info.indexOf("rv:1.6") >= 0);
var esMoz1_7 = nn && nn6 && (info.indexOf("rv:1.7") >= 0 || info.indexOf("rv:1.8") >= 0);
var esMoz1_0 = nn && nn6 && info.indexOf("rv:1.0") >= 0;


b=navigator;na=b.appName;v=b.appVersion;p=b.platform
var ie5=ie&&(v.indexOf("IE 5")!=-1);
var ie55=ie5&&(v.indexOf("IE 5.5")!=-1);
var ie50=ie5&&(!ie55);
var nn4=nn&&(v.indexOf("4.")==0);


if (navigator.userAgent.indexOf("Linux") >= 0  && (esNN71 || esNN72 || esMoz1_4 || esMoz1_7)) {
	properties.xpiArchive =  jssURL + "jss34LinuxN71.xpi";
} else if (navigator.userAgent.indexOf("Linux") >= 0  && esNN7) {
	properties.xpiArchive =  jssURL + "jss32LinuxN70.xpi";
} else if (navigator.userAgent.indexOf("Linux") >= 0  && (esNN60 || esMoz1_0)) {
	properties.xpiArchive =  jssURL + "jss32LinuxN60.xpi";
} else if (navigator.userAgent.indexOf("Linux") >= 0  && esNN6) {
	properties.xpiArchive =  jssURL + "jss32LinuxN6.xpi";
} else if (esNN71 || esNN72 || esMoz1_4 || esMoz1_7) {
	properties.xpiArchive =  jssURL + "jss34N71.xpi";
} else if (esNN7) {
	properties.xpiArchive =  jssURL + "jss32N70.xpi";
} else if (esNN62) {
	properties.xpiArchive =  jssURL + "jss32N6.xpi";	
} else if (esNN6) {
	properties.xpiArchive =  jssURL + "jss32N6.xpi";
} else if (esNN60) {
	properties.xpiArchive =  jssURL + "jss32N60.xpi";
} else {
	properties.xpiArchive = null;
}

//FUNCTIONS 
/***************************************************
 Name: checkFormat
 Description: Check if the format  is valid
 Input:
 iType: int
 Output:
    boolean
***************************************************/
function checkFormat(iType)
{
    return ((iType==MT_PKCS7) || (iType==MT_CMS) ||(iType==MT_XMLDSIG));
}


/***************************************************
 Name: checkAlgorithm
 Description: Check if the algorithm for sign is valid
 Input:
 sAlgorithm: string with the algorithm.
 Output:
    boolean
***************************************************/
function checkAlgorithm(sAlgorithm)
{
    return ((sAlgorithm==HASH_MD2) || (sAlgorithm==HASH_MD4) || (sAlgorithm==HASH_MD5) || (sAlgorithm==HASH_SHA1));
}


if (ie){
    document.write('<object id="oWebSigner_Crypto"  style="position:absolute;top:50;left=-3"');    
    document.write('codebase="' + _WEBSIGNER_LOCATION + 'WebSigner2.cab#Version=' +  _WEBSIGNER_VERSION + '"');    
    document.write('classid="CLSID:B178DBD1-25DF-4187-9BE0-05D123B91B98" VIEWASTEXT>');    
    document.write('</object>'); 
    
    document.write('<object id="oCAPICOM" style="position:absolute;top:-25;left=-3"');
    document.write('codeBase="' + _WEBSIGNER_LOCATION + 'capicom.cab#version=2,0,0,0"');
    document.write('classid="clsid:A996E48C-D3DC-4244-89F7-AFA33EC60679" VIEWASTEXT>');
    document.write('</object>');
    
    document.write('<script language="JavaScript" src="' + jscriptURL + 'WSIE.js"></script>');
    document.write('<script language="JavaScript" src="' + jscriptURL + 'WSIE_const.js"></script>');
    document.write('<script language="JavaScript" src="' + jscriptURL + 'WSIE_utils.js"></script>');
    
    
    
}
if (nn6){
    document.write('<script language="JavaScript" src="' + jscriptURL + 'WSNN_const.js"></script>');
    document.write('<script language="JavaScript" src="' + jscriptURL + 'WSNN_utils.js"></script>');
    document.write('<script language="JavaScript" src="' + jscriptURL + 'WSNN.js"></script>');

    var ready = false;
    
    if (properties.isAutoInstall)
    {      	  
      	ready = promtForInstallation() ; // establece si esta todo inicializado o no  
      	if (ready == true) {
      		properties.appletFirstInstallation = false;
      	} else {
      		properties.appletFirstInstallation = true;
      	}    	  
    } else
    {
      	ready = true;
    }  
    
          
   
    if (ready) {
    	//firstInstall = false;
        properties.appletInitialized = true;
        properties.appletCertificatesLoaded = true;
    
    	if (esNN7 || esMoz1_4 || esMoz1_7){// El navegador es 7.0 o superior
	        // Inicialmente el applet estará escondido !!
	        document.write  ('<OBJECT TYPE="application/x-java-vm" width="1" height="1"');
	        document.write  (' NAME="'+ properties.appletName +'"');
	        document.write  (' ID="' + properties.appletName +'"');
	        document.writeln('>');
	
	        //document.writeln('<PARAM NAME="cache_option" VALUE="No">');
	        document.writeln('<PARAM NAME="cache_archive" VALUE="' + properties.appletArchivePlugin +'">');
	        document.writeln('<PARAM NAME="cache_version" VALUE="1.2.0.1, 2.1.1.2, 1.1.2.7">');
	
	        document.writeln('<PARAM NAME="NAME" VALUE="' + properties.appletName +'">');
	        document.writeln('<PARAM NAME="CODE" VALUE="' + properties.appletCode +'">');
	        document.writeln('<PARAM NAME="CODEBASE" VALUE="' + properties.appletCodebase +'">');
	
	        document.writeln('<PARAM NAME="mayscript" VALUE="true">'); 
	        document.writeln('<PARAM NAME="SCRIPTABLE" VALUE="true">');
	        
	        document.writeln('<PARAM NAME="CABBASE" VALUE="' + properties.appletCab +'">');
	        document.writeln('<PARAM NAME="CABINETS" VALUE="' + properties.appletCab +'">');
	        
	        document.writeln('<PARAM NAME="WINDOWTITLE" VALUE="' + properties.windowTitle +'">');
	        document.writeln('<PARAM NAME="LANGUAGE" VALUE="' + properties.language +'">');
   		
   		document.writeln('<PARAM NAME="LOADTYPE" VALUE="' + properties.initialLoadType +'">');
   		document.writeln('<PARAM NAME="PROFILEWINTITLE" VALUE="' + properties.profileWinTitle +'">');
	
	        document.writeln('<p>You need the Java Plugin.Get it from <a href="http://java.sun.com/products/plugin/index.html">here.</a></p>');
	        document.write ('</object>');
	    } else {// El navegador es NetScape 6.x 
	        document.write  ('<APPLET');
	        document.write  (' NAME="'+ properties.appletName +'"');
	        document.write  (' CODE="' + properties.appletCode +'"');
	        document.write  (' CODEBASE="' + properties.appletCodebase + '"');
	        document.write  (' ARCHIVE="' + properties.appletArchivePlugin + '"');
	        document.write  (' WIDTH="1"');
	        document.write  (' HEIGHT="1"');
	        document.write  (' SCRIPTABLE=true');
	        document.write  (' MAYSCRIPT');
	        document.writeln('>');
	        
	        document.writeln('<PARAM NAME="NAME" VALUE="' + properties.appletName +'">');
	        document.writeln('<PARAM NAME="CODE" VALUE="' + properties.appletCode +'">');
	        document.writeln('<PARAM NAME="CODEBASE" VALUE="' + properties.appletCodebase +'">');
	
	        //document.writeln('<PARAM NAME="mayscript" VALUE="true">'); 
	
	        document.writeln('<PARAM NAME="ARCHIVE" VALUE="' + properties.appletArchivePlugin +'">');
	        
	        document.writeln('<PARAM NAME="MAYSCRIPT" VALUE="true">');
	        document.writeln('<PARAM NAME="SCRIPTABLE" VALUE="true">');
	        
	        document.writeln('<PARAM NAME="WINDOWTITLE" VALUE="' + properties.windowTitle +'">');
	        document.writeln('<PARAM NAME="LANGUAGE" VALUE="' + properties.language +'">');
	        document.writeln('<PARAM NAME="LOADTYPE" VALUE="' + properties.initialLoadType +'">');
	        
	        document.writeln('</APPLET>');		
	    }
	/* // BETER TAGS FOR SOME BROWSERS
	document.write  ('<EMBED');
	document.write  (' type="application/x-java-applet;version=1.4"'); //width="0" height="0"
	document.write  (' java_CODE = "' + properties.appletCode +'"');
	document.write  (' ID="' + properties.appletName +'"');
	document.write  (' java_CODEBASE = "' + properties.appletCodebase + '"');
	document.write  (' java_ARCHIVE = "' + properties.appletArchivePlugin + '"');
	document.write  (' java_NAME="' + properties.appletName +'"');
	document.write  (' pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html"');
	
	document.write (' NAME="NAME" VALUE="' + properties.appletName +'"');
        document.write (' NAME="CODE" VALUE="' + properties.appletCode +'"');
        document.write (' NAME="CODEBASE" VALUE="' + properties.appletCodebase +'"');
        document.write (' NAME="ARCHIVE" VALUE="' + properties.appletArchivePlugin +'"');        
        document.write (' NAME="MAYSCRIPT" VALUE="true"');
        document.write (' NAME="SCRIPTABLE" VALUE="true"');       
        document.write (' NAME="WINDOWTITLE" VALUE="' + properties.windowTitle +'"');
        document.write (' NAME="LANGUAGE" VALUE="' + properties.language +'"');
        document.write (' NAME="LOADTYPE" VALUE="' + properties.initialLoadType +'"');
	document.writeln ('>');
	
	document.writeln ('<NOEMBED>');
	document.writeln ('<p>You need the Java Plugin.Get it from <a href="http://java.sun.com/products/plugin/1.4/plugin-install.html">here.</a></p>');
	document.writeln ('</NOEMBED>');
	document.writeln ('</EMBED>');
	*/
    } else {
    	properties.appletInitialized = false;
        properties.appletCertificatesLoaded = false;
    }
}
if (nn4)
{
	alert("The navigator´s version is unsupported");
}

var installation_result = null;
var promtWindow = null;
function promtForInstallation(actualToken) {  
    if ( navigator.javaEnabled() ) {
        if (navigator.mimeTypes && navigator.mimeTypes["application/x-jss32"] && navigator.mimeTypes["application/x-jss32"].enabledPlugin) {
            return true;
        } else {
            var xpi = new Object();
            var result = InstallTrigger.compareVersion(FINAL_REG_NAME, properties.appletVersion);	 
            if (result  < 0) {
            	if (esNN62) {
            		confirm_entry();	
            	} else { 
	            	promtWindow = window.open(jscriptURL + 'prompt.htm',INSTALLATION_WINDOW_TITTLE,'width=440,height=60'); //'width=488,height=100'
		    	////promtWindow.XPI_ARCHIVE = properties.xpiArchive ;
		    	////promtWindow.FINAL_REG_NAME = FINAL_REG_NAME ;
		    	promtWindow.focus();
		    	if (esNN61 || esNN60 || esNN71 || esMoz1_4 || esMoz1_7) {
		    		waitN61DllDownload();
		    	}
		    	//waitForInstallation();
		    	//waitForAppletInitialized();
		}
	    	return false;
            } else { 
            	return true;
            } 
        } 
    } else {
        alert("Para la ejecución de ASF debe tener habilitado Java en su navegador.");
    }  
    return true;    
}

function waitN61DllDownload() {
	if  (!installation_result) {
		// Lanzamos un nuevo thread (en espera) para comprobar la finalización del acceso al almacén !
        	window.setTimeout('waitN61DllDownload()', 3000);
	} else {
		promtWindow.close();
	}
}

function cancelar() {
    if (promtWindow != null) promtWindow.close();
    alert(DLL_NOT_INSTALL);
}

function confirm_entry() {
	var index = properties.xpiArchive.lastIndexOf("/");
	var XPI_NAME = null; 
	if (index != -1) {
	    XPI_NAME = properties.xpiArchive.substring(index+1, properties.xpiArchive.length);
	}
	input_box=confirm(INSTALLATION_WINDOW_MESSAGE + "\n" + XPI_NAME + "\n \n" + "Después de la instalación del componente debe recargar la página");
	if (input_box==true) { 	
		var comandoEval =  "xpi={'" + FINAL_REG_NAME + "':'" + properties.xpiArchive + "'}";
		eval(comandoEval) ;           
		InstallTrigger.install(xpi,xpinstallCallback);    
	} 
}

function xpinstallCallback(url, status)
{
	window.opener.installation_result = true;
	window.opener.promtWindow = window;
  
	if (status == 0) {
	msg = "XPInstall Test:   PASSED\n";
	// no imprimimos el mensaje de exito (demasiados mensajes)  
	}else{
	msg = "XPInstall Test:   FAILED\n";
	dump(msg);
	}    
}


function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}

