//init then login_form patten
var getQrCodeUrlCount = 3;
var winW;
var winH;
var validateCodeCheck;

// 跳转前全屏遮罩，避免先闪出门户登录页
(function() {
    var mask = document.createElement("div");
    mask.id = "sso-jump-mask";
    mask.style.cssText = [
        "position:fixed",
        "top:0",
        "left:0",
        "width:100vw",
        "height:100vh",
        "background:#ffffff",
        "z-index:999999",
        "display:flex",
        "justify-content:center",
        "align-items:center",
        "font-size:14px",
        "color:#666666"
    ].join(";");
    mask.innerText = "正在跳转，请稍候...";
    document.documentElement.appendChild(mask);

    // 跳转失败时兜底，避免一直白屏
    window.__ssoJumpMaskTimer = setTimeout(function() {
        var jumpMask = document.getElementById("sso-jump-mask");
        jumpMask && jumpMask.remove();
    }, 5000);
})();

/*
 * 门户 SSO 桥接（BaoYPro / 泛微 E10）
 * eassso/login?service=SHR地址
 *   -> /qy/auth/weaver/app.do?appId&redirect
 *   -> 泛微授权
 *   -> /qy/auth/callback/weaver/pa
 *   -> index2sso.jsp 写 LTPA（POST，不经 Location）
 *   -> 回到 SHR
 * 仅 /shr/home.do 保留原生账号密码登录，其余 SHR 入口走 SSO。
 * weaverAppId 需与 integration-config.json 中 oauth.apps[].appId 一致。
 * 入口走 weaver 包自有 /auth/weaver/app，不依赖 UnifiedAuth 的 platform 参数。
 */
var ENV_CONFIG = {
    test: {
        shrBaseUrl: "http://172.16.38.1:6888",
        oaSsoUrl: "http://172.16.38.1:6888/qy/auth/weaver/app.do",
        weaverAppId: "cce4cd9a-9f55-4976-93b0-4f46b5b28a01"
    },
    prod: {
        shrBaseUrl: "https://hr.szpgm.com",
        oaSsoUrl: "https://hr.szpgm.com/qy/auth/weaver/app.do",
        weaverAppId: "cce4cd9a-9f55-4976-93b0-4f46b5b28a01"
    },
    keepLoginPath: "/shr/home.do",
    shrRootPath: "/shr/"
};

function removeJumpMask() {
    if (window.__ssoJumpMaskTimer) {
        clearTimeout(window.__ssoJumpMaskTimer);
        window.__ssoJumpMaskTimer = null;
    }
    var jumpMask = document.getElementById("sso-jump-mask");
    jumpMask && jumpMask.remove();
}

function getCurrentEnv() {
    var currentHost = window.location.host.toLowerCase();
    console.log("[SHR-OA-SSO] 当前Host：", currentHost);

    if (currentHost.indexOf("172.16.38.1") !== -1 || currentHost.indexOf(":6888") !== -1) {
        return ENV_CONFIG.test;
    }
    // 正式：https://hr.szpgm.com/shr
    if (currentHost.indexOf("hr.szpgm.com") !== -1) {
        return ENV_CONFIG.prod;
    }
    return ENV_CONFIG.prod;
}

// login_withForm.jsp 对 service 只做一次 URLEncoder.encode
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null && r[2]) {
        var paramValue = decodeURIComponent(r[2]).trim();
        console.log("[SHR-OA-SSO] 解析参数" + name + "：", paramValue);
        return paramValue;
    }
    console.log("[SHR-OA-SSO] 未找到参数" + name);
    return null;
}

function normalizeShrPathname(pathname) {
    if (!pathname) {
        return "";
    }
    pathname = pathname.trim();
    if (pathname === "/shr" || pathname === "/shr/") {
        return ENV_CONFIG.shrRootPath;
    }
    return pathname;
}

function isShrServicePath(pathname) {
    pathname = normalizeShrPathname(pathname);
    if (!pathname) {
        return true;
    }
    return pathname.indexOf(ENV_CONFIG.shrRootPath) === 0;
}

function toAbsoluteServiceUrl(serviceUrl) {
    if (!serviceUrl) {
        return "";
    }
    var url = serviceUrl.trim();
    if (url.indexOf("http://") === 0 || url.indexOf("https://") === 0) {
        return url;
    }
    if (url.indexOf("/") === 0) {
        return window.location.protocol + "//" + window.location.host + url;
    }
    return window.location.protocol + "//" + url;
}

function getOriginalPathFromService(serviceUrl) {
    if (!serviceUrl) {
        console.log("[SHR-OA-SSO] service 为空，按 SHR 根路径处理");
        return "";
    }

    try {
        var fullServiceUrl = toAbsoluteServiceUrl(serviceUrl);
        var pathname = normalizeShrPathname(new URL(fullServiceUrl).pathname);
        console.log("[SHR-OA-SSO] 解析 service 路径：", pathname);
        return pathname;
    } catch (e) {
        console.warn("[SHR-OA-SSO] URL 解析失败，改用字符串截取：", e);
        var pathStart = serviceUrl.indexOf(ENV_CONFIG.shrRootPath);
        if (pathStart === -1 && serviceUrl.indexOf("/shr") !== -1) {
            pathStart = serviceUrl.indexOf("/shr");
        }
        if (pathStart === -1) {
            console.log("[SHR-OA-SSO] service 不含 /shr");
            return serviceUrl;
        }
        var pathEnd = serviceUrl.indexOf("?", pathStart);
        if (pathEnd === -1) {
            pathEnd = serviceUrl.indexOf("#", pathStart);
        }
        if (pathEnd === -1) {
            pathEnd = serviceUrl.length;
        }
        return normalizeShrPathname(serviceUrl.substring(pathStart, pathEnd).trim());
    }
}

function resolveShrTargetUrl(serviceUrl, shrBaseUrl) {
    if (!serviceUrl) {
        return shrBaseUrl + ENV_CONFIG.shrRootPath;
    }
    var target = serviceUrl.trim();
    if (target.indexOf("http://") !== 0 && target.indexOf("https://") !== 0) {
        if (target.indexOf("/") !== 0) {
            target = "/" + target;
        }
        target = shrBaseUrl + target;
    }
    return target;
}

function buildWeaverSsoUrl(envConfig, targetUrl) {
    return envConfig.oaSsoUrl
        + "?appId=" + encodeURIComponent(envConfig.weaverAppId)
        + "&redirect=" + encodeURIComponent(targetUrl);
}

(function() {
    window.onbeforeunload = null;

    var currentEnv = getCurrentEnv();
    console.log("[SHR-OA-SSO] 当前环境：", currentEnv);

    var serviceParam = getUrlParam("service");
    var originalPath = getOriginalPathFromService(serviceParam);
    var onEasssoLogin = window.location.pathname.indexOf("/eassso/login") !== -1;

    var isKeepLogin = originalPath === ENV_CONFIG.keepLoginPath
        || originalPath === ENV_CONFIG.keepLoginPath + "/"
        || (serviceParam && serviceParam.indexOf(ENV_CONFIG.keepLoginPath) !== -1);

    // 只处理 SHR 相关 service；非 SHR 的 eassso/login 仍走原生登录
    var needRedirect = !isKeepLogin && isShrServicePath(originalPath) && (
        onEasssoLogin || originalPath.indexOf(ENV_CONFIG.shrRootPath) === 0
    );

    if (isKeepLogin) {
        console.log("[SHR-OA-SSO] /shr/home.do 保留原生登录");
        removeJumpMask();
    } else if (needRedirect) {
        var targetUrl = resolveShrTargetUrl(serviceParam, currentEnv.shrBaseUrl);
        var oaRedirectUrl = buildWeaverSsoUrl(currentEnv, targetUrl);
        console.log("[SHR-OA-SSO] 跳转泛微 SSO，目标 SHR：", targetUrl);
        console.log("[SHR-OA-SSO] OAuth 入口：", oaRedirectUrl);
        window.top.location.replace(oaRedirectUrl);
    } else {
        console.log("[SHR-OA-SSO] 非 SHR 场景，保留原生登录逻辑");
        removeJumpMask();
    }
})();



