/* create date  : 2002-05-25
   author       : sword  , jgchen@cn.ibm.com
				: Roy , SSEInfoNet Ltd.
   last updated : 2004-3-23
   decription   : PKI Framework client API , user to verify cert , construct secure connection with server,
                  secure package in client side etc
	Update for : Use ekey without cookie, Roy
  

*/

var ERR_SIGN              = "签名失败";
var ERR_RANDNUM_SIGN      = "随机数签名失败";
var ERR_ENCRYPT           = "加密失败";
var ERR_DECRYPT           = "解密失败";
var ERR_INITIALIZE        = "控件初始化失败";
var ERR_READ_CERT         = "读取证书失败";
var ERR_READ_CLIENT_CERT  = "读取客户端证书失败";
var ERR_READ_CLIENT_CERTID= "读取客户端证书用户ID失败";
var ERR_READ_CLIENT_CERTSERIALNUMBER= "读取客户端证书序号失败";
var ERR_READ_THIRD_CERT   = "读取第三方证书失败";
var ERR_READ_PIN          = "读取PIN码失败";
var ERR_READ_RANDNUM      = "读取随机数失败";
var ERR_READ_RANDNUM_SIGN = "没有得到随机数签名";
var ERR_LOGIN_DISA        = "登录失败，请依次确认:\r\n  您的密码(PIN码)是否正确,连续输入3次错误密码EKey将被锁定\r\n  您的计算机上是否有别的进程正在使用EKey\r\n  您的EKey是否插入到计算机上\r\n  您的计算机上是否安装了驱动程序 ";
var ERR_LOGOUT_DISA       = "注销实体密码鉴别器失败";
var ERR_AUTH_CERT         = "服务器证书未通过验证!";
var ERR_AUTH_RANDNUM_SIGN = "随机数签名未通过验证!";
var ERR_AUTH_SIGN         = "签名未通过验证!";
var ERR_READ_FILE         = "读取文件失败";
var ERR_EMPTY_ELEMENT     = "表单元素空";
var ERR_ENCODE            = "Base64编码失败";
var ERR_DECODE            = "Base64解码失败";
var ERR_READ_EKEYID	  = "读取证书序号失败";
var ERR_GET_CERT          = "获取证书失败";
var ERR_EMPTY_FORM        = "表单对象空" ;
var ERR_EMPTY_SECUREMSG   = "密文串为空" ;
var ERR_MODE		      = "签名或者加密参数不正确" ;
var ERR_RECEIVE_MSG       = "接收失败" ;
//roy add 20030828
var ERR_NULL_PASS         = "请输入PIN码";

var RTN_OKAY              = "OKAY";

var FLG_NULL              = 0;                  //不作任何签名加密
var FLG_SIGN			  = 1;                  //仅作签名
var FLG_ENCRYPT_SIGN      = 2;                  //签名和加密


var DISA_LOGIN            = 0;                  // 0:表示尚未登陆到Disa  1:表示已经登陆到Disa
var MAX_FILE_SIZE         = 1048000;           // Max File Size     

// get cookie by cookie name
function getCookie(name)
{
	
    var cookies=document.cookie;
    var start=-1;
    var end=-1;


    var rtn=null;

    if(cookies.length>0)
    {
        start=cookies.indexOf(name);
        if(start!=-1)
        {
            start+=name.length+1;
            end=cookies.indexOf(";",start);
            if(end == -1)
            {
                end =cookies.length;
            }
            rtn=cookies.substring(start,end);
        }
    }
    return rtn;
}

// Create Formated ClientCert Object

function CCert(clientCert,randnum,randnumSign,clientCertID,eKeyID){
    this.clientCert  = clientCert; 
	this.randnum    = randnum;
	this.randnumSign = randnumSign;
	this.clientCertID = clientCertID;
	this.eKeyID=eKeyID;
}

