﻿// Формирует список сертификатов пользователя
function EnumAvaibleCertAppend(certList)
{
  EnumAvaibleCertChoice(certList, true, null, '');
}

function EnumAvaibleCert(certList)
{
    EnumAvaibleCertChoice(certList, false, null, '');
}

function EnumAvaibleCert(certList, singleSigner, SelectedCertHash) {
    EnumAvaibleCertChoice(certList, false, singleSigner, SelectedCertHash);
}

function EnumAvaibleCertChoice(certList, preserve, singleSigner, SelectedCertHash) 
{
	try 
	    {
	    var MyStore = new ActiveXObject("CAPICOM.Store");
	    var FilteredCertificates = new ActiveXObject("CAPICOM.Certificates");
	    }
	catch (e) 
	{
	    alert("<br/>Не установлен объект CAPICOM<br/>");
	    return false;
	}
	try
	{
	   	MyStore.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);
	}
	catch (e)
	{
		if (e.number != CAPICOM_E_CANCELLED)
		{
	    alert("<br/>Ошибка при открытии персонального хранилища сертификатов<br/>");
        return false;
		}
		else {return false;}
	}

	if (typeof(certList).toLowerCase() == "string")
	  certList = document.getElementById(certList);
	if(!preserve && certList && certList.innerHTML)
	    certList.innerHTML = "";

	if (SelectedCertHash == undefined || SelectedCertHash == null)
	    SelectedCertHash = "";
	
    var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_KEY_USAGE,CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE).Find(CAPICOM_CERTIFICATE_FIND_TIME_VALID);
	var oOption;
	if( FilteredCertificates.Count > 0 )
	{
		var sFieldsList;
	    var aFields = new Array();
		for(i = 1; i <= FilteredCertificates.Count; i++) {

		    var signername = FilteredCertificates.Item(i).GetInfo(CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME);
		    if (SelectedCertHash == "") {
		        var checkName = signername.split(' ').join('').toLowerCase();
		        var pos = checkName.indexOf(',', 0);
		        if (pos > -1)
		            checkName = checkName.substring(0, pos);
		        if (singleSigner != null && TrimStr(checkName) != TrimStr(singleSigner.split(' ').join('')).toLowerCase()) continue;

		        oOption = document.createElement("OPTION");
		        certList.add(oOption);
		        oOption.innerText = signername + ' (до:' + FilteredCertificates.Item(i).ValidToDate + ')';
		        oOption.value = FilteredCertificates.Item(i).Thumbprint;
		    }
		    else {
		        if (FilteredCertificates.Item(i).Thumbprint == SelectedCertHash) {
		            oOption = document.createElement("OPTION");
		            certList.add(oOption);
		            oOption.innerText = signername + ' (до:' + FilteredCertificates.Item(i).ValidToDate + ')';
		            oOption.value = FilteredCertificates.Item(i).Thumbprint;
		        }
		    }
		}
	}
	else
	{
	  
	    alert("<br/>Не найдено ни одного действующего сертификата для ЭЦП<br/>");
		return false;
	}

	// Clean Up
	MyStore = null;
	FilteredCertificates = null;
}

// find cert by hash
function FindCertificateByHash(szThumbprint)
{
	// instantiate the CAPICOM objects
	try {
	    var MyStore = new ActiveXObject("CAPICOM.Store");
        }
    catch (e)
    { 
	    alert("<br/>Не установлен объект CAPICOM<br/>");
        return null;
     }
	// 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("<br/>Ошибка при открытии персонального хранилища сертификатов<br/>");
			return null;
		}
	}

	// find all of the certificates that have the specified hash
	var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, szThumbprint);
	if( FilteredCertificates.Count > 0 )
	{
		return FilteredCertificates.Item(1);
	}
	else
	{
	   alert("<br/>Ошибка. Не найден сертификат пользователя<br/>");
		return null;
	}

	MyStore = null;
	FilteredCertificates = null;
}

// find cert by hash
function FindCertificateByHash(szThumbprint) {
  // instantiate the CAPICOM objects
  try {
    var MyStore = new ActiveXObject("CAPICOM.Store");
  }
  catch (e) {
    alert("Не установлен объект CAPICOM");
    return null;
  }
  // 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("Ошибка при открытии персонального хранилища сертификатов.");
      return null;
    }
  }

  // find all of the certificates that have the specified hash
  var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, szThumbprint);
  if (FilteredCertificates.Count > 0) {
    return FilteredCertificates.Item(1);
  }
  else {
    alert("Ошибка. Не найден сертификат пользователя.");
    return null;
  }

  MyStore = null;
  FilteredCertificates = null;
}

// sign data
function SignData(sData, sCertHash) {
  try {
    var SignedData = new ActiveXObject("CAPICOM.SignedData");
    var Signer = new ActiveXObject("CAPICOM.Signer");
    var TimeAttribute = new ActiveXObject("CAPICOM.Attribute");
  }
  catch (e) {
    alert("Не установлен объект CAPICOM ");
    return false;
}

  //sData = sData.replace(String.fromCharCode(10), "\r\n");
// only do this if the user selected a certificate
  if (sCertHash != "") {
      // Set the data that we want to sign
      
    SignedData.Content = sData;
    try {
      // Set the Certificate we would like to sign with
      Signer.Certificate = FindCertificateByHash(sCertHash);
      if (Signer.Certificate == null)
        return false;

      // Set the time in which we are applying the signature
      var Today = new Date();
      TimeAttribute.Name = CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;
      TimeAttribute.Value = Today.getVarDate();
      Today = null;
      Signer.AuthenticatedAttributes.Add(TimeAttribute);

      // Do the Sign operation
      var szSignature = SignedData.Sign(Signer, true, CAPICOM_ENCODE_BASE64);

      return szSignature;
    }
    catch (e) {
      if (e.number != CAPICOM_E_CANCELLED) {
        alert("Ошибка при подписании данных: " + e.description);
        return false;
      }
      else { return false; }
    }
  }
}

function sign(xmlData, certList, sign) {
  sData = $("#"+xmlData).val();
  thumb = $("#"+certList).val();
 try {
    var sSignature = SignData(sData, thumb);
    if (sSignature != null & sSignature != "" & sSignature != false)
     { 
      $("#"+sign).val(sSignature);
     }
    else $("#"+sign).val("");
    return true;
  }
  catch (e) { alert(e);;alert("Произошла ошибка!"); return false;}
}

function clickme() {
}

//<![CDATA[
function DropNonregCert(clientCerts) {
  var regCerts = new Array();
  var idxArr = new Array(); var cntDrop = 0;
   for(var i=1;i<=clientCerts.Count;i++){
    var present = false;
    for(aHash in regCerts)
      {if(regCerts[aHash] == clientCerts.Item(i).Thumbprint) present = true;}
    if(!present){idxArr[cntDrop++]=i;} 
  }
  for (var i = idxArr.length - 1; i >= 0; i--) { clientCerts.Remove(idxArr[i]); } return clientCerts;
} //]]>


