//ukey变量
var UseCom = "";
var user_sign_cert = "";
var user_enc_cert = "";
var KeyType = "";
//ukey接口

/******************************************************************************************
* 函数名称：GDCA_Finalize
* 创建作者：羊城    
* 创建日期：2008.4.17    
* 函数功能：结束GDCA控件，释放GDCA_Initialize中分配的全局资源（内存、信号量等）    
* 输入参数：i_Com      COM控件名称
* 输出参数：errorCode  COM控件返回的错误代码   
* 修改记录：

******************************************************************************************/
function GDCA_Finalize(i_Com) {
    try {
        var errorCode;               //COM控件返回的错误代码

        i_Com.GDCA_Finalize();       //释放资源
        errorCode = i_Com.GetError(); //检查函数是否成功运行，在函数运行结束后调用
        if (errorCode != 0)
            ;
    }
    catch (objError) {
        ;
    }
    return errorCode;
}

/******************************************************************************************
* 函数名称：GDCA_Logout
* 创建作者：羊城    
* 创建日期：2008.4.17    
* 函数功能：退出登录，并结束GDCA控件   
* 输入参数：i_Com    COM控件名称
* 输出参数：ret      COM控件返回代码   
* 修改记录：

******************************************************************************************/
function GDCA_Logout(i_Com) {
    var ret, errorCode;

    try {
        if (i_Com.GDCA_isLogin(2) == 0)     //判断有无登录
        {
            ret = i_Com.GDCA_Logout();      //退出登录

            errorCode = i_Com.GetError();   //检查上一函数是否成功运行
            if (errorCode != 0)              //退出登录失败

                ;
        }
    }
    catch (objError) {
        ;
    }
    finally {
        GDCAFinalize(i_Com);            //释放资源
    }
    return ret;
}

