var CAPICOM_STORE_OPEN_READ_ONLY = 0;
var CAPICOM_CURRENT_USER_STORE = 2;
var CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0;
var CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY = 6;
var CAPICOM_CERTIFICATE_FIND_TIME_VALID = 9;
var CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1;
var CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12;
var CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 0x00000080;
var CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
var CAPICOM_INFO_SUBJECT_SIMPLE_NAME = 0;
var CAPICOM_ENCODE_BASE64 = 0;
var CAPICOM_E_CANCELLED = -2138568446;
var CERT_KEY_SPEC_PROP_ID = 6;
var CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
var CAPICOM_VERIFY_SIGNATURE_AND_CERTIFICATE = 1;
var CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME = 0;

function MM_displayStatusMsg(msgStr) {status=msgStr; document.MM_returnValue = true;}
function adicionarfavoritos(){window.external.AddFavorite('http://www.exsign.com.br',".:: Família XSign ::.");}
function open_link(link) {if (link != '#') {window.open (link);}}

function display_padrao()
{
   MM_displayStatusMsg('.:: Centro de Certificação Digital ::.'); return document.MM_returnValue = true;
}

function SolicitarCertificado() 
{
   window.open("https://www.acxsign.com.br/acadmin/passo1.asp", "solicitarcertificado","status=yes,location=no,directories=no,menubar=no,scrollbars=yes,resizable=no,width=" + (screen.width - 10) + ",height=" + (screen.height - 70) + ",top=0,left=0");	
}

function SolicitarCertificadoCliente(tipocliente, certificado) 
{
   window.open("https://www.acxsign.com.br/acadmin/passo1.asp?id=1UjagbUyhIokm85fR5ty09dctag6H8juksbyk2695sdjT152&action=1&tipocliente=" + tipocliente + "&certificado=" + certificado, "solicitarcertificado","status=yes,location=no,directories=no,menubar=no,scrollbars=yes,resizable=no,width=" + (screen.width - 10) + ",height=" + (screen.height - 70) + ",top=0,left=0");	
}

function Tecla(e)
{
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = e.which;
		if (tecla > 47 && tecla < 58) // numeros de 0 a 9
			return true;
		else
			{
				if (tecla != 8) // backspace
					event.keyCode = 0;
					//return false;
				else
					return true;
			}
}


function isMail(strMail){
  var re = new RegExp;
  re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  var arr = re.exec(strMail);
  if (arr == null)
    return(false);
  else
    return(true);
}

function minLen(txtField, minVal){
  strExp = txtField.value;
  l = strExp.length;
  if (l < minVal)
    return(true);
  else
    return(false);
}

function maxLen(txtField, maxVal){
  strExp = txtField.value;
  l = strExp.length;
  if (l > maxVal)
    return(true);
  else
    return(false);
}

function isBlank(txtField){
  if (txtField.value)
    return (false);
  else
    return(true);
}

function isSelectedZero(txtField){
  selected = txtField.selectedIndex;
  if (selected == 0)
    return(true);
  else
    return(false);
}

function isNumber(txtField){
  numExp = txtField.value;
  if (isNaN(numExp) || (numExp.length == 0))
    return (false);
  else
    return(true);
}

function isCPF(cpfvalue){ 

  if (cpfvalue=='000.000.000-00') return false; 
  if (cpfvalue=='111.111.111-11') return false;
  if (cpfvalue=='222.222.222-22') return false;
  if (cpfvalue=='333.333.333-33') return false;
  if (cpfvalue=='444.444.444-44') return false;
  if (cpfvalue=='555.555.555-55') return false;
  if (cpfvalue=='666.666.666-66') return false;
  if (cpfvalue=='777.777.777-77') return false;
  if (cpfvalue=='888.888.888-88') return false;
  if (cpfvalue=='999.999.999-99') return false;

  var i; 
  s = cpfvalue;  
  s = s.replace(".","");
  s = s.replace(".","");
  s = s.replace("-","");
  var c = s.substr(0,9); 
  var dv = s.substr(9,2); 
  var d1 = 0; 
  
  for (i = 0; i < 9; i++){ 
    d1 += c.charAt(i)*(10-i); 
  } 
  
  if (d1 == 0) return false;   
  
  d1 = 11 - (d1 % 11); 
  
  if (d1 > 9) d1 = 0; 
  
  if (dv.charAt(0) != d1) return false; 
  
  d1 *= 2; 
  
  for (i = 0; i < 9; i++){ 
    d1 += c.charAt(i)*(11-i);   
  } 
  
  d1 = 11 - (d1 % 11); 
  
  if (d1 > 9) d1 = 0; 
  
  if (dv.charAt(1) != d1) return false; 
  
  return true; 
  
}