function initLoginFormPattern(authPattern) {
    initEvent();
    initLoginFormValue();
    if("BaseDB" == authPattern || "KingdeeCloud" == authPattern) {
        loginSwitch(authPattern);
    } else if("QrCodeToken" == authPattern) {
        loginSwitch("QrCodeToken");
        getQrCodeUrl();
    }else{
    	if(authPattern){
    		loginSwitch(authPattern);
    	}else{
    		 loginSwitch("BaseDB");
    	}
    }

    $(".login-switch").unbind().bind("click", function() {
        clearErrMsg();
        if($(this).hasClass("user-name")) {
        	var _authPattern = $.trim(document.getElementById("userAuthPatternTMP").value);
            loginSwitch(_authPattern);
            $("#userAuthPattern").val(_authPattern);
            $(".login-switch-text1").hide();
            $(".login-switch-text0").show();
        } else {
            loginSwitch("QrCodeToken");
            authPattern = "QrCodeToken";
            $("#userAuthPattern").val(authPattern);
            $(".login-switch-text0").hide();
            $(".login-switch-text1").show();
            getQrCodeUrl();
        }
        $(".login-switch-text-right1").show();
        $(".login-switch-text-right0").show();
    });
}

function loginSwitch(_target) {
    loginForm.userAuthPattern.value = _target;
    setDefaultCookie("EasAuthPattern", _target);
    if("QrCodeToken" == _target) {
    	$(".user_cont").hide();
        $(".user-cont-qrcode,.qr-tips").show();
        $(".kingdee-eas,.type-pictrue,#loginErrorID").addClass("qr-code");
        $(".login-switch").addClass("user-name").removeClass("qrcode");
        $(".login-switch img").attr("src", "./images/newlogin1/username-login.png");
    } else {
        $(".user_cont").show();
        $(".user-cont-qrcode,.ui-form-title.login-title,.qr-tips").hide();
        $(".kingdee-eas,.type-pictrue,#loginErrorID").removeClass("qr-code");
        $(".login-switch").removeClass("user-name").addClass("qrcode");
        $(".login-switch img").attr("src", "./images/newlogin1/qrcode-login.png");
    }
}

//\u83b7\u53d6\u4e8c\u7ef4\u7801\u56fe\u7247
function getQrCodeUrl() {
    var chooseDataCenter = document.getElementById("dataCenter");
    var dataCenter = chooseDataCenter.options[chooseDataCenter.selectedIndex].value;
    $.get("QrCodeLoginServlet?language="+defaultLang+"&dataCenter="+dataCenter, {}, function(result) {
        if(result.success && result.result) {
            //\u83b7\u53d6\u56fe\u7247\u5931\u8d25\u65f6\uff0c\u5c1d\u8bd5\u91cd\u65b0\u83b7\u53d6
            if(result.errinfo == "200") {
                //\u83b7\u53d6\u6210\u529f
                window.setTimeout("getQrCodeUrl()", 120000);
                var retData = result.result;
                var url = retData.url;
                var qrCodeToken = retData.token;
                $("#qrCodeToken").val(qrCodeToken);
                $(".user-cont-qrcode .qr-wrap img").attr("src",url);

                qrLoginPolling();
            } else {
                dealQrCodeErr(result);
            }

        } else {
            //\u83b7\u53d6\u56fe\u7247\u5931\u8d25\u65f6\uff0c\u5c1d\u8bd5\u91cd\u65b0\u83b7\u53d6
            if(getQrCodeUrlCount > 0) {
                getQrCodeUrlCount--;
                getQrCodeUrl();
            } else {
            	console.log("\u83b7\u53d6\u56fe\u7247\u5931\u8d25");
            }

        }
    });
}






function pollingCallBack(userNumber, openId) {
    if("0" == licenseValidDayJs) {
        showErrMsg('-errlicense');
        return ;
    }
    if(typeof userNumber == "undefined" || userNumber == null || $.trim(userNumber) == "" || userNumber == "null") {
        showErrMsg('2');
        return;
    }
    $("#username").val(userNumber);
    $("#password").val($("#qrCodeToken").val());
    login();
}

//\u8f6e\u8be2\u670d\u52a1\u5668
function qrLoginPolling() {
    var qrcodeToken = $("#qrCodeToken").val();
    var chooseDataCenter = document.getElementById("dataCenter");
    var dataCenter = chooseDataCenter.options[chooseDataCenter.selectedIndex].value;
    $.get("QrLoginPollingServlet?language="+defaultLang+"&dataCenter="+dataCenter+"&qrcodeToken="+qrcodeToken, function(result) {
        if(result.success && result.result) {
            if(result.errinfo == "200") {
                try {
                    eval("("+result.result+")")
                } catch(e) {

                }
            } else {
                dealQrCodeErr(result);
            }
        } else {
            //\u4e0d\u505a\u5904\u7406
        }
    });
}

/*\u5904\u7406\u5f02\u5e38\u4fe1\u606f*/
function dealQrCodeErr(result) {
    if(result.errinfo == "400") {
        //\u7f51\u7edc\u4e0d\u901a
        showErrMsg('1');
    } else if(result.errinfo == "408") {
        //\u4e8c\u7ef4\u7801\u672a\u88ab\u626b\u63cf\uff0c\u91cd\u65b0\u83b7\u53d6
        qrLoginPolling();
    } else if(result.errinfo == "409") {
        //the qrcode from yunzhijia is ExpireTime
        showErrMsg('3');
    } else if(result.errinfo == "500") {
        //unknown exception from yunzhijia
        showErrMsg('4');
    } else if(result.errinfo == "501") {
        //unknown exception from yunzhijia
        showErrMsg('4');
    } else if(result.errinfo == "502") {
        //unknown exception from yunzhijia
        showErrMsg('4');
    } else if(result.errinfo == "503") {
        ////the qrcode from yunzhijia error
        if(getQrCodeUrlCount > 0) {
            getQrCodeUrlCount--;
            getQrCodeUrl();
        } else {
            //\u7ed9\u51fa\u63d0\u793a
            showErrMsg('1');
        }
    }
}

function showErrMsg(errNumber) {
    var errSpan = $(".login-app-qrerr"+errNumber);
    document.getElementById("loginErrorID").innerHTML = errSpan.html();

    //\u9519\u8bef \u63d0\u793a\u4fe1\u606f\u52a0\u4e2a\u5c0f\u56fe\u6807
    var loginErrorInfo = $("#loginErrorID").html();
    if ($.trim(loginErrorInfo)){
        loginErrorInfo =  "<span>" + loginErrorInfo+"</span>";
        $("#loginErrorID").html(loginErrorInfo);
        $("#loginErrorID").css({"display":"block"});
    }

    //\u9519\u8bef\u63d0\u793a\u4fe1\u606f\u592a\u957f\uff0c\u6837\u5f0f\u8c03\u6574
    var layoutDivWidth = $("#layoutDiv").width();
    var errinfoWidth = $("#loginErrorID").width();
    $("#loginErrorID").css("width", errinfoWidth+"px");
    $("#loginErrorID").css("left", ((layoutDivWidth-errinfoWidth)/2)+"px");
}