function verys() {
    var GDCACom;                       //GDCACOM控件
    var DeviceType;                     //密码设备类型
    var errorCode = -1;                 //COM控件返回的错误代码

    var ReadOutSignCert;                //读出的用户签名证书

    var ReadOutEncCert;                 //读出的用户加密证书

    var ReadOutKeyIdEnCode;             //读出的唯一标识符（未解码）
    var ReadOutKeyId;                   //读出的唯一标识符

    var user_pin = $("#userpw").val(); //密码设备PIN码



    /*****************************************************************************************
    第一步：动态加载GDCA的COM控件
    *****************************************************************************************/
    try {
        //安装客户端中间件和设备驱动后可以在注册表里查询Atl_com.Gdca已经注册，

        //Atl_com.Gdca为GDCAUSBkey的COM接口
        GDCACom = new ActiveXObject("Atl_com.Gdca");
        //alert("3.0控件创建成功！");
    }
    catch (objError) {
        ;
        //ReadCert();
        return false;
    }

    /*****************************************************************************************
    第二步：初始化GDCA的COM控件
    其分步骤如下：

    1、判断密码设备和注册表信息是否安装正常

    2、设置密码设备类型

    3、初始化COM控件
    *****************************************************************************************/

    try {
        DeviceType = GDCACom.GDCA_GetDevicType();   //获取客户端密码设备设备类型


        switch (parseInt(DeviceType)) {
            case -1: ;
                break;
            case -2: ;
                break;
            case -3: ;
                break;
            default:
                //设置密码设备类型，具体设置详见gdca_device.ini的配置信息，gdca_device.ini在安装包中有
                GDCACom.GDCA_SetDeviceType(DeviceType);
                errorCode = GDCACom.GetError(); //检查函数是否成功运行，在函数运行结束后调用
                if (errorCode != 0) {
                    ;
                    return errorCode;
                }

                //初始化接口所需要的全局资源（内存、信号量等），如果初始化成功，返回值为0
                GDCACom.GDCA_Initialize();
                errorCode = GDCACom.GetError(); //检查函数是否成功运行，在函数运行结束后调用
                if (errorCode != 0) {
                    ;
                    return errorCode;
                }
                break;
        }
    }
    catch (objError) {
        ;
        GDCA_Finalize(GDCACom);         /*释放密码设备接口资源*/
        return false;
    }
    //  	alert("测试控件初始化，读取密码设备标签内容：" + GDCACom.GDCA_ReadLabel("CA_CERT",9));

    /*****************************************************************************************
    第三步：用户登录
    *****************************************************************************************/

    try {
        if (user_pin == null || user_pin == '') {
            ;
            $("#userpw").focus();
            return false;
        }

        GDCACom.GDCA_Login(2, user_pin); //客户端密码设备登录

        errorCode = GDCACom.GetError(); //检查函数是否成功运行，在函数运行结束后调用
        if (errorCode != 0) {
            ;
            GDCA_Logout(GDCACom);     //释放GDCA_Initialize中分配的全局资源
            return false;
        }
    }
    catch (objError) {
        ;
        GDCA_Logout(GDCACom);         /*释放密码设备接口资源*/
        return false;
    }

    /*****************************************************************************************
    第四步：读取用户密码设备（USBKey）的用户证书
    用户证书包括：

    1、签名证书

    2、加密证书

    *****************************************************************************************/

    try {
        //读取用户签名证书，保存在ReadOutSignCert中

        ReadOutSignCert = GDCACom.GDCA_ReadLabel("LAB_USERCERT_SIG", 7);
        errorCode = GDCACom.GetError(); //检查函数是否成功运行，在函数运行结束后调用
        //证书读取失败
        if (errorCode != 0) {
            ;
            //退出登录

            GDCA_Logout(GDCACom);
            return false;
        }
    }
    catch (objError) {
        ;
        GDCA_Logout(GDCACom);          /*释放密码设备接口资源*/
        return false;
    }
    //alert("ReadOutSignCert==== " + ReadOutSignCert);

    try {
        //读取用户加密证书，保存在ReadOutEncCert中

        ReadOutEncCert = GDCACom.GDCA_ReadLabel("LAB_USERCERT_ENC", 8);
        errorCode = GDCACom.GetError();  //检查函数是否成功运行，在函数运行结束后调用
        //证书读取失败
        if (errorCode != 0) {
            ;
            //退出登录

            GDCA_Logout(GDCACom);
            return false;
        }
    }
    catch (objError) {
        ;
        GDCA_Logout(GDCACom);         /*释放密码设备接口资源*/
        return false;
    }
    //alert("ReadOutEncCert==== " + ReadOutEncCert);

    /*****************************************************************************************
    第五步：判断签名证书的证书时间的有效性（判断证书是否过期）

    注：此处直接调用GDCASecure.js文件里的GDCAGetCerTime函数，因为GDCAGetCerTime实现太长
    *****************************************************************************************/

    try {
        errorCode = GDCAGetCerTime(GDCACom, 2, ReadOutSignCert);
        if (errorCode != 0) {
            ;
            return errorCode;
        }
    }
    catch (objError) {
        ;
        GDCA_Logout(GDCACom);         /*释放密码设备接口资源*/
        return false;
    }

    /*****************************************************************************************
    将JS的参数保存在form里传递给服务器端
    *****************************************************************************************/
    user_sign_cert = ReadOutSignCert; //用户签名证书
    user_enc_cert = ReadOutEncCert;   //用户加密证书
    KeyType = 2;                      //KEY类型 

    //	alert("ReadOutSignCert==="+form1.user_sign_cert.value);

    /*
    alert("用户签名证书: " + form1.user_sign_cert.value);
    alert("用户加密证书：" + form1.user_enc_cert.value);
    alert("密码设备类型：" + DeviceType);
    alert("KEY类型: " + form1.KeyType.value);
    */
}