// Create Formated Form String
function SForm(strForm){
	this.strForm  =strForm; 
	this.getValue =getValue;
	this.getValues=getValues;
	this.getFileStr   = getFileStr;
	this.getFileName  = getFileName;

	function getValue(name){
		var start=-1;
		var end=-1;
		var rtn=null;
		if(strForm.length>0)
		{
			start=strForm.indexOf("<"+name+">");
			if(start!=-1)
			{  
				start+=name.length+2;
				end =strForm.indexOf("</"+name+">");
				if(end == -1)
				{
					end =strForm.length;
				}
				rtn=strForm.substring(start,end);
			}
		}
		return rtn;
	 }

	 function getValues(name){
		var arrayValues = new Array();
		var strTemp = strForm;
		var i=0;

		while (getValue(name)!=null)
		{   
			arrayValues[i] = getValue(name);
			strForm = strForm.substring(strForm.indexOf("</"+name+">")+name.length+3,strForm.length);
			i++;
		}
		strForm=strTemp;
		return arrayValues;
	 }

	function getFileName(tagName){
		var start=-1;
		var end=-1;
		var fileName=null;

		var strTemp;

		if (strForm.length<=0) return null;

	 	start=strForm.indexOf("<"+tagName);
		if (start == -1) return null;
 
		strTemp=strForm.substring(start);
		end = strTemp.indexOf(">");
		if (end==-1) return null;

		strTemp = strTemp.substring(0,end);

		if  (strTemp.indexOf("type=file")==-1)   return  null;  // not file

		if ((start=strTemp.indexOf("name='"))==-1)   return  null;       // no param name

		strTemp = strTemp.substring(start+6);

		if ((end=strTemp.indexOf("'"))==-1)  fileName=strTemp;
		else fileName = strTemp.substring(0,end);
		return fileName;
	}	

	function getFileStr(tagName){
		var start=-1;
		var end=-1;

		var strTemp;

		if (strForm.length<=0) return null;

	 	start=strForm.indexOf("<"+tagName);
		if (start == -1) return null;
 
		strTemp=strForm.substring(start);
		end = strTemp.indexOf(">");
		if (end==-1) return null;

		strTemp = strTemp.substring(0,end);
        
		if  (strTemp.indexOf("type=file")==-1)   return  null;  // not file

		strTemp = strForm.substring(start+end+1);
		end =strTemp.indexOf("</"+tagName+">");
		if (end == -1)  return strTemp.substring(0);
		return strTemp.substring(0,end);
	}

}

// verify each other,Parameter form present formID, Parameter objectID presnet Active Control Object ID Parameter mode = 0 presnet not to encrypt and sign , mode=1 presnet only sign mode=2 present sign and encry
function checkActiveX(objCert)                  
{
    var serverCert,randnum,randnumSign,clientCert,clientCertID,eKeyID;
    var PIN;

    serverCert = getCookie("serverCert");
	if (serverCert == null)	return ERR_READ_CERT;          // fail to read certificate of server
	
    randnum=getCookie("randnum");
	if (randnum == null)  return ERR_READ_RANDNUM;          // fail to read random number
	
    randnumSign=getCookie("randnumSign");
	if (randnumSign == null)	return ERR_READ_RANDNUM_SIGN; // fail to get signature of random number
	

	if(!mytest.IsLogin()){
		mytest.InitActV();
		if(mytest.Status<0)  return ERR_INITIALIZE;             //ActiveX control object Initializtion failure

			
		//PIN=document.submitForm.keyPin.value;	
	
		mytest.login(document.submitForm.keyPin.value);                    //Login Disa use current PIN
		if (mytest.Status<0)	return  ERR_LOGIN_DISA; //Fail to login use current PIN
	 	//document.cookie ="PIN="+PIN+";PATH=/" ;  //set pin in cookie which will be used in the whole session
	}
	
	 //DISA_LOGIN = 1 ;                          // Disalogin =1 represent disa has been logged in 

	 mytest.VerifyCertString(serverCert);
     if(mytest.Status<0) return ERR_AUTH_CERT; //Server Certification authorization  failed
  
	 mytest.VerifySign(serverCert,randnum,randnumSign);
	 if( mytest.Status<0 ) return ERR_AUTH_RANDNUM_SIGN; //RandNum  authorization  failed
 
	 clientCert=mytest.GetCertString();
     if(mytest.Status<0) return  ERR_READ_CLIENT_CERT; //Fail to get client cert
  
  	 clientCertID=mytest.GetCertUserID();
	 if(mytest.Status<0) return  ERR_READ_CLIENT_CERTID; //Fail to get client cert
	 
	 
	 eKeyID=mytest.GetCertSerialNumber();
	 
	if (mytest.Status<0) return ERR_READ_EKEYID;  //
	
	 randnumSign=mytest.SignData(PIN,randnum);  
   	 if (mytest.Status<0) return ERR_RANDNUM_SIGN;  //
	
	
	
      objCert.clientCert = clientCert;
      objCert.randnum  = randnum;
	  objCert.randnumSign = randnumSign;
	  objCert.clientCertID = clientCertID;
	  objCert.eKeyID = eKeyID;
	 
	  return RTN_OKAY;
}