function clearErrMsg() {
    $("#loginErrorID").html("");
    $("#loginErrorID").css({"display":"none"});
}

function initEvent() {

    $(".login_content .user .input_text").bind("focus", function() {
        $(this).parent().parent().css("borderBottom", "1px solid #44BBFC");
    });

    $(".login_content .user .input_text").bind("blur", function() {
        $(this).parent().parent().css("borderBottom", "1px solid #ccc");
    });

    $(document).bind("click", function() {

        for (i=0;i<selects.length;i++){
            $$$('select_info_' + selects[i].id).className = 'tag-select';
            $$$('options_' + selects[i].id).style.display = 'none';
            $("#select_"+selects[i].id+" .dropdown-pic").removeClass("up");
        }
    })

	$("#validateCode").keyup(function(){
		checkValidateCode(true);
		if(validateCodeCheck){
			$("#validateCodeTip").show();
		}else{
			$("#validateCodeTip").hide();
		}
	});
}

function closePage(){
    window.location.href = 'about:blank ';
    window.close();
}

//init the login_form value

function initLoginFormValue(){
    multiLanguage();
    var dcIdx = getCookie("EasPortalDataCenter");
    var idx = 0 ;
    //priority is: 1.request parameter selectDataCenter 2.forceDefaultDc 3.cookie EasPortalDataCenter
    if(selectDataCenterFlag==-1 && forceDefaultDc==-1 && dcIdx != null && dcIdx!=undefined ){
        try{
            idx = new Number(dcIdx);
        }catch(e){
            idx = -1 ;
        }
        var dataCenterSel = document.getElementById("dataCenter");
        if(idx > -1 && idx < dataCenterSel.options.length)
            dataCenterSel.selectedIndex=idx;
    }

    var username = getCookie("EasPortalUsername");
    if(username!=null && username!="" && username!="null" &&username!='undefined'){
        document.getElementById("username").value = username;
        document.getElementById("password").focus();
    }else{
        document.getElementById("username").focus();
    }
    if(selectLangFlag){
		var localeSel = document.getElementById("locale");
		var easPortalLocaleLanguage = getCookie("EasPortalLocaleLanguage");

		try{
			if( typeof easPortalLocaleLanguage == "undefined" ||
				easPortalLocaleLanguage == null ||
				$.trim(easPortalLocaleLanguage) == "" ||
				easPortalLocaleLanguage == "null" ) {
				easPortalLocaleLanguage = localeSel.options[localeSel.selectedIndex].value;
			}
			var	_idx = 0;
			for(var i=0;i<localeSel.options.length;i++){
				if(easPortalLocaleLanguage == localeSel.options[i].value){
					_idx = i;
					break;
				}
			}
			localeSel.selectedIndex = _idx;
			indexChange();
		}catch(e){
			var langIdx = getCookie("EasPortalLocale");
			idx = 0 ;
			try{
				idx = new Number(langIdx);
			}catch(e){
				idx = 0 ;
			}
			if(idx <0 ||  idx >= localeSel.length){
				idx = 0 ;
			}
			if(localeSel.selectedIndex!=idx){
				localeSel.selectedIndex=idx;
				indexChange();
			}
		}
    }
	//\u8c03\u6574\u8bed\u8a00\u9009\u62e9\u6846\u7684\u4f4d\u7f6e
	if("L1" == defaultLanguage){
		$("#top").children().first().attr("style","position:relative;left:25px")
	}else{
		$("#top").children().first().attr("style","position:relative;left:55px")
	}

}

//autoLogin
function autoLogin(){
    enabledComponent(true);
    setAutoLoginFormValue();
    autoLogon = true ;
    setTimeout("login()",200);
}

function setAutoLoginFormValue(){
    var lang = autoLoginDefaultLocale;
    if(lang == null || lang == "" || lang == "null"){
        lang = defaultLanguage;
    }

    var idx = document.getElementById("locale").options[lang];
    if(idx == -1 ){
        idx = 0 ;
    }
    var dc = autoLoginDataCenter;
    if(dc == null || dc == "" || dc == "null"){
        dc = "error";
    }
    idx = document.getElementById("dataCenter").options[dc];

    if(idx == -1 ){
        idx = 0 ;
    }

    if(autoLoginDataCenterFlag){
        document.getElementById("dataCenter").value = autoLoginDataCenter;
    }

    document.getElementById("username").value = autoLoginUser;
    document.getElementById("password").value = autoLoginCheckFlag;
}

//set Component state
function enabledComponent(bflag){
    document.getElementById("username").readOnly = bflag;
    document.getElementById("password").readOnly = bflag;
    document.getElementById("dataCenter").readOnly = bflag;
    document.getElementById("locale").readOnly = bflag;
    document.getElementById("loginSubmit").disabled = bflag;
}

function loginCancelBt(){
  document.getElementById("username").value = "";
  document.getElementById("username").focus();
  document.getElementById("password").value = "";
}

function fingerLogin(){
    checkFinger();
}

function login(){
	if(storage('localStorage').getItem("ckie")!=true && $("#cookieKey").attr('value')!="auto"){
		var img = document.getElementById("pingCloud");
		var version = Math.round(Math.random()*10000000);
		img.setAttribute("src","https://account.kdcloud.com/favicon.ico?v="+version);
		img.onload = function(){
		$("a.privacy_policy").attr("href","https://account.kdcloud.com/privacy?id=3515729708820185088");
		};
		var localeLang = document.getElementById("locale").value;
		var html = $("#cookieDomBox").html();
		//\u767b\u5f55\u524d\u589e\u52a0cookie\u63d0\u793a
		$('body').dialogbox({type:"ok",title:"",divHeight:"cookieheight",locale:localeLang,message:html},function($btn){
				if($btn == "ok") {
					storage('localStorage').setItem("ckie",true);
					return loginReal();
				}
			}
		);

		//$('.dialogbox-button-bar').append('<input id="keyInput" style="width: 0px;border: 0px;">');

		setInterval(function(){
			document.getElementById('keyInput').focus();
		},1000)



		 $('#keyInput').keydown(function(event) {
		  if (event.keyCode === 13) {
		   storage('localStorage').setItem("ckie",true);
			return loginReal();
		  }
		});

	}else{
		return loginReal();
	}
}