$(document).ready(function() {





    if (CheckLogin() == '1') {

        Get_MY_Name(function(msg)
        //取登陆用户名
        {
            if (msg.length > 12) {
                // $("#uname").html(msg.substring(0, 12) + "...");
                $("#uname").html("进入我的管理中心");
                $("#uname").attr('title', msg);
                $("#loginout").html(' |    退出登录');
                $("#loginbt").html('');
                $("#regbt").html('');

            }
            else {
                // $("#uname").html(msg.substring(0, 12));
                $("#uname").html("进入我的管理中心");
                $("#uname").attr('title', msg);
                $("#loginout").html(' |    退出登录');
                $("#loginbt").html('');
                $("#regbt").html('');
            }

        });
    }
    else {
        $("#uname").html('');
        $("#loginout").html('');
        $("#loginbt").html('登录');
        $("#regbt").html('注册');
    }
    $("#nav3").html("<div id='nav3'><ul>"
+ "<li ><a href='javascript:void(0)' onclick='My_cgs_Manage();' ><img src='/web/newgb/images/zkh01.jpg' width='164' height='111' /></a>"
+ "<div class='tt'><a href='javascript:void(0)' onclick='My_cgs_Manage();' >我要找采购商</a></div></li>"
+ "<li><a href='javascript:void(0)' onclick='My_hwsj_Manage();' ><img src='/web/newgb/images/zkh02.jpg' width='164' height='111' /></a>"
+ "<div class='tt'><a  href='javascript:void(0)' onclick='My_hwsj_Manage();'>我要找海外商机</a></div></li>"
+ "<li><a href='javascript:void(0)' onclick='My_cgxx_Manage();' ><img src='/web/newgb/images/zkh03.jpg' width='164' height='111' /></a>"
+ "<div class='tt'><a href='javascript:void(0)' onclick='My_cgxx_Manage();' >我要找采购信息</a></div></li>"
+ "<li><a href='javascript:void(0)' onclick='My_zdpp_Manage();' ><img src='/web/newgb/images/zkh04.jpg' width='164' height='111' /></a>"
+ "<div class='tt'><a href='javascript:void(0)' onclick='My_zdpp_Manage();'>自动匹配采购信息</a></div></li></ul>"
+ "</div>");
});
function Login_CallBack(callback) {
    $("#login_div").html($.ajax({ url: "/web/newgb/login.aspx", async: false }).responseText);
   
    $("#login_div").zxxbox({
        bar: false, onshow: function() {
            document.onkeydown = function(e) {
                var ev = document.all ? window.event : e;
                if (ev.keyCode == 13) {


                    $("#loginBtn").click();

                }
            }



        },
        onclose: function() { $("#login_div").html('') }
    });     //或者是$.zxxbox($("#login"));
    $("#loginBtn").click(function() {

        var login_type = 1; //登录类型,1.普通登录,2.证书登录
        if ($('input[name=rdo_login_type]:checked').val() == "1")
        //普通登录
        {
            if ($("#userName").attr("value") == '') {
                alert('请输入用户名');
                return;
            }
            if ($("#userpw").attr("value") == '') {
                alert('请输入用户密码');
                return;
            }
            login_type = 1;
            openloading('登录');
            UserLogin($("#userName").attr("value"), $("#userpw").attr("value"), login_type, function(msg) {
                var res_commom = msg.split('|');
                if (res_commom[0] == '100') {
                    alert('登录成功');
                    try
                    {
                    $.cookie('name', $("#userName").attr("value"), { expires: 1 });
                    }
                    catch(e)
                    {
                    }
                    Get_MY_Name(function(msg)
                    //取登陆用户名
                    {
                        if (msg.length > 12) {
                            $("#uname").html("进入我的管理中心");
                            $("#uname").attr('title', msg);
                            $("#loginout").html(' |    退出登录');
                            $("#loginbt").html('');
                            $("#regbt").html('');

                        }
                        else {
                            $("#uname").html("进入我的管理中心");
                            $("#uname").attr('title', msg);
                            $("#loginout").html(' |    退出登录');
                            $("#loginbt").html('');
                            $("#regbt").html('');
                        }

                    });

                    $.zxxbox.hide();
                    callback();
                    //showTip('登录成功',null,10)
                    closeloading();
                }
                else {
                    alert(res_commom[1]);
                    closeloading();

                }
            },
        function() {
            alert('登录超时.');
            closeloading();
        }
        );
        }


        else if ($('input[name=rdo_login_type]:checked').val() == "2")
        //ukey登录
        {
            login_type = 2;
            if ($("#userpw").attr("value") == '') {
                alert('请输入证书密码');
                return;
            }

            KeyType = GDCACom.GDCA_GetDevicType();
            if (KeyType < 0) {
                alert("请在USB口插入证书介质！并确认是否正确安装中间件" + KeyType);
                return false;
            }
            if (verys() == false) {

                alert('密码错误,如果读取证书失败!插入证书介质请等待20秒后再操作');
                return;
            }
            var client_keyid = GDCACom.GDCA_ReadLabel("LAB_DISAID", 3);
            var keyid = GDCACom.GDCA_Base64Decode(client_keyid);

            openloading('登录');
            UserLogin_ukey($("#userpw").attr("value"), login_type, keyid, KeyType, function(msg) {
                var res_commom = msg.split('|')
                if (res_commom[0] == '200') {
                    alert('登录成功');
                    Get_MY_Name(function(msg)
                    //取登陆用户名
                    {
                        if (msg.length > 12) {
                            $("#uname").html("进入我的管理中心");
                            $("#uname").attr('title', msg);
                            $("#loginout").html(' |    退出登录');
                            $("#loginbt").html('');
                            $("#regbt").html('');

                        }
                        else {
                            $("#uname").html("进入我的管理中心");
                            $("#uname").attr('title', msg);
                            $("#loginout").html(' |    退出登录');
                            $("#loginbt").html('');
                            $("#regbt").html('');
                        }

                    })

                    $.zxxbox.hide();
                    callback();
                    //showTip('登录成功',null,10)
                    closeloading();
                }
                else {
                    alert(res_commom[1]);
                    closeloading();

                }
            },
        function() {
            alert('登录超时.');
            closeloading();
        }
        );
        }



    });
    $("#cancelBtn").click(function() {
        $.zxxbox.hide();
    }
					);

}