function checkexpiretime(expiretime)
{
	   var eyear = expiretime.substring(0, 4);
	   var emonth = expiretime.substring(4, 6);
	   var eday = expiretime.substring(6, 8);
	   var today = new Date();    
	   var cday = today.getDate();    
	   var cmonth = today.getMonth() + 1;    
	   var cyear = today.getYear();    

	   var leftday = (eyear-cyear)*365+(emonth-cmonth)*30 + (eday-cday);
	   if (leftday <= 30)
	   {
		   if (leftday > 0)
		   {
				alert ("您的证书将于"+ eyear + "-" + emonth + "-" + eday + "过期，\r\n请务必在证书到期前到CA服务专区在线更新");
		   } 
		   else
		   {
				alert ("您的证书已于"+ eyear + "-" + emonth + "-" + eday + "过期，\r\n请联系CA中心进行证书更新");
				window.close ();
		   }
	   }
}

//verify each other,Parameter form present formID, Parameter objectID presnet Active Control Object ID Parameter mode = 0 presnet not to encrypt and sign , mode=1 presnet only sign mode=2 present sign and encry
function verify(mode)                  
{
	if ((mode!=FLG_NULL)&&(mode!=FLG_SIGN)&&(mode!=FLG_ENCRYPT_SIGN))
	{
		alert(ERR_MODE);
		return;
	}else{
	}
	
	if (mode != FLG_NULL) 
	{
		objCert = new CCert("","","","","");
		var checkResult = checkActiveX(objCert);
	

		if (checkResult != RTN_OKAY)  {
			alert(checkResult);
			window.close();
		}
		else{
			   document.submitForm.clientCert.value = objCert.clientCert;
      		   document.submitForm.randnum.value = objCert.randnum;
			   document.submitForm.randnumSign.value = objCert.randnumSign;
			   document.submitForm.clientCertID.value = objCert.clientCertID;
			   document.submitForm.eKeyID.value = objCert.eKeyID;	       		  
                //------------------- 增加下面的代码-------------------
				mytest.GetCertInfo(objCert.clientCert);
				if( mytest.Status<0 ) {
				  alert("解析证书失败");
				  window.close();
				}
				var expiretime = "20" + mytest.SendTime.substring(0,6);
				checkexpiretime(expiretime);
		//-------------------

			   document.submitForm.submit();	  			 
		}
	}
	else  document.submitForm.submit();       //if mode=0 then skip all next processing
	//alert (document.submitForm.eKeyID.value);
}