function isNUMB(c) 
 { 
 if((cx=c.indexOf(","))!=-1) 
  { 
  c = c.substring(0,cx)+"."+c.substring(cx+1); 
  } 
 if((parseFloat(c) / c != 1)) 
  { 
  if(parseFloat(c) * c == 0) 
   { 
   return(1); 
   } 
  else 
   { 
   return(0); 
   } 
  } 
 else 
  { 
  return(1); 
  } 
 } 

function LIMP(c) 
 { 
 while((cx=c.indexOf("-"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("/"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(","))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("."))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("("))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(")"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(" "))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 return(c); 
 } 

function isCNPJ(CNPJ) 
 { 
 CNPJ = LIMP(CNPJ); 
 if(isNUMB(CNPJ) != 1) 
  { 
  return(0); 
  } 
 else 
  { 
  if(CNPJ == 0) 
   { 
   return(0); 
   } 
  else 
   { 
   g=CNPJ.length-2; 
   if(RealTestaCNPJ(CNPJ,g) == 1) 
    { 
    g=CNPJ.length-1; 
    if(RealTestaCNPJ(CNPJ,g) == 1) 
     { 
     return true; 
     } 
    else 
     { 
     return false; 
     } 
    } 
   else 
    { 
    return false; 
    } 
   } 
  } 
 } 

function RealTestaCNPJ(CNPJ,g) 
 { 
 var VerCNPJ=0; 
 var ind=2; 
 var tam; 
 for(f=g;f>0;f--) 
  { 
  VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind; 
  if(ind>8) 
   { 
   ind=2; 
   } 
  else 
   { 
   ind++; 
   } 
  } 
  VerCNPJ%=11; 
  if(VerCNPJ==0 || VerCNPJ==1) 
   { 
   VerCNPJ=0; 
   } 
  else 
   { 
   VerCNPJ=11-VerCNPJ; 
   } 
 if(VerCNPJ!=parseInt(CNPJ.charAt(g))) 
  { 
  return(0); 
  } 
 else 
  { 
  return(1); 
  } 
 } 

function DownloadCertificado(requisicao) 
{

    location = "certificado.cer?ID=G174e169T40290c4630E249r4721527T102i66f25I159c578A612d9656o&ReqID=" + requisicao;

}

function DownloadCertificadoWEB() 
{

    location = "certweb.cer?ID=G125e589T4152c4570E269r402859T12i596f25I1479c5489A639d966o";

}
  

function FormataCGC(Formulario, Campo, TeclaPres) 
  { 
    var tecla = TeclaPres.keyCode; 
    var strCampo; 
    var vr; 
    var tam; 
    var TamanhoMaximo = 14; 
  
    eval("strCampo = document." + Formulario + "." + Campo); 
  
    vr = strCampo.value; 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace(",", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    tam = vr.length; 

    if (tam < TamanhoMaximo && tecla != 8) 
    { 
      tam = vr.length + 1; 
    } 

    if (tecla == 8) 
    { 
      tam = tam - 1; 
    } 

    if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105) 
    { 
      if (tam <= 2) 
      { 
        strCampo.value = vr; 
      } 
       if ((tam > 2) && (tam <= 6)) 
       { 
         strCampo.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam); 
       } 
       if ((tam >= 7) && (tam <= 9)) 
       { 
         strCampo.value = vr.substr(0, tam - 6) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 10) && (tam <= 12)) 
       { 
         strCampo.value = vr.substr(0, tam - 9) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 13) && (tam <= 14)) 
       { 
         strCampo.value = vr.substr(0, tam - 12) + '.' + vr.substr(tam - 12, 3) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 15) && (tam <= 17)) 
       { 
         strCampo.value = vr.substr(0, tam - 14) + '.' + vr.substr(tam - 14, 3) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam); 
      } 
    } 
  } 