/////------母版页

function my_index()
//我的管理中心
{
    if (CheckLogin() == '1') {
        window.open('/web/gb/company/index.aspx', '_blank');
    }
    else {
        Login_CallBack(function() { window.open('/web/gb/company/index.aspx', '_blank'); });
    }
}
function Login_out() {

    if (UserLogin_out() == '1') {
        alert('成功退出登录');
        $("#uname").html('');
        $("#loginout").html('');
        $("#loginbt").html('登录');
        $("#regbt").html('注册');
    }
}
function User_type() 
//登陆类型
{

    if ($('input[name=rdo_login_type]:checked').val() == "2") {
        $("#user_tr").hide();
        $("#psw_td").html('证书密码：');
    }
    else {
        $("#user_tr").show();
        $("#psw_td").html('密&nbsp;&nbsp;&nbsp; 码：');
    }
}
//////------------做外贸zwm.aspx
function My_Data_Manage()
//管理我的基本信息
{
	if(CheckLogin()=='1')
	{

	    GetCompany_type(function(type) {
	        switch (type) {
	            case '1': window.open('/web/gb/company/dzreportc_bg.aspx', '_blank'); break;
	            case '3': window.open('/web/gb/company/dzreportccc_bg.aspx', '_blank'); break;
	           default: window.open('/web/gb/company/index.aspx', '_blank'); break;
	        }
	     
	    });
	}
	else
	{
	    Login_CallBack(function() {

	        GetCompany_type(function(type) {
	        switch (type) {
	            case '1': window.open('/web/gb/company/dzreportc_bg.aspx', '_blank'); break;
	            case '3': window.open('/web/gb/company/dzreportccc_bg.aspx', '_blank'); break;
	            default: window.open('/web/gb/company/index.aspx', '_blank'); break;
	        }
	        });


	    });
	}
}
function My_Contract_Manage() {
//洽谈签约
    if (CheckLogin() == '1') {
        window.open('/web/gb/company/navqtqy.aspx', '_blank');
    }
    else {

        Login_CallBack(function() { window.open('/web/gb/company/navqtqy.aspx', '_blank'); });
    }
}

function My_ckjh_Manage()
//出口交货
 {
    if (CheckLogin() == '1') {
        window.open('/web/gb/company/navckjh.aspx', '_blank');
    }
    else {

        Login_CallBack(function() { window.open('/web/gb/company/navckjh.aspx', '_blank'); });
    }
}
function My_tshx_Manage()
//退税核销
{
    if (CheckLogin() == '1') {
        window.open('/web/gb/company/navtshx.aspx', '_blank');
    }
    else {

        Login_CallBack(function() { window.open('/web/gb/company/navtshx.aspx', '_blank'); });
    }
}


//--------找客户zkw.aspx

function My_cgxx_Manage()
//找采购信息

{

    window.open('/web/gb/search/searchqgcp2.aspx', '_blank');


}

function My_cgs_Manage()
    //找采购商
{

   
    if (CheckLogin() == '1') {
        window.open('/web/gb/company/findbuyer.aspx', '_blank');
    }
    else {
       window.open('/web/gb/search/findbuyer.aspx', '_blank');
    }

}
function My_hwsj_Manage()
//我要找海外商机
{

    window.open('/web/gb/common/searchcg/searchcg.aspx', '_blank');

}

//建设企业基本网站调用My_Contract_Manage()


function My_zdpp_Manage()
//自动匹配
{
        if (CheckLogin() == '1') {
        window.open('/web/gb/company/myqgcp.aspx', '_blank');
        }
        else
        {
                Login_CallBack(function() { window.open('/web/gb/company/myqgcp.aspx', '_blank'); });
        }

    }



function openloading(txt) {
    if (!window.XMLHttpRequest) {
        $("#targetFixed").css("top", $(document).scrollTop() + 2);
    }
    //创建半透明遮罩层


    if (!$("#overLay").size()) {
        $('<div id="overLay"></div>').prependTo($("body"));
        $("#overLay").css({
            width: "100%",
            backgroundColor: "#000",
            opacity: 0.2,
            position: "absolute",
            left: 0,
            top: 0,
            zIndex: 99
        }).height($(document).height());
    }
    //显示操作提示，最关键核心代码
    $("#targetFixed").powerFloat({
        eventType: null,
        targetMode: "doing",
        target: "正在" + txt + "中...",
        position: "1-2"
    });
} //打开加载效果
function closeloading() {
    $("#overLay").remove();
    $.powerFloat.hide();
} //关闭加载效果