function doSend(form,cert,mode) 
{
  var PIN="";								  //PIN码
  var PlainMsg="";							  //明文串
  var Signature="";							  //签名串            
  var SecureMsg="";                           //用于存放提交给Server端的加密过的所有  
  var MsgPart = ""                            //明文+签名
  var strFileName="";                         //文件名称
  var strFileValue="";                        //文件String串

  var receiver ="" ;                          //接收人
  var clientCert = "" ;                        //客户端证书
  var clientCertUserID ="";                     //客户端证书ID
  var clientCertSerialNumber= "";		//客户端证书序号
  var arraySize = 0;                    

  var elementNameArray  = new Array();        //明文元素名称
  var elementValueArray = new Array();        //明文元素值
  
  if (mode!=FLG_NULL)
  {
	if(!mytest.IsLogin()){
		mytest.InitActV();
		if(mytest.Status<0)  return ERR_INITIALIZE;             //ActiveX control object Initializtion failure

	mytest.login(mytest.getPin());
		if (mytest.Status<0)	return  ERR_LOGIN_DISA; //Fail to login use current PIN
	 	document.cookie ="PIN="+PIN+";PATH=/" ;  //set pin in cookie which will be used in the whole session
	}
 	//DISA_LOGIN = 1; 	
  }

  for (var i=0;i<form.length;i++ )
  {
	  if (form.elements[i].name==null) return ERR_EMPTY_ELEMENT;
	  if (form.elements[i].name.substring(0,3)=="PLN"){
		  elementNameArray[arraySize] =form.elements[i].name;
		  elementValueArray[arraySize]=form.elements[i].value;
		  arraySize++;
	  }
	  //if the prefix of form elements is PLN it means that it will be visible in the whole transportation
	  switch (form.elements[i].type)
	  {
	      case "select":
		  case "select-one":
		  case "select-two":
		  case "select-multiple":
			  for (j=0;j<form.elements[i].options.length ;j++ )
					if (form.elements[i].options[j].selected)
						PlainMsg+= "<"+form.elements[i].name+">"+form.elements[i].options[j].value+"</"+form.elements[i].name+">";
			  break;
		  case "checkbox":
		  case "radio":
			  if (form.elements[i].checked )
				PlainMsg+= "<"+form.elements[i].name+">"+form.elements[i].value+"</"+form.elements[i].name+">";
			  break;
		  case  "text":
		  case  "textarea":
		  case  "password":
			  PlainMsg+= "<"+form.elements[i].name+">"+form.elements[i].value+"</"+form.elements[i].name+">";
		      break;
		  case  "hidden":
			if (form.elements[i].name=="receiver")
				receiver = form.elements[i].value
		    else
				PlainMsg+= "<"+form.elements[i].name+">"+form.elements[i].value+"</"+form.elements[i].name+">";
			break;
		  case  "file":
			strFileName = form.elements[i].value;
			if (strFileName != "")
			{
				strFileName=strFileName.substring(strFileName.lastIndexOf("\\")+1,strFileName.length);
				strFileValue = mytest.ReadLocalFile(form.elements[i].value,36823636);

				if (strFileValue == "") return ERR_READ_FILE;
				PlainMsg+= "<"+form.elements[i].name+"  type=file name='"+strFileName+"'>"+strFileValue+"</"+form.elements[i].name+">";
			}
		    break;
		  case  "submit","button","reset":break;
	  }
  }


 if (mode!=FLG_NULL)
 { 		
	 Signature = mytest.SignData(PIN,PlainMsg);    //签名表单数据
	 if(mytest.Status < 0) return ERR_SIGN;
 }

 if (mode==FLG_SIGN) 
 {	     			
	  PlainMsg = mytest.Encode(PlainMsg);		      //如果只签名，则对原文进行Base6编码
	  if(mytest.Status < 0) return ERR_ENCODE;
 }	



  var strMsgPart = "<MsgPart><PlainMsg>"+PlainMsg+"</PlainMsg><Signature>"+Signature+"</Signature></MsgPart>";//组包
	
  if (mode==FLG_ENCRYPT_SIGN)    
  {
		SecureMsg = mytest.Encrypt(cert,strMsgPart);
		if(mytest.Status<0) return ERR_ENCRYPT;
  }
  else
	    SecureMsg=strMsgPart;          // do not need encryption  
  form.reset();

 if (mode!=FLG_NULL)
 {
 	  
	 clientCert=mytest.GetCertString();
     	 if(mytest.Status<0) return  ERR_READ_CLIENT_CERT; //Fail to get client cert
	
	 clientCertUserID=mytest.GetCertUserID();	 
	 if(mytest.Status<0) return  ERR_READ_CLIENT_CERTID; //Fail to get client cert

	 clientCertSerialNumber=mytest.GetCertSerialNumber();
	 if(mytest.Status<0) return ERR_READ_CLIENT_CERTSERIALNUMBER; //Fail to get client cert
 }

  var formString = "<form name=\"secureForm\" action=\""+ form.action+"\" method=\""+form.method+"\">"
	+ "<input type=\"hidden\" name=\"secureMsg\" value=\""+SecureMsg+"\">"
	+ "<input type=\"hidden\" name=\"clientCert\" value=\""+clientCert+"\">"
	+ "<input type=\"hidden\" name=\"clientCertUserID\" value=\""+clientCertUserID+"\">"
	+ "<input type=\"hidden\" name=\"eKeyID\" value=\""+clientCertSerialNumber+"\">";

  if (receiver!="")
  {
	  var strDesc = "<receiver>"+receiver+"</receiver>";
      formString += "<input type=\"hidden\" name=\"Description\" value=\""+strDesc+"\">";
  }

  if (arraySize>0)
  {  
	  for (j=0;j<arraySize ;j++ )
	  {
		 formString += "<input name=\""+elementNameArray[j]+"\" type=\"hidden\" value=\""+elementValueArray[j]+"\">";
	  }
  }
  document.open("text/html");

  document.write(formString);
  document.write("</form>");
  document.close();

  return RTN_OKAY;
}