function loginReal(){


	var dataCenter = document.getElementById("dataCenter").value;
    var locale = document.getElementById("locale").value;
	var username =  document.getElementById("username").value;


    //for re-submit form, if comment this, it will redirect to eassso/login page when you submit form by pressing enter key many times.
    if(document.getElementById("loginSubmit").disabled)
        return;
    if("BaseDB" == authPattern) {
        enabledComponent(true);
    }
    var loginErrorID = document.getElementById("loginErrorID");
    if(loginErrorID){
       loginErrorID.innerHTML="";
       $(loginErrorID).hide();
    }

    if(autoLoginUserFlag)
        document.getElementById("username").value = autoLoginUser;

    //white space stripped
    document.getElementById("username").value = username.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

    var password =  document.getElementById("password").value;
    var solutionName =  document.getElementById("solutionName").value ;

    var dbType1 = 0 ;
    var divID = document.getElementById("dataCenter");
    document.getElementById("dbType").value = dbType[divID.selectedIndex];
    try{
        dbType1 = new Number(document.getElementById("dbType").value);
    }
    catch(e){
        dbType1 = 0 ;
    }

    var authPattern;
    if(loginForm.commentscore != null){
        if(loginForm.commentscore[0].checked){
            authPattern = "ReginAutoLogin" ;
        }else{
            authPattern = loginForm.userAuthPattern.value ;
        }
    } else{
        authPattern = loginForm.userAuthPattern.value ;
    }

    setLoginCookie();
    if(typeof dealUsbKeyOper!='undefined' && dealUsbKeyOper instanceof Function){
        dealUsbKeyOper();
    }

    document.getElementById("enU").value = getRsaEntrypt(base64Decode($.trim($("#username").val())));
    document.getElementById("enP").value = getRsaEntrypt(base64Decode($.trim($("#password").val())));
    document.getElementById("enL").value = base64Decode($.trim(document.getElementById("locale").value));
    document.getElementById("enD").value = base64Decode($.trim(document.getElementById("dataCenter").value));

    document.getElementsByName("locale")[0].value = base64Decode($.trim(document.getElementById("locale").value));
    document.getElementsByName("dataCenter")[0].value = base64Decode($.trim(document.getElementById("dataCenter").value));
    document.getElementsByName("username")[0].value = getRsaEntrypt(base64Decode($.trim($("#username").val())));
    document.getElementsByName("password")[0].value = getRsaEntrypt(base64Decode($.trim($("#password").val())));
    if ('2'!=$("#isFirstPage").val()){
        document.getElementById("lt").value = base64Decode($.trim(document.getElementById("lt").value));
        document.getElementById("isPureWeb").value = base64Decode($.trim(document.getElementById("isPureWeb").value));
        document.getElementById("easSessionId").value = base64Decode($.trim(document.getElementById("easSessionId").value));
        document.getElementById("userAuthPattern").value = base64Decode($.trim(document.getElementById("userAuthPattern").value));
        document.getElementById("loginFlow").value = base64Decode($.trim(document.getElementById("loginFlow").value));
        $("#isFirstPage").val('2');
    }
    document.loginForm.submit();
    return false ;
}

function base64Decode(str){
    var b = new KDBase64();
    return b.encode(str);

}

function getRsaEntrypt(pwd){
    var pubKey = $('#pubKey').val();
    if(!pubKey||"null"==pubKey){
        return pwd;
    }
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(pubKey);
	var rs = encrypt.encrypt(pwd);
	if(rs==false&&rs!=pwd){
		return pwd;
	}
    return rs;
}


function EnEight(str){
    var monyer = new Array();
    for(var i=0;i<str.length;i++)
        monyer+=","+str.charCodeAt(i).toString(8);
    return monyer;
}

function setLoginCookie(){

    var user = document.getElementById("username").value;
    setDefaultCookie("EasPortalUsername",user);

    var datacenterBox = document.getElementById("dataCenter");
    setDefaultCookie("EasPortalDataCenter", datacenterBox.selectedIndex);

    var localeBox = document.getElementById("locale");
    setDefaultCookie("EasPortalLocale", localeBox.selectedIndex);
	//Cookie\u8bbe\u7f6e\u8bed\u8a00\u7c7b\u578bL1\L2\L3
    setDefaultCookie("EasPortalLocaleLanguage",localeBox.options[localeBox.selectedIndex].value);
    var dbType = document.getElementById("dbType").value;
    setDefaultCookie("EasPortalDBType",dbType);
}

function iniLoginTypet(){
    if(loginForm.commentscore != null){
        if(String(document.getElementById("kdrbLoginUser").disable) == "false"){
            if(loginForm.commentscore[0].checked){
                document.getElementById("username").disable = true;
                document.getElementById("password").disable = true;
                tempLoginName = document.getElementById("username").value;
                document.getElementById("username").value = "";
                loginForm.userAuthPattern.value = "ReginAutoLogin";
            }
            else{
                document.getElementById("username").disable = false;
                document.getElementById("password").disable = false;
                document.getElementById("username").value = tempLoginName;
                loginForm.userAuthPattern.value = authPattern;
            }
        }
    }
}

function displayProcessBar(displayValue){
    var loginProcceBarID = document.getElementById("loginProcceBarID");
    if(loginProcceBarID){
        if(displayValue == "block"){
            loginProcceBarID.style.display = "block";
        }else{
            loginProcceBarID.style.display = "none";
        }
    }
}

function loginEnterPassword(event){
    if(isNullObject(document.getElementById("validateCode"))){
        loginByEnterKey(event);
    }
}

function loginByEnterKey(event){
//    event = event?event:window.event;
//    if(event.keyCode == 13){
//        login();
//    }
}

function indexChange(){
    var localeBox = document.getElementById("locale");
    var datacenterBox = document.getElementById("dataCenter");
	var userAuthPattern = $("#userAuthPattern").val();
    document.location.href = langIndexChangeUrl + "&selectDataCenter="+datacenterBox.selectedIndex+"&selectLang="+localeBox.options[localeBox.selectedIndex].value+"&userAuthPattern="+userAuthPattern;
}

function enterkey(e) {
      e=e?e:window.event;
      var elm=e.target || e.srcElement;
      if(e.keyCode==13) {
        if(elm.tabIndex && elm.getAttribute("id")!='loginSubmit'){
            var elms = getTabElms();
            for(var i=0; i<elms.length; i++){
                //curent element -> next element focus
                if(elm.tabIndex == elms[i].tabIndex){

                    if(i == elms.length-1){
                        if(!elms[i+1].disabled)
                            elms[0].focus();
                    }else{
                        if(!elms[i+1].disabled)
                            elms[i+1].focus();
                    }
                    return;
                }
            }

        }
      }
}

function getTabElms(){
      var elms = new Array();
      var formElms = document.getElementById("loginForm").elements;
      for (var i=0; i<formElms.length; i++){
         var elm = formElms[i];
         if(elm.tabIndex)
            elms.push(elm);
      }
      return elms;
}

//\u6839\u636e\u95e8\u6237\u7684\u8bbe\u7f6e\u5207\u6362\u80cc\u666f\u56fe\u7247\u7684\u5c55\u793a\u7c7b\u578b
function setBackImgBySetting(defaultLang,dataCenter){
	var bgShowTypes = $("#backImgDiv").attr("bgShowType").split(";");
	bgShowType = (defaultLang=='ch')?bgShowTypes[0]:((defaultLang=='tw')?bgShowTypes[1]:bgShowTypes[2]);
	var typeTmp = (bgShowType=="FULL_BG")?"full_bg1":(($(window).width() > 1600)?"big_bg1":"bg1");
	backImg_1 ="url(/portal/logoImgServlet?type="+typeTmp+"&language="+defaultLang+"&dataCenter="+dataCenter+"&insId=insId&v=2)";
	var bg_url_css = (bgShowType=="FULL_BG")?" 0px no-repeat":(($(window).width() > 1600)?" 230px no-repeat":" 130px no-repeat");
	$('body #backImgDiv').css("background",eval("backImg_1")+bg_url_css);
	$('body #backImgDiv').css("background-position-y","bottom");
	return bgShowType;
}