function FormataCpf(campo,tammax,teclapres) {
 var tecla = teclapres.keyCode;
  
 vr = event.srcElement.value;
 vr = vr.replace( "/", "" );
 vr = vr.replace( "/", "" );
 vr = vr.replace( ",", "" );
 vr = vr.replace( ".", "" );
 vr = vr.replace( ".", "" );
 vr = vr.replace( ".", "" );
 vr = vr.replace( ".", "" );
 vr = vr.replace( "-", "" );
 vr = vr.replace( "-", "" );
 vr = vr.replace( "-", "" );
 vr = vr.replace( "-", "" );
 vr = vr.replace( "-", "" );
 tam = vr.length;

 if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

 if (tecla == 8 ){ tam = tam - 1 ; }
  
 if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
  if ( tam <= 2 ){ 
    event.srcElement.value = vr ; }
   if ( (tam > 2) && (tam <= 5) ){
    event.srcElement.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
   if ( (tam >= 6) && (tam <= 8) ){
    event.srcElement.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
   if ( (tam >= 9) && (tam <= 11) ){
    event.srcElement.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
   if ( (tam >= 12) && (tam <= 14) ){
    event.srcElement.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
   if ( (tam >= 15) && (tam <= 17) ){
    event.srcElement.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
 }  
}

function TimeStamp()
{
   var now = new Date();
   var hour = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   var dia = now.getDay()
   var mes = now.getMonth()
   var ano = now.getYear()
   
   return dia + "/" + mes + "/" + ano + " " + hour + ":" + minute + ":" + second;

}

function AssinarDigitalmente(ThumbPrint, Transacao)
{
   // instantiate the CAPICOM objects
   var MyStore = new ActiveXObject("CAPICOM.Store");
   var SignOBJ = new ActiveXObject("CAPICOM.SignedData");
   var Signer = new ActiveXObject("CAPICOM.Signer");
   var FilteredCertificates = new ActiveXObject("CAPICOM.Certificates");
   var Signture = "";

   try
   {
	MyStore.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);
   }
	catch (e)
   {
	if (e.number != 0)
		{
   			alert("Você cancelou a leitura do seu certificado digital, sua solicitação não será processada.");
			return false;
		}
   }

      try
   {
	var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, ThumbPrint);
   	Signer.Certificate = FilteredCertificates.Item(1);
   }
	catch (e)
   {
	if (e.number != 0)
		{
   			alert("Não foi possível localizar sua assinatura digital para completar a transação solicitada.\nVerifique se seu Smart Card ou Token estão instalados corretamente no computador.");
			return false;
		}
   }
   
   SignOBJ.Content = Transacao;
    
   try
   {	
	Signture = SignOBJ.Sign(Signer)
	return Signture;
   }
	catch (e)
   {
	if (e.number != 0)
		{
   			alert("Não foi possível obter sua assinatura digital para completar sua solicitação.\nVerifique se sua senha foi digitada corretamente.");
			return false;
		}
   }
   
}

function VerificarAssinatura(Signture)
{
   // instantiate the CAPICOM objects
   var SignOBJ = new ActiveXObject("CAPICOM.SignedData");
   var Signer = new ActiveXObject("CAPICOM.Signer");
   var Transacao = "";

   try
   {
	   	SignOBJ.Verify(Signture);
   }
       catch (e)
   {
		if (e.number != 0)
			{
   				alert("A assinatura digital informada esta inválida");
				return false;
			}
   }

	Signer = SignOBJ.Signers.Item(1);
	Transacao = SignOBJ.Content;
	alert("A assinatura digital verificada com sucesso!!\n\n" + Transacao + "\n\n" + "Assinado Digitalmente por: \n" + Signer.Certificate.GetInfo(0) + "\n" + Signer.Certificate.GetInfo(1) + "\n" + Signer.Certificate.GetInfo(2));
}

function LoginCentroCertificacao()
{
   // Filter the certificates to only those that are good for my purpose
   var FilteredCertificates = FilterCertificates();
   var Transacao = "Login no Centro de Certificação Digital";

   // if only one certificate was found then lets show that as the selected certificate
   if (FilteredCertificates.Count == 1)
   {
	var ThumbPrint = FilteredCertificates.Item(1).Thumbprint;
	var assinatura = AssinarDigitalmente(ThumbPrint, Transacao)	 
	if (assinatura == "")
	{
		document.frmCertificate.assinatura.value = "";
		document.frmCertificate.hash.value = ""; 
		document.frmCertificate.email.value = "";
		document.frmCertificate.timestamp.value = "";
	} else {
		document.frmCertificate.assinatura.value = assinatura;
		document.frmCertificate.hash.value = FilteredCertificates.Item(1).Thumbprint; 
		document.frmCertificate.email.value = FilteredCertificates.Item(1).GetInfo(2);
		document.frmCertificate.timestamp.value = TimeStamp();
	}
   } else {
	document.frmCertificate.assinatura.value = "";
	document.frmCertificate.hash.value = ""; 
	document.frmCertificate.email.value = "";
	document.frmCertificate.timestamp.value = "";
   }

   // clean up	
   FilteredCertificates = null;
}

   function FilterCertificates()
   {
	   // instantiate the CAPICOM objects
	   var MyStore = new ActiveXObject("CAPICOM.Store");
	   var FilteredCertificates = new ActiveXObject("CAPICOM.Certificates");
	   	   	   
	   // open the current users personal certificate store
	   try
	   {
	   	MyStore.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);
	   }
	   catch (e)
	   {
		if (e.number == CAPICOM_E_CANCELLED)
		{
	   		alert("Não foi possível acessar a chave pública do seu certificado digital. Aguarde pois a página será relida, clique em Yes para que o site acesse seu certificado");
			window.history.go(0);
	   		return false;
		}
	   }

		try
	   {
	   var FilteredCertificates = MyStore.Certificates;
  	   var FilteredCertificates = FilteredCertificates.Select("Certificado Digital ", "Selecione o certificado digital para que você possa assinar eletronicamente a fatura eletrônica", "false");	
	   }	
	   catch (e)
	   {
		if (e.number == CAPICOM_E_CANCELLED)
		{
			alert("Não foi possível acessar a chave pública do seu certificado digital.");
		}
	   }
	   return FilteredCertificates;

	   // Clean Up
	   MyStore = null;
	   FilteredCertificates = null;
}


function CheckCAPICOM()
{
	   try
	   {
		        var FilteredCertificates = new ActiveXObject("CAPICOM.Certificates");
		   	return true;
	   }
	   		catch (e)
	   {
			alert("Solicitação Cancelada!!! Não foi detectado o biblioteca Microsoft CAPICOM instalada em seu computador. Possivelmente você cancelou a instalação automática da Biblioteca ou uma barra superior desta página foi exibida para que você aceite a instalação.\n\nEssa biblioteca é necessária para seu certificado digital possa ser instalado corretamente. Lembre-se!!! Você está operando em um Ambiente totalmente seguro.");
			return false;		
	   }

	   MyStore = null;
}

function FindCertificateByHash(szThumbprint)
{
	   // instantiate the CAPICOM objects
	   var MyStore = new ActiveXObject("CAPICOM.Store");

	   // open the current users personal certificate store
	   try
	   {
	   	MyStore.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);
	   }
	   catch (e)
	   {
		if (e.number != 0)
		{
	   		alert("Você cancelou a leitura do seu certificado, Clique em F5 e clique em sim para a mensagem de segurança");
			return false;
		}
	   }

	   // find all of the certificates that have the specified hash
	   var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, szThumbprint);

	   MyStore = null;
	   FilteredCertificates = null;
}