function send(form,cert,mode) 
{
	var  result;
    if ((form =="")||(form==null))
    {
		alert(ERR_EMPTY_FORM);
		return;
	}

    if ((cert =="")||(cert==null))
    {
		cert = getCookie("serverCert");           //如果没有得到证书，默认为服务器证书
		if (cert == null) {
			alert(ERR_READ_CERT);
			return;
		}
    }

	if ((mode!=FLG_NULL)&&(mode!=FLG_SIGN)&&(mode!=FLG_ENCRYPT_SIGN))
	{
		alert(ERR_MODE);
		return;
	}

	result = doSend(form,cert,mode);
	

	if (result == RTN_OKAY)  
	{
		
		document.secureForm.submit();
	
	}
	else {
	
 		alert(result);
		window.close();
	}
}

function doReceive(secureMsg,cert,mode) 
{

	
  var PIN="";								  //PIN码
  var MsgPart,PlainMsg;

  if (mode==FLG_NULL)                         //即不签名也不加密
  {
      PlainMsg = new SForm(secureMsg);
      return PlainMsg;
  }

  mytest.InitActV();
  if  (mytest.Status!=0)
  {
	  alert (ERR_INITIALIZE);
	  return null ;
  }
  
  if(!mytest.IsLogin()){
		mytest.InitActV();
		if(mytest.Status<0)  return null;             //ActiveX control object Initializtion failure
mytest.login(mytest.getPin())
		if (mytest.Status<0)	return  null; //Fail to login use current PIN
	 	//document.cookie ="PIN="+PIN+";PATH=/" ;  //set pin in cookie which will be used in the whole session
  }


  mytest.VerifyCertString(cert);
  if(mytest.Status<0)
  {
       alert(ERR_AUTH_CERT);						//the third Certification authorization  failed
       return null;
  }

  if (mode==FLG_ENCRYPT_SIGN)
  {    
	    var secureLength = secureMsg.length;
		MsgPart = mytest.Decrypt(PIN,secureMsg);        //decrypt secure message

		//alert(	"MsgPart="+MsgPart);
		if(mytest.Status < 0) 
		{
			alert(ERR_DECRYPT);
			return null;
		}
  }
  else MsgPart = secureMsg;


  
  objMsgPart = new SForm(MsgPart);					//Create Object Message Part
   
  PlainMsg=objMsgPart.getValue("PlainMsg");  
  Signature=objMsgPart.getValue("Signature"); 

  if (mode == FLG_SIGN) 
  {	
	  PlainMsg = mytest.Decode(PlainMsg);	  
	  if (mytest.Status <0 )	
	  {	
		  alert(ERR_DECODE);
		  return null;
	  }  
   }   
	//alert(	"PlainMsg="+PlainMsg);	 
  mytest.VerifySign(cert, PlainMsg,Signature);  //Authorization the signature
  if(mytest.Status < 0)
  {
     alert(ERR_AUTH_SIGN);
     return null;
  } 

   PlainMsg = new SForm(PlainMsg);
   return PlainMsg;
}



//send mail 群发安全邮件  cert为用来加密的一组证书串，count 为证书的数量


function sendMail(form,eMail,mode,cert,count) 