function reSize(){
    //\u9ad8\u5ea6\u5c0f\u4e8e550\u51fa\u73b0\u7ad6\u76f4\u6eda\u52a8\u6761
	var difference = ($(".bottom_recordcode") && $(".bottom_recordcode").length>0)?47:25;
    if (winH<550){
        $("#backImgDiv").parent().css("overflow-y","scroll");
        $("#backImgDiv").css("min-height",582);
		$("#bottom").css("top",parseInt(document.documentElement.scrollHeight - difference));
		if($("#browserTip").is(':hidden')==false){
			$("#browserTip").css("width",parseInt(document.body.scrollWidth-382));
			$("#browserTip").css("top",parseInt(document.documentElement.scrollHeight - difference));
		}
    }else{
    	$("#backImgDiv").parent().css("overflow-y","hidden");
		$("#bottom").css("top",parseInt(document.documentElement.clientHeight - difference));
		if($("#browserTip").is(':hidden')==false){
			$("#browserTip").css("width",parseInt(document.body.offsetWidth-382));
			$("#browserTip").css("top",parseInt(document.documentElement.clientHeight - difference));
		}
    }



	var chooseDataCenter = document.getElementById("dataCenter");
	var dataCenter = chooseDataCenter.options[chooseDataCenter.selectedIndex].value;
	var bgShowType = setBackImgBySetting(defaultLang,dataCenter);

	var size;
	if(bgShowType=='FULL_BG'){
		size = (window.innerWidth-$("#layoutDiv").width())+'px 100%';
		$('body').css('background','#FFFFFF');
	}else{
		if($(window).width() > 1600){
			size = "1114.2px 860.4px";
		}else{
			size = "742.8px 573.6px";
		}
		$('body').css('background-image','url("/eassso/images/newlogin1/full_bg1_logo_default_ch.png")');
		$('body').css('background-position','0px 100%');
		$('body').css('background-repeat','no-repeat')
	}
	$('body').css("background-size",(window.innerWidth-$("#layoutDiv").width())+'px 100%');
	$('body #backImgDiv').css("background-size",size);

}

function redirectToTopFrame(){
    if(top.jSetting){
        top.location.href = "/portal/web_frame/uncheck/logout.action";
    }else{
        if(parent != this && this.name != "ContentFrame"){
            var topFrame = getTopFrame(this);
            var contentFrame = getContentFrame(topFrame);
            if(!isNullObject(contentFrame)){
                // when waf session is invalid, poratl should logout also.
                var cf = contentFrame.document.frames('contentFrame');
                cf.kingdee.portal.support.logoutWebNoTips();
            } else {
                // ignore the situation that the waf page is embed in other page

            }
        }
    }
}

function getTopFrame(win){
    if(win.parent == win){
        return win;
    } else {
        return getTopFrame(win.parent);
    }
}

function getContentFrame(win){
    var array = win.document.getElementsByName("ContentFrame");
    if(array != null && array.length > 0){
        return array[0];
    } else {
        return null;
    }
}

function isNullObject(obj){
    if(obj == null || obj == "undefined" || obj == "null"){
        return true;
    } else {
        return false;
    }
}

/** init select **/
var selects = document.getElementsByTagName('select');
var isIE = (document.all && window.ActiveXObject && !window.opera) ? true : false;
function $$$(id) {
    return document.getElementById(id);
}
function stopBubbling (ev) {
    ev.stopPropagation();
}
function rSelects() {
    for (i=0;i<selects.length;i++){
        selects[i].style.display = 'none';
        select_tag = document.createElement('div');
        select_tag.id = 'select_' + selects[i].id;
        select_tag.className = 'dropdown';
        select_left = document.createElement('span');
        select_left.className="dropdown-left"
        select_pic = document.createElement('span');
        select_pic.className="dropdown-pic"
        select_pic.style.cursor='pointer';
        select_tag.appendChild(select_left);
        select_tag.appendChild(select_pic);

        selects[i].parentNode.insertBefore(select_tag,selects[i]);
        select_info = document.createElement('div');
        select_info.id = 'select_info_' + selects[i].id;
        select_info.className='tag-select';
        select_info.style.cursor='pointer';
        select_tag.appendChild(select_info);
        select_ul = document.createElement('ul');
        select_ul.id = 'options_' + selects[i].id;
        select_ul.className = 'tag-options';
        select_ul.style.position='absolute';
        select_ul.style.display='none';
        select_ul.style.zIndex='999';
        select_tag.appendChild(select_ul);
        rOptions(i,selects[i].id);
        mouseSelects(selects[i].id);
    }
}

function rOptions(i, name) {
    var options = selects[i].getElementsByTagName('option');
    var options_ul = 'options_' + name;
    for (n=0;n<selects[i].options.length;n++){
        option_li = document.createElement('li');
            option_li.style.cursor='pointer';
            option_li.className='open';
            option_li.title=selects[i].options[n].text;
        $$$(options_ul).appendChild(option_li);

        option_text = document.createTextNode(selects[i].options[n].text);

        option_li.appendChild(option_text);

        option_selected = selects[i].options[n].selected;

        if(option_selected){
            option_li.className='open-selected';
            option_li.id='selected_' + name;
            $$$('select_info_' + name).title = option_li.innerHTML;
            $$$('select_info_' + name).appendChild(document.createTextNode(option_li.innerHTML));
        }

        option_li.onmouseover = function(){ this.className='open-hover';}
        option_li.onmouseout = function(){
            if(this.id=='selected_' + name){
                this.className='open-selected';
            }
            else {
                this.className='open';
            }
        }

        option_li.onclick = new Function("clickOptions("+i+","+n+",'"+selects[i].id+"')");
    }
}

function mouseSelects(name){
    var sincn = 'select_info_' + name;
    var pic = $$$(sincn).previousSibling;
    $$$(sincn).onmouseover = function(){ if(this.className=='tag-select') this.className='tag-select-hover'; }
    $$$(sincn).onmouseout = function(){ if(this.className=='tag-select-hover') this.className='tag-select'; }
    if (isIE){
        $$$(sincn).onclick = new Function("clickSelects('"+name+"');window.event.cancelBubble = true;");
        pic.onclick = new Function("clickSelects('"+name+"');window.event.cancelBubble = true;");
    }
    else if(!isIE){
        $$$(sincn).onclick = new Function("clickSelects('"+name+"');");
        $$$(sincn).addEventListener("click", stopBubbling, false);
        pic.onclick = new Function("clickSelects('"+name+"');");
        pic.addEventListener("click", stopBubbling, false);
    }

}

function clickSelects(name){
    var sincn = 'select_info_' + name;
    var sinul = 'options_' + name;
    $$$(sinul).style.display = '';
    for (i=0;i<selects.length;i++){
        if(selects[i].id == name){
            if( $$$(sincn).className =='tag-select-hover'||$$$(sincn).className =='tag-select'){
                $$$(sincn).className ='tag-select-open';
                $$$(sinul).style.display = '';
                $("#select_"+name+" .dropdown-pic").addClass("up");
            }
            else if( $$$(sincn).className =='tag-select-open'){
                $$$(sincn).className = 'tag-select-hover';
                $$$(sinul).style.display = 'none';
                $("#select_"+name+" .dropdown-pic").removeClass("up");
            }
        }
        else{
            $$$('select_info_' + selects[i].id).className = 'tag-select';
            $$$('options_' + selects[i].id).style.display = 'none';
            $("#select_"+selects[i].id+" .dropdown-pic").removeClass("up");
        }
    }
}