function FindCertificateByName(NameCertificate)
{
	   // instantiate the CAPICOM objects
	   var MyStore = new ActiveXObject("CAPICOM.Store");

	   // open the current users personal certificate store
	   try
	   {
	   	MyStore.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);	   	
		var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME, NameCertificate, true);
		return FilteredCertificates;
	   }
	   catch (e)
	   {
		if (e.number != 0)
		{
	   		alert("Não foi possível localizar nenhum certificado digital para do cliente\n" + NameCertificate);
			return false;
		}
	   }
	   MyStore = null;
	   FilteredCertificates = null;
}

function FilteredCertificateBySerial(Certificates, Serial, Mensage)
{

	   // open the current users personal certificate store
	   //var i = 0;
	   var branco = "";
	   var zero = "0";
	   var Totalcertificados = 0;  	  
	   try
	   {
	   	Totalcertificados = Certificates.count;
		if (Totalcertificados > 0) 
		{	
			if (Mensage == true)
			{
				alert("Foram Encontrados " + Totalcertificados + " certificados digitais neste computador. Aguarde até que seja localizado o certificado correto.");
			}
	
			for (i = 1; i = Totalcertificados; i++)
			{ 
				var MyCertificate = Certificates.Item(i);
				if (MyCertificate.SerialNumber == Serial)
				{
					return MyCertificate.Thumbprint;									
				}
  			} 
			return branco;

		} else {
			return zero;
		}		 
	   }
	   catch (e)
	   {
		if (e.number != 0)
		{
	   		alert("Erro ao filtrar certificado digital. Não foi localizado nenhum certificado digital.");
			return branco;
		}
	   }
}

function delay(Amount)
{
	d = new Date() //today's date
	while (1)
	{
		mill=new Date() // Date Now
		diff = mill-d //difference in milliseconds
		if( diff > Amount ) {break;}
	}
}

function VerificaCertificadoWEBSeguro()
{
	var ID = "By1R24F1Vod5as7w45d2f4ds52dyTFd54p4jg5drU6h53UsNd2K6W5aTs3fs6er9fg8V514sfdQ54F5h2jsyT0H19k56fd012s24ih21G";
	var Serial = "149c44dd000000000196";
	var AC = "1";

    	window.open("https://www.acxsign.com.br/acadmin/selosslweb.asp?id=" + ID + "&ac=" + AC + "&serial=" + Serial, "selosslweb","status=yes,location=no,directories=no,menubar=no,scrollbars=no,resizable=no,width=630,height=430,top=50,left=50");	
}