{   
   //alert("cert="+cert.length);
	//alert("eMail="+eMail);
	//alert("count="+count);
	//alert("mode="+mode);

	
	var  result;
    if ((form =="")||(form==null))
    {
		alert(ERR_EMPTY_FORM);
		return false;
	}

    if(!chkmail())
    {    	
    	return false;
     }
	if ((mode!=FLG_NULL)&&(mode!=FLG_SIGN)&&(mode!=FLG_ENCRYPT_SIGN))
	{
		alert(ERR_MODE);
		return false;
	}

	if(form.body == "" || form.body == null)
    {
        alert("邮件正文不能为空");
        return false;
    }
    
   if(cert == "" || cert == null)
    {
        alert("证书不能为空");
        return false;
    }

	  if(count == "" || count == null)
    {
        alert("证书的数量不能为空");
        return false;
    }

    sending.style.visibility="visible";
    cover.style.visibility="visible";

	result = doSendMail(form,eMail,mode,cert,count);

	if (DISA_LOGIN == 1)
	{
//		mytest.disaLogout();							 //Log out current Disa
//		if (mytest.Status<0)	return  ERR_LOGOUT_DISA; //Fail to login use current PIN
		DISA_LOGIN = 0 ; 
	}

	if (result == RTN_OKAY){
		document.frm_mail.submit();
		return true;
	}
	else {
		alert(result);
		sending.style.visibility="hidden";
		cover.style.visibility="hidden";

		return false;
	}
}