function clickOptions(i, n, name){
    var li = $$$('options_' + name).getElementsByTagName('li');
    $$$('selected_' + name).className='open';
    $$$('selected_' + name).id='';
    li[n].id='selected_' + name;
    li[n].className='open_hover';
    $$$('select_' + name).removeChild($$$('select_info_' + name));
    select_info = document.createElement('div');
    select_info.id = 'select_info_' + name;
    select_info.className='tag-select';
    select_info.style.cursor='pointer';
    $$$('options_' + name).parentNode.insertBefore(select_info,$$$('options_' + name));

    mouseSelects(name);

    $$$('select_info_' + name).title=li[n].title;
    $$$('select_info_' + name).appendChild(document.createTextNode(li[n].innerHTML));
    $$$( 'options_' + name ).style.display = 'none' ;
    $$$( 'select_info_' + name ).className = 'tag-select';
    selects[i].options[n].selected = 'selected';
    if(name==='dataCenter' || name === 'locale'){
        indexChange();
    }

    var _textDataCenter = $('#select_info_' + name).html();
}

var defaultLang ;
if("L1" == defaultLanguage){
    defaultLang = "en";
}else if("L3" == defaultLanguage){
    defaultLang = "tw";
}else{
    defaultLang = "ch";
}


var backImg_1 ="";
var loginLogoImg = "";

window.onload = function(e) {
	winW=$(window).width();
	winH=$(window).height();
    rSelects();
    $(".input_text").each(function(){
        var thisVal=$(this).val();
        var thisId = $(this).attr("id");
        if(thisId != "username" && thisId != "password") return;
        //\u5224\u65ad\u6587\u672c\u6846\u7684\u503c\u662f\u5426\u4e3a\u7a7a\uff0c\u6709\u503c\u7684\u60c5\u51b5\u5c31\u9690\u85cf\u63d0\u793a\u8bed\uff0c\u6ca1\u6709\u503c\u5c31\u663e\u793a
        if(thisVal!=""){
           $("."+thisId+"-text").hide();
          }else{
           $("."+thisId+"-text").show();
          }
          $(this).keyup(function(){
           var val=$(this).val();
           $("."+thisId+"-text").hide();
          }).blur(function(){
            var val=$(this).val();
            if(val!=""){
             $("."+thisId+"-text").hide();
            }else{
             $("."+thisId+"-text").show();
            }
          })
     });

    $(".login-switch").hover(function(){
    	 if($(this).hasClass("user-name")) {
             $(".login-switch-text1").show();
         } else {
             $(".login-switch-text0").show();
         }
         $(".login-switch-text-right1,.login-switch-text-right0").show();
    },function(){
    	$(".login-switch-text0,.login-switch-text1,.login-switch-text-right0,.login-switch-text-right1").hide();
    });
    var chooseDataCenter = document.getElementById("dataCenter");
    var dataCenter = chooseDataCenter.options[chooseDataCenter.selectedIndex].value;
    //xjw \u5224\u65ad\u662f\u5426\u8bbe\u7f6e\u4e86\u5e73\u94fa
	//setBackImgBySetting();
    loginLogoImg = "/portal/logoImgServlet?type=login&language="+defaultLang+"&dataCenter="+dataCenter+"&insId=insId";
    $('body #logoLoginPage').attr("src",eval("loginLogoImg"));

    //\u9519\u8bef \u63d0\u793a\u4fe1\u606f\u52a0\u4e2a\u5c0f\u56fe\u6807
    var loginErrorInfo = $("#loginErrorID").html();
    if ($.trim(loginErrorInfo)){
        loginErrorInfo =  "<span>" + loginErrorInfo+"</span>";
        $("#loginErrorID").html(loginErrorInfo);
        $("#loginErrorID").css({"display":"block"});
    }
    //\u9519\u8bef\u63d0\u793a\u4fe1\u606f\u592a\u957f\uff0c\u6837\u5f0f\u8c03\u6574
    var layoutDivWidth = $("#layoutDiv").width();
    var errinfoWidth = $("#loginErrorID").width();
    $("#loginErrorID").css("width", errinfoWidth+"px");
    $("#loginErrorID").css("left", ((layoutDivWidth-errinfoWidth)/2)+"px");

 	if($(".type-pictrue").length < 1) {
		$(".kingdee-eas").css({"left":"64px"});
	}
	//\u5224\u65ad\u63d0\u793a\u4fe1\u606f\u662f\u5426\u5e94\u8be5\u663e\u793a
	if(window.screen.width<1920||window.screen.height<1080){
		$("#browserTip").show();
	}
	var browser = BrowserInfo();
    if (""==browser.name ||("Chrome" == browser.name && parseInt(browser.version) < 59) ||
                ("Internet Explorer" == browser.name && parseInt(browser.version) <9)) {
		$("#browserTip").show();
	}
 	reSize();
    //\u80cc\u666f\u56fe\u6e10\u53d8
	cssFilter();
	helpBtn();
}

function setLoginButtonImg(licenseValid){
    if(licenseValid){
        changeCN_TW_ENBtn();
        //\u767b\u5f55\u6309\u94ae\u7ed1\u5b9a\u9f20\u6807\u6ed1\u8fc7\u70b9\u51fb\u4e8b\u4ef6
        $('#loginSubmitImg_id').mouseover(function(){
            $("#loginSubmit").css({"background":"#39B0FB"});
            $("#loginSubmitImg_id").css({"display":"block"});
        });
        $('#loginSubmitImg_id').mouseout(changeCN_TW_ENBtn);
        $('#loginSubmitImg_id').click(function(){
            $("#loginSubmit").css({"background":"#39B0FB"});
            $("#loginSubmitImg_id").css({"display":"block"});
        });
        changCN_TW_ENFingerLoginIcon();
        $('#fingerLoginSubmit_spanId').mouseover(function(){
            if (defaultLanguage == 'L3'){
                $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginMouseoverSta_TW.png)");
            }else if (defaultLanguage == 'L2'){
                $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginMouseoverSta_CN.png)");
            }else{
                $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginMouseoverSta_EN.png)");
            }
        });
        $('#fingerLoginSubmit_spanId').mouseout(changCN_TW_ENFingerLoginIcon);
        $('#fingerLoginSubmit_spanId').click(function(){
            if (defaultLanguage == 'L3'){
                $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginClickStat_TW.png)");
            }else if (defaultLanguage == 'L2'){
                $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginClickStat_CN.png)");
            }else{
                $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginClickStat_EN.png)");
            }
        });
    }else{
        changeCN_TW_ENBtnGray();
        changCN_TW_ENFingerLoginIconGray();
    }

}