function doSendMail(form,eMail,mode,cert,count) 
{
 // var cert=""                                 //接收方证书
  var PIN="";								  //PIN码
  var PlainMsg="";							  //明文串
  var Signature="";							  //签名串            
  var SecureMsg="";                           //用于存放提交给Server端的加密过的所有  
  var MsgPart = "";                            //明文+签名
  var strFileName="";                         //文件名称
  var strFileValue="";                        //文件String串

  var receiver ="" ;                          //接收人
  var clientCert = ""                         //客户端证书
  var arraySize = 0;                    

  var elementNameArray  = new Array();        //明文元素名称
  var elementValueArray = new Array();        //明文元素值
  
 if (mode!=FLG_NULL)
  {
	if(!mytest.IsLogin()){
		mytest.InitActV();
		if(mytest.Status<0)  return ERR_INITIALIZE;             //ActiveX control object Initializtion failure

		PIN=getCookie("PIN");
		if (PIN==null)                              //the first login to get pin
			PIN=mytest.getPin();                    //get PIN

		mytest.login(PIN);                    //Login Disa use current PIN
		if (mytest.Status<0)	return  ERR_LOGIN_DISA; //Fail to login use current PIN
	 	document.cookie ="PIN="+PIN+";PATH=/" ;  //set pin in cookie which will be used in the whole session
	}
 	DISA_LOGIN = 1;
  }

 // cert=mytest.GetCertByMail(eMail);
 // if (mytest.Status<0)	return  ERR_GET_CERT; //Fail to login use current PIN

  for (var i=0;i<form.length;i++ )
  {
	  if (form.elements[i].name==null) return ERR_EMPTY_ELEMENT;
	  switch (form.elements[i].type)
	  {
	      case "select":
		  case "select-one":
		  case "select-two":
			  for (j=0;j<form.elements[i].options.length ;j++ )
					if (form.elements[i].options[j].selected)
						PlainMsg+= "<"+form.elements[i].name+">"+form.elements[i].options[j].value+"</"+form.elements[i].name+">";
			  break;
          case "select-multiple":
           	  for (j=0;j<form.elements[i].options.length ;j++ )
              {
					FileName = form.elements[i].options[j].value;
	                if (FileName != "")
		           {
				          FileValue = mytest.ReadLocalFile(FileName,MAX_FILE_SIZE);
				          if ((FileValue == "")||(FileValue==null)) return ERR_READ_FILE;
						  var num = j+1;
						  var FileElementName = form.elements[i].name + num;
						  FileName=FileName.substring(FileName.lastIndexOf("\\")+1,FileName.length);
				          FilePlainMsg="<"+FileElementName+"  type=file name='"+FileName+"'>"+FileValue+"</"+FileElementName+">";

				        if (mode!=FLG_NULL)
				        {
					         FileSignature = mytest.SignData(PIN,FilePlainMsg);    //签名表单数据
					         if(mytest.Status < 0) return ERR_SIGN;
				        }
				         if (mode==FLG_SIGN)                                      //如果仅作签名则对原文进行编码
				         {	    	
					         FilePlainMsg = mytest.Encode(FilePlainMsg);		
					         if(mytest.Status < 0) return ERR_ENCODE;
				         }	

		               var FileMsgPart = "<MsgPart><PlainMsg>"+FilePlainMsg+"</PlainMsg><Signature>"+FileSignature+"</Signature></MsgPart>";//文件组包

				        if (mode==FLG_ENCRYPT_SIGN)    
				        {
						    // FileSecureMsg = mytest.Encrypt(cert,FileMsgPart);
                            FileSecureMsg = mytest.EncryptEx(cert,count,FileMsgPart); //对数据进行多证书集体加密

						     if(mytest.Status<0) return ERR_ENCRYPT;
				         }

					    else 
						       FileSecureMsg = FileMsgPart;
				        if (document.frm_mail.attachment.value!="")
					          document.frm_mail.attachment.value=document.frm_mail.attachment.value+","+FileSecureMsg;
				        else
					         document.frm_mail.attachment.value=FileSecureMsg;
				     }
	              } 
	              break;
		  case "checkbox":
		  case "radio":
			  if (form.elements[i].checked )
				PlainMsg+= "<"+form.elements[i].name+">"+form.elements[i].value+"</"+form.elements[i].name+">";
			  break;
		  case  "text":
		  case  "textarea":
		  case  "password":
			  PlainMsg+= "<"+form.elements[i].name+">"+form.elements[i].value+"</"+form.elements[i].name+">";
		      break;
		  case  "hidden":
			if (form.elements[i].name=="receiver")
				receiver = form.elements[i].value
		    else
				PlainMsg+= "<"+form.elements[i].name+">"+form.elements[i].value+"</"+form.elements[i].name+">";
			break;	
		case  "file","submit","button","reset":
			break;
	  }
  }

 if (mode!=FLG_NULL)
 {
	 Signature = mytest.SignData(PIN,PlainMsg);    //签名表单数据
	 if(mytest.Status < 0) return ERR_SIGN;
 }

 if (mode==FLG_SIGN) 
 {	    	
	  PlainMsg = mytest.Encode(PlainMsg);		      //如果只签名，则对原文进行Base6编码
	  if(mytest.Status < 0) return ERR_ENCODE;
 }	


  var strMsgPart = "<MsgPart><PlainMsg>"+PlainMsg+"</PlainMsg><Signature>"+Signature+"</Signature></MsgPart>";//组包

  if (mode==FLG_ENCRYPT_SIGN)    
  { 

	    //alert("begin to EncryptEx mail");
	    //alert("cert="+cert.length);
	   //alert(cert.indexOf("|"));
       ///alert(cert);
       //alert("count="+count);
		//SecureMsg = mytest.Encrypt(cert,strMsgPart);
		SecureMsg = mytest.EncryptEx(cert,count,strMsgPart); //对数据进行多证书集体加密
		if(mytest.Status<0) return ERR_ENCRYPT;
  }
  else
	    SecureMsg=strMsgPart;          // do not need encryption
  
  form.reset();

  document.frm_mail.body.value=SecureMsg;
  return RTN_OKAY;
}

//end 



function receive(secureMsg,cert,mode) 
{
	var  result;

    if ((secureMsg =="")||(secureMsg==null))
    {
		alert(ERR_EMPTY_SECUREMSG);
		return null;
	}

    if ((cert =="")||(cert==null))
    {
		cert = getCookie("serverCert");           //如果没有得到证书，默认为服务器证书
		if (cert == null) {
			alert(ERR_READ_CERT);
			return null;
		}
    }

	if ((mode!=FLG_NULL)&&(mode!=FLG_SIGN)&&(mode!=FLG_ENCRYPT_SIGN))
	{
		alert(ERR_MODE);
		return null;
	}

	result = doReceive(secureMsg,cert,mode);

	
	
	return result;
}

function exitPKI(){
	if(mytest.IsLogin())
	{
		//alert("exit ekey");
		mytest.disaLogout();
		//DISA_LOGIN=0;
	}
}