function cssFilter()
{
 var opacity = $("#backImgDiv").css("opacity");
  if(opacity < 1){
	  var cc = parseFloat(opacity)+parseFloat(0.04);
	  var bb = parseInt(cc*100);
	  backImgDiv.style.opacity = cc;
	  backImgDiv.style.filter = "alpha(opacity="+bb+")";
	  setTimeout(cssFilter, 50);
  }else{
	  backImgDiv.style.opacity = 1;
  }
}
var changeCN_TW_ENBtn = function(){
    $("#loginSubmit").css({"background":"#44BBFC"});
    $("#loginSubmitImg_id").css({"display":"block"});
}
var changeCN_TW_ENBtnGray = function(){
    $("#loginSubmit").css({"background":"#44BBFC"});
    $("#loginSubmitImg_id").css({"display":"block"});
    $("#loginSubmit").attr("disabled", "disabled");
}
var changCN_TW_ENFingerLoginIcon = function(){
    $("#validateCode_p").css({"width":"220px"});
    if (defaultLanguage == 'L3'){
        $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginNormalSta_TW.png)");
    }else if (defaultLanguage == 'L2'){
        $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginNormalSta_CN.png)");
    }else{
        $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginNormalSta_EN.png)");
    }
}
var changCN_TW_ENFingerLoginIconGray = function(){
    //$("#loginSubmitImg_id").css({"display":"none"});
    //$("#fingerLoginSubmit").css({"display":"none"});
	$('#loginSubmit').attr("disabled","disabled");
	$("#loginSubmit").css({"background":"#CCCCCC"});
	$('#loginSubmit').unbind("click");
	$("#findPass").css({"display":"none"});
	$("#licenseExpireTip").css({"display":"block"});
	$("#fingerLoginSubmit").attr("disabled","disabled");
	$("#fingerLoginSubmit").css({"background":"#CCCCCC"});

    $("#validateCode_p").css({"width":"220px"});
    if (defaultLanguage == 'L3'){
        $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginNormalSta_TW_gray.png)");
    }else if (defaultLanguage == 'L2'){
        $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginNormalSta_CN_gray.png)");
    }else{
        $('#fingerLoginSubmit_spanId').css("background-image","url(./images/newlogin/fingerLoginImg/fingerLoginNormalSta_EN_gray.png)");
    }
}

/** validateCode function **/
function generateValidateCode(){
	$("#validateCodeTip").hide();
    var validateCodeImg = document.getElementById("validateCodeImg");
    validateCodeImg.src = "validateCodeServlet?"+Math.random();

}

function checkValidateCode(isOnlyCheck) {
    try{
    	var ajaxUrl = "/eassso/checkValidateCodeServlet";
    	$.ajax({
            type: "GET",
            url: ajaxUrl,
            data: {
            	validateCode:$("#validateCode").val()
            },
            dataType: "json",
            async:false,
            success: function(data){
            	if(data){
            		validateCodeCheck = true;
                } else {
					if(isOnlyCheck){
						validateCodeCheck = false;
					}else{
						document.getElementById("loginErrorID").innerHTML = invalidCodeMsg;

						//\u9519\u8bef \u63d0\u793a\u4fe1\u606f\u52a0\u4e2a\u5c0f\u56fe\u6807
						var loginErrorInfo = $("#loginErrorID").html();
						if ($.trim(loginErrorInfo)){
							loginErrorInfo =  "<span>" + loginErrorInfo+"</span>";
							$("#loginErrorID").html(loginErrorInfo);
							$("#loginErrorID").css({"display":"block"});
						}
						enabledComponent(false);
						generateValidateCode();
						validateCodeCheck = false;
					}
                }
            }
       });
    } catch(e) {
        return false;
    }
}

/**
 * *****  jsUtils.js function strat *****
 */

//string is empty,"" or null
function isEmpty(str){
    var result = false;
    if(str == "" || str == null || str == "undefined"){
        result = true;
    }
    return result;
}
//set default cookie
function setDefaultCookie(cookieName,cookieValue){
    var path = "/eassso";
    if("EasPortalUsername"==cookieName){
		var encode = base64Decode(cookieValue);
		storage('localStorage').setItem("EasPortalUsername",JSON.stringify(encode));
	}else{
		setCookie(cookieName,cookieValue,"","",path);
	}
}

//set cookie
function setCookie(name, value, expires, domain, path, secure) {
    if(isEmpty(name)){
        return ;
    }

    var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
    if(isEmpty(expires)){
        var tmpDate = new Date(2100,1,1);
        expires = tmpDate;
    }
    if (expires instanceof Date) {
        cookieText += "; expires=" + expires.toGMTString();
    }
    if (path) {
        cookieText += "; path=" + path;
    }
    if (domain) {
        cookieText += "; domain=" + domain;
    }
    if (secure) {
        cookieText += "; secure";
    }
    document.cookie = cookieText;
}


//get cookie
function getCookie(cName){
    var cookieName = encodeURIComponent(cName) + "=",
    cookieStart = document.cookie.indexOf(cookieName),
    cookieValue = null;
    if (cookieStart > -1){
        var cookieEnd = document.cookie.indexOf(";", cookieStart)
        if (cookieEnd == -1){
            cookieEnd = document.cookie.length;
        }
        cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
    }
    if("EasPortalUsername"==cName){
		if(isEmpty(cookieValue)){ //\u8bfb\u53d6\u672c\u5730\u5b58\u50a8
		    var decodeName = "";
			try{
				var encodeName = storage('localStorage').getItem(cName);
				var crypto = new KDBase64();
				decodeName = crypto.decode(encodeName);
			}catch(err){
			}
			return decodeName;
		}else{
			//\u8fc1\u79fb\u52a8\u4f5c\uff0c\u5220\u9664\u6b64cookie\uff0c\u5e76\u5199\u5230localStorage
			setDefaultCookie(cName,cookieValue);
			document.cookie = cName + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/eassso';
		}
	}
    return cookieValue;
}

function createXMLHttpRequest(){
    if (typeof XMLHttpRequest != "undefined"){
        return new XMLHttpRequest();
    } else if (typeof ActiveXObject != "undefined"){
        if (typeof arguments.callee.activeXString != "string"){
            var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"];
            for (var i=0,len=versions.length; i < len; i++){
                try {
                        var xhr = new ActiveXObject(versions[i]);
                        arguments.callee.activeXString = versions[i];
                        return xhr;
                } catch (ex){
                    //skip
                }
            }
        }

        return new ActiveXObject(arguments.callee.activeXString);
    } else {
        throw new Error("No XHR object available.");
    }
}

var EventUtil = {
    addHandler: function(element, type, handler){
        if (element.addEventListener){
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent){
            element.attachEvent("on" + type, handler);
        } else {
            element["on" + type] = handler;
        }
    },
    removeHandler: function(element, type, handler){
        if (element.removeEventListener){
            element.removeEventListener(type, handler, false);
        } else if (element.detachEvent){
            element.detachEvent("on" + type, handler);
        } else {
            element["on" + type] = null;
        }
    }
};

var handPlaceHolderForIE = function(){
        var input = $('#username');
        $('#username').css('top', '11px').css('color','#3F3F3F');
        if(input.length <1){
            return;
        }
        $.each( input , function(i){
            if(!input.val()){
                $(this).css('color', '#3F3F3F');
            }
        });
        input.blur(function(e){
            if($(this).val() == $(this).attr('placeholder')){
                $(this).css('color', '#3F3F3F');
            }
            else if($(this).val() == ''){
                $(this).css('color', '#3F3F3F');
            }
        });
        input.click(function(e){
            if($(this).val() == $(this).attr('placeholder')){
                $(this).css('color', 'black');
                $(this).val('');
            }
        });
        input.focus(function(e){
            if($(this).val() == $(this).attr('placeholder')){
                $(this).val('');
                $(this).css('color', 'black');
            }
        });
};
//\u5e2e\u52a9\u8bf4\u660e\u5f39\u7a97
function helpBtn(){
    var localeBox = document.getElementById("locale");
    if(localeBox.options[localeBox.selectedIndex].value == "L1") {
        $("#clientHelpDiv").css("height","712px");
    }
}

function multiLanguage(){
    //\u5224\u65ad\u662f\u5426\u6709cookie,\u6ca1\u6709\u8bbe\u7f6e\u521d\u59cb\u5316\u7684\u591a\u8bed\u8a00\u53c2\u6570
    var EasPortalLocale = getCookie("EasPortalLocale");
	var EasPortalLocaleLanguage = getCookie("EasPortalLocaleLanguage");
    //\u786e\u4fdd\u53ea\u53d1\u9001\u4e00\u6b21\u8bf7\u6c42
    var flag = getCookie("flag");
	if(!EasPortalLocaleLanguage && !flag){
		//\u4f18\u5148\u662f\u8bed\u8a00cookie\uff0c\u6ca1\u6709\u518d\u987a\u5e8f\u4e0b\u6807
		 multiLanguage02();
	}else if(!EasPortalLocale && !flag){
        multiLanguage02();
    }else{
        return;
    }

}

function multiLanguage02(){
    var chooseDataCenter = document.getElementById("dataCenter");
    var dataCenter = chooseDataCenter.options[chooseDataCenter.selectedIndex].value;
     $.ajax({
         type: "post",
         url: "/eassso/defaultLanguageServlert",
         data: {
                language:'L2',
                dataCenter:dataCenter
                },
         dataType: "json",
         success: function(data){
             var localeBox = document.getElementById("locale");
             var temp = localeBox.options[localeBox.selectedIndex].value;
            if (data.FConfigValue=='L1'){
                $("#locale").val("L1");
            }else if(data.FConfigValue=='L3'){
                $("#locale").val("L3");
            }else{
                $("#locale").val("L2");
            }
			//\u591a\u8bed\u8a00\u573a\u666f\u8bed\u8a00\u9009\u62e9bug\u4fee\u590d
            setDefaultCookie("EasPortalLocale", localeBox.selectedIndex);
			setDefaultCookie("EasPortalLocaleLanguage",temp);
            if(temp != data.FConfigValue){
                 indexChange();
            }
            document.cookie = "flag="+true;
         }
    });
}

var showClientHelp = function(){
	$("#clientHelpDiv").show();
	if(defaultLanguage=="L1"||defaultLanguage=="L2"||defaultLanguage=="L3")
		$("#clientHelp").attr('src', "/eassso/portalClientHelper.jsp?defaultLanguage="+defaultLanguage);
}

var changeLoginType = function(authPattern){
	if("KingdeeCloud"==authPattern){
		$("#userAuthPattern").val(authPattern);
		$("#userAuthPatternTMP").val(authPattern);
		$("#loginCloud").attr("checked",true);
		$(".username-text").text($(".username-text-cloud").text());
		$(".password-text").text($(".password-text-cloud").text());
		$("#loginType").text($(".login-change-erp").text());
		$("#forget").show();
		$("#findPass").hide();
		$(".user-icon").css("background","url(./images/newlogin1/cloudzhanghu.png?v=1) no-repeat")
		$("#loginCloud").prop("checked",true);
		loginSwitch(authPattern);
	}else if(!("QrCodeToken" == authPattern)){
		$("#userAuthPattern").val(authPattern);
		$("#userAuthPatternTMP").val(authPattern);
		$("#loginErp").attr("checked",true);
		$(".username-text").text($(".username-text-erp").text());
		$(".password-text").text($(".password-text-erp").text());
		$("#loginType").text($(".login-change-cloud").text());
		$("#forget").hide();
		if($("#loginSubmit").prop("disabled")){
			$("#findPass").hide();
		}else{
			$("#findPass").show();
		}
		$(".user-icon").css("background","url(./images/newlogin1/yonghu.png?v=1) no-repeat")
		$("#loginErp").prop("checked",true);
		loginSwitch(authPattern);
	}
}


function openFindPassPage(){
	var userNumber = $("#username").val();
    var localeBox = document.getElementById("locale");
    var chooseDataCenter = document.getElementById("dataCenter");
    var dataCenter = chooseDataCenter.options[chooseDataCenter.selectedIndex].value;
	$.ajax({
		url: '/eassso/findPass?method=checkCanFindPass',
		data:{
			dataCenter:dataCenter,
			language:localeBox.options[localeBox.selectedIndex].value,
			userNumber:userNumber
		},
		success: function(data){
			var rs = JSON.parse(data);
			var actioneUrl = $("#loginForm").attr("action");
			if (JSON.parse(data).success==true){
				window.open('/eassso/findpass/findPass.jsp?language='+localeBox.options[localeBox.selectedIndex].value+"&dataCenter="
						+dataCenter+"&userNumber="+userNumber+"&actionUrl="+actioneUrl);
			}else{
				$("#loginErrorID").html("<span>"+rs.errorInfo+"<br></span>");
				$("#loginErrorID").css({"display":"block"});
			}
		}
	});
}

function BrowserInfo() {
	var res = {
		name: "",
		version: "",
	};
	var reg;
	var userAgent = self.navigator.userAgent;

	if (reg = /edge\/([\d\.]+)/i.exec(userAgent)) {
		res.name = "Edge";
		res.version = reg[1];
	}
	else if (/msie/i.test(userAgent)) {
		res.name = "Internet Explorer";
		res.version = /msie ([\d\.]+)/i.exec(userAgent)[1];
	}
	else if (/Trident/i.test(userAgent)) {
		res.name = "Internet Explorer";
		res.version = /rv:([\d\.]+)/i.exec(userAgent)[1];
	}
	else if (/chrome/i.test(userAgent)) {
		res.name = "Chrome";
		res.version = /chrome\/([\d\.]+)/i.exec(userAgent)[1];
	}
	else if (/safari/i.test(userAgent)) {
		res.name = "Safari";
		res.version = /version\/([\d\.]+)/i.exec(userAgent)[1];
	}
	else if (/firefox/i.test(userAgent)) {
		res.name = "Firefox";
		res.version = /firefox\/([\d\.]+)/i.exec(userAgent)[1];
	}
	return res;
}

var storage=(function(opts) {
		function StorageHandle(storage) {
			this.storage = window[storage] || window.sessionStorage;
		}
		StorageHandle.prototype = {
			constructor: StorageHandle,
			//\u5b58\u5165session\u7684\u65b9\u6cd5
			setItem: function(key, param) {
				if (typeof param == 'object') {
					this._setStorages(key, param);
				} else {
					this._setStorage(key, param);
				}
			},
			_setStorage: function(key, val) {
				this.storage.setItem(key, val);
			},
			_setStorages:function(key, obj) {
				var l = JSON.stringify(obj);
				this.storage.setItem(key, l);
			},
			//\u83b7\u53d6\u6570\u636e\uff0c\u4f20\u5165\u83b7\u53d6\u7684name
			getItem: function(key) {
				var data = this.storage.getItem(key);
				if(!!data){
					console.warn('\u5f53\u524dsession\u4e2d\u6ca1\u6709'+key+'\u8fd9\u4e2a\u53c2\u6570');
				}
				return JSON.parse(data);
			}
		}
		 return new StorageHandle(opts);
	});
