/**
* NetEase QuickLogin快速登陆，也可用于首页登陆模块
* @param {Boolean}bFromIndex
*		  是否是首页调用
*/

if (NetEase==undefined){
	var NetEase={};
}
NetEase.quickLoginTemplate = null;
NetEase.indexLoginTemplate = null;
var type163 = 0;
var typePopo = 1;
var type126 = 2;
var type188 = 3;
var typeVip =4;
var typeYeah =5;
//blog自动登录cookie，格式type;
var ckLoginInfoKey = "NEBLOG_LOGIN";
//自动登录cookie信息
var ckLoginInfo = {type:null, name:null, pass:null};
//var ckKeyFromType = "NEBLOG_LOGTP";
var ckPath = "/";
var ckDomain=DomainMap.cookieDomain;
var errInfo = ["用户名或密码不正确，请重新输入", "该网易博客用户名不存在", "超时退出或无权限访问，请重新登录"];

NetEase.QuickLogin = Class.create();
NetEase.QuickLogin.prototype = {
	initialize: function(presentShowId, serverName, bFromIndex){
		this.options = Object.extend({
			err:false,
			jsWindowManager:null
		}, arguments[3] || {});
		//全局变量
		this.presentShowId = presentShowId;
		this.serverName = serverName;
		this.bFromIndex = bFromIndex;		
		this.err = false;
		this.jsWindowManager = this.options.jsWindowManager;
		this.objUsername;
		this.objPassword;
		this.objSetCkCheck;
		this.frmLogin;
		this.divNotice;
		this.btn_login;
		this.btn_reg;
		this.curUserType = 0;
		this.noticeInit = "请输入用户名和密码登录";
		this.noticeAccount = "请输入网易通行证用户名";
		this.noticePassword = "请完整填写登录信息，密码不能为空";
		this.isPwdFromCk = false;
		this.pwdFromCk;
		this.pwdFromCkTrim;	
		this.strUsername;
		this.strPassword;
		this.qLoginZone = null;
		this._load();			
	},
	
	_load: function(){	
		//从cookie得到用户名，密码等。get Login info  from last login .
		getLoginCookie();
		
		this.curUserType = ckLoginInfo.type;
		//this.curUserType = Cookie.get(ckKeyFromType);
		if(this.curUserType==null){
			this.curUserType = type163;
		}else{
			this.curUserType = parseInt(this.curUserType);
		}
		if(!this.bFromIndex || this.presentShowId=="qIndexLoginDiv"){
			//快速登录
			if (NetEase.quickLoginTemplate == null) 
				NetEase.quickLoginTemplate = quicklogin_jst;
			
			var data={err:false};
			var result = NetEase.quickLoginTemplate;
			if(this.presentShowId){
				this.qLoginZone = this.jsWindowManager.createWindow(this.presentShowId, {
					className:'g_lay_com g_win_4 g_f_shw',width: 500, height:250,hideFlash:true,
					title:'登录网易博客', onTop:true,notKeepPos:true
				});			
				this.qLoginZone.panel.innerHTML = result;	
				this.qLoginZone.showWindow();
			}
		}else{
			//首页登录
			if (NetEase.indexLoginTemplate == null) 
				NetEase.indexLoginTemplate = indexlogin_jst;//createJSTAndParse("indexlogin_jst", indexlogin_jst);
			
			var data={err:false};
			var result = NetEase.indexLoginTemplate;//.process(data);
			$("outLoginDiv").innerHTML = result;	
		}
		
		this.frmLogin = $("frmLogin");
		this.divNotice = $("notice_bar");
		this.objUsername = $("in_username");
		this.objPassword = $("in_password");
		this.objSetCkCheck = $("setCookieCheck");
		
		if(document.all) {
			//this.objUsername.attachEvent("onfocus", this.checkUsername.bind(this));
			this.objUsername.attachEvent("onblur", this.checkUsername.bind(this));
			//this.objUsername.attachEvent("onkeyup", this.checkUsername.bind(this));
			this.objPassword.attachEvent("onfocus", this.fnPassOnFocus.bind(this));
			this.objPassword.attachEvent("onblur", this.checkPassword.bind(this));
			//this.objPassword.attachEvent("onkeyup", this.checkPassword.bind(this));
			if(!this.bFromIndex){
				for(var i=0; i<6; i++){
					if ($("tab_a_"+i))
						$("tab_a_"+i).attachEvent("onclick", this.selectUserType.bind(this, i));
					else
					    $("tab_"+i).attachEvent("onclick", this.selectUserType.bind(this, i));
				}
			}
			$("qLoginButt").attachEvent("onclick", this.dologin.bind(this));
			this.frmLogin.attachEvent("onkeypress", this.frmDologinIE.bind(this));
			this.objSetCkCheck.attachEvent("onclick", this.changeCookieCheck.bind(this));
		}
		else {
			//this.objUsername.addEventListener("focus", this.checkUsername.bind(this), true);
			this.objUsername.addEventListener("blur", this.checkUsername.bind(this), true);
			//this.objUsername.addEventListener("keyup", this.checkUsername.bind(this), true);
			this.objPassword.addEventListener("focus", this.fnPassOnFocus.bind(this), true);
			this.objPassword.addEventListener("blur", this.checkPassword.bind(this), true);
			//this.objPassword.addEventListener("keyup", this.checkPassword.bind(this), true);
//			this.btn_reg.addEventListener("onmouseout", this.regBtnOut.bind(this), true);	
				
			if(!this.bFromIndex){
				for(var i=0; i<6; i++){
					if ($("tab_a_"+i))
						$("tab_a_"+i).onclick = this.selectUserType.bind(this, i);
					else
						$("tab_"+i).onclick = this.selectUserType.bind(this, i);
				}
			}
			$("qLoginButt").onclick = this.dologin.bind(this);
			this.frmLogin.onkeypress = this.frmDologin.bind(this);	
			this.objSetCkCheck.onclick = this.changeCookieCheck.bind(this);			
		}
		if (this.bFromIndex)
		   showLoginType(this.curUserType);	
		this.selectUserType(this.curUserType);
		
	},
	
	showWindow: function(target){
		if(target){
			this.loginTarget = target;
		}
		this.qLoginZone.showWindow();
	},
	
	frmDologinIE: function(){
		if(event.keyCode==13) 
			this.dologin();
	},
	frmDologin: function(event){
		if(event.keyCode==13) 
			this.dologin();
	},
	
	changeCookieCheck:function(){
		if(!this.objSetCkCheck.checked){	
			//get Login type from last login 
			//var userNameInit = getUserNameInit(this.curUserType);			
			clearLoginCookie();			
		}
	},
	
	checkUsername: function(){	
		//divNotice.innerHTML = noticeAccount;
		//return true;	

		var strUsername = this.objUsername.value;
		//var reUsername = /^[A-Za-z0-9-][A-Za-z0-9\._-]{1,17}$/g;
		if (strUsername.length>0){		
			this.divNotice.innerHTML = this.noticeAccount;
		} else {
			this.divNotice.innerHTML = this.noticeInit;
		}	
		return true;
	},
	
	//不响应onfocus事件，只做从cookie获得密码
	checkPasswordFocus: function(){
		var strPassword = this.objPassword.value;
		if(strPassword==""){
			var strUsername = this.objUsername.value + getNameSuffix(this.curUserType);
			strPassword = ckLoginInfo.pass;
			if(null != strPassword){
				this.pwdFromCk = strPassword;
				this.pwdFromCkTrim = strPassword.substring(0,11);			
				this.isPwdFromCk = true;
				this.objPassword.value = strPassword.substring(0,11);
			}
		}
		this.checkPassword();
	},
	
	//响应密码输入框的onfocus事件
	fnPassOnFocus: function(){
		this.objPassword.select();
		this.checkPassword();
	},
	
	checkPassword: function(){
		var strPassword = this.objPassword.value;
		if(null==strPassword || strPassword==""){
			this.isPwdFromCk = false;
		}
		
		var rePassword = /^[\s]*$/g;
			if (strPassword.match(rePassword) != null){
				this.divNotice.innerHTML = this.noticePassword;
				//this.objPassword.style.backgroundColor = "#fff";
				return false;
			} else {
				this.divNotice.innerHTML = this.noticeInit;
				//this.objPassword.style.backgroundColor = "#fff";
				return true;
			}
	},
	
	dologin: function(){
		if(this.checkUsername() && this.checkPassword()) { //顺利登录
			this.divNotice.innerHTML = "正在登录，请稍候...";
			this.objUsername.disabled=true;
			this.objPassword.disabled=true;
			
			if(document.all){
				this.objUsername.detachEvent("onblur", this.checkUsername);
				this.objPassword.detachEvent("onfocus", this.checkPassword);
				this.objPassword.detachEvent("onblur", this.checkPassword);
		
				$("frmLogin").detachEvent("onkeypress", this.frmDologinIE);	
				$("qLoginButt").detachEvent("onclick", this.dologin);
				this.objSetCkCheck.detachEvent("onclick", this.changeCookieCheck);				
			}else {
				this.objUsername.removeEventListener("blur", this.checkUsername, true);
				this.objPassword.removeEventListener("focus", this.checkPassword, true);
				this.objPassword.removeEventListener("blur", this.checkPassword, true);
			}
			
			var strPassword = this.objPassword.value;
			var strPwdOld;
			if(!this.isPwdFromCk || strPassword != this.pwdFromCkTrim){
				if(this.curUserType==type163 || this.curUserType==typeVip)
					strPassword = this.pwd_js_string(strPassword);
				if(this.curUserType==type163  || this.curUserType==typeVip){
					strPassword = strPassword.substring(0,16);
				}else if(this.curUserType==typePopo){
					strPassword = strPassword.substring(0,21);
				}			
				strPwdOld = strPassword;
				strPassword = hex_md5(strPassword);		
			}else{
				//get from cookie
				strPassword = this.pwdFromCk;
				strPwdOld = strPassword;
			}
			
			var strUsername = Trim(this.objUsername.value);	
			var strUsernameOld = strUsername;
			strUsername += getNameSuffix(this.curUserType);
			
			if(this.curUserType == type126 || this.curUserType == type188 || this.curUserType == typeYeah){				
				strPassword = strPwdOld;//.replace(/#/g,"%23");			
			}
			
			if(this.objSetCkCheck.checked){
				//username
				clearLoginCookie();
				
				setLoginCookie(1, strUsernameOld);
				setLoginCookie(2, strPassword);
			}else{
				clearLoginCookie();
			}			
			
			//save cookie for login type
			setLoginCookie(0, this.curUserType);
			
			this.strUsername = strUsername;
			this.strPassword = strPassword;

			if(this.bFromIndex || this.presentShowId=="qIndexLoginDiv"){
				loginFromIndex(strUsername, strPassword);
			}else{
				UserBean.check(strUsername, strPassword, this.dologinCb.bind(this));	
			}		
		}
		return false;
	},
	
	dologinCb: function(b){
		if(b!=null){
			if (b=="not reg!!") {
					window.open("http://blog.163.com/passportIn.do?in_username="+this.strUsername+"&in_password="+this.strPassword);
			} else {
				//modified by xcc, 用户可以指定loginTarget
				if (this.loginTarget==null){
					if ( $("$_oppoPageUrlForLogin")&&(UD.hostName == this.strUsername) ){
					  if (UD.hostPath =="") //如果是个性化域名
					     this.loginTarget = "http://"+DomainMap.getParentDomain(this.strUsername)+$("$_oppoPageUrlForLogin").value;
					     //this.loginTarget = $("$_oppoPageUrlForLogin").value;
					  else 
					     this.loginTarget = $("$_oppoPageUrlForLogin").value;
					}
					else
						this.loginTarget=window.location;
				} 
				
				//location.href = UD.hostPath + "/loginGate.do?username="+this.strUsername+"&target=http://"+DomainMap.getParentDomain(this.strUsername)+this.loginTarget;
				location.href =  "http://blog.163.com/loginGate.do?username="+this.strUsername+"&target="+encodeURIComponent(this.loginTarget);
			}
		}else{
			//this.objUsername.value = "";
			this.objPassword.value = "";
			this.objUsername.disabled=false;
			this.objPassword.disabled=false;
			this.divNotice.innerHTML = "<span class='clr03'>用户名或密码不正确，请重新输入。</span>";
			$("in_username").focus();
		}
		
		return false;
	},
	
	pwd_js_string: function(s){
		return String(s).replace(/\\/g, "\\\\").replace(/'/g, "\\\'").replace(/"/g, "\\\"");
	},
	
	updateSuffix: function(suffix){
		var e = $("account_suffix");
		e.innerHTML = suffix;
	},
		
	selectUserType: function(type){
		if(!this.bFromIndex){
			for(var i=0; i<6; i++){
				if($("tab_"+i)){
					if(type == i){
						if (!this.bFromIndex)
							$("tab_"+i).className="g_f_hov selected";
					}else{
						if (!this.bFromIndex)
							$("tab_"+i).className="g_f_hov";
					}
				}
			}
		}    
		     
		var regAdd = $("reg_add");
		var getPassAdd = $("getPass_add");
		
		var innerLoginDiv = $("innerLoginDiv");
		var sbStr = "bg_taglog";
		if(!this.bFromIndex){
			sbStr = "bg_menu";
		}
		if (!this.bFromIndex&&innerLoginDiv)
		   innerLoginDiv.style.backgroundImage = "url(http://b.bst.126.net/style/common/index/"+ sbStr + type +".gif)";
		
		if (this.bFromIndex){	
			this.noticeInit = "已开通网易博客的＂"+getShowLogName(type)+"＂用户直接登录";
			this.noticeAccount = "请输入"+getShowLogName(type)+"用户名";	
		}
		else{
			this.noticeInit = "请输入"+getShowLogName(type)+"用户名和密码登录";
			this.noticeAccount = "请输入"+getShowLogName(type)+"用户名";	
		}	
		if(type == type163){
			this.updateSuffix("@163.com");
			regAdd.href="http://reg.163.com/reg/reg0.jsp?url=http://blog.163.com/ntesRegBlank.html";
			getPassAdd.setAttribute("href","http://reg.163.com/RecoverPasswd1.shtml");
		}else if(type ==  type126){
			this.updateSuffix("@126.com");	
			getPassAdd.setAttribute("href","http://reg.126.com/recoverpass/");
		}else if(type ==  typePopo){
			this.updateSuffix(".popo&nbsp;&nbsp;&nbsp;");	
			regAdd.href="http://reg.popo.163.com/";
			getPassAdd.setAttribute("href","http://popo.163.com/prtpass/getpass.sp");
			getPassAdd.href="http://popo.163.com/prtpass/getpass.sp";
		}else if(type ==  type188){
			this.updateSuffix("@188.com");
			regAdd.href="http://reg.mail.188.com/index.jsp?from=";
			getPassAdd.setAttribute("href","http://reg.mail.188.com/rstpsw/rpsel.htm");
		}else if(type == typeVip){
			this.updateSuffix("@vip.163.com");
			regAdd.href="http://vip.163.com/register.m";
			getPassAdd.setAttribute("href","http://vip.163.com/PwdRepair/index.htm");
		}
		else if(type == typeYeah){
			this.updateSuffix("@yeah.net");
			regAdd.href="http://reg.mail.yeah.net/reg/reg1.jsp";
			getPassAdd.setAttribute("href","http://reg.mail.yeah.net/reg/recoverpass/");
		}
		$("reg_add").innerHTML="注册"+getShowRegName(type)+" -->";
		
		this.curUserType = type;
		//填充用户名和密码
		this.objUsername.value ="";
		this.objPassword.value ="";
		var userNameInit = ckLoginInfo.name;
		
		if(userNameInit && ckLoginInfo.type==type){
			this.objUsername.value = userNameInit;
			this.checkPasswordFocus();
			this.objSetCkCheck.checked = true;
			this.noticeAccount = "请点击登录按钮";
			this.noticeInit = "请点击登录按钮";
		}else{
			this.objSetCkCheck.checked = false;
			//$("in_username").focus();
		}		
		
		//处理出错信息
		var urlStr = window.location.href;
		var i = urlStr.indexOf("err=");
		if(i != -1){
			var errStr = urlStr.charAt(i+4);
			if(errStr=="1" || errStr=="2" || errStr=="3"|| errStr=="4"){
				var n = parseInt(errStr);
				if (n>3)n=1;
				this.noticeInit = this.noticeAccount = "<span class='cr'>"+errInfo[n-1]+"</span>";
			}
		}
		this.checkUsername();	
		if ($("in_username")) try{Field.activate("in_username");}catch(e){};
		
		if (this.bFromIndex) showLoginType(type);	
		return false;
	}
	
}

function closeLogin(){
	$("loginNewDiv").style.display="none";
}
	

function getLogStr(type){
	if(type==type163)
		return  "163";
	else if(type==typePopo)
		return  "POPO";
	else if(type==type126)
		return  "126";
	else if(type==type188)
		return  "188";		
	else if(type==typeVip)
		return  "VIP";	
	else if(type==typeYeah)
		return  "YEAH";		
}

function getNameSuffix(type){
	if(type==type163)
		return  "";
	else if(type==typePopo)
		return  ".popo";
	else if(type==type126)
		return  "@126";
	else if(type==type188)
		return  "@188";		
	else if(type==typeVip)
		return  ".vip";	
	else if(type==typeYeah)
		return  "@yeah";		
}

function getShowLogName(type){
	if(type==type163)
		return  "网易通行证";
	else if(type==typePopo)
		return  "POPO";
	else if(type==type126)
		return  "126邮箱";
	else if(type==type188)
		return  "188邮箱";		
	else if(type==typeVip)
		return  "VIP邮箱";	
    else if(type==typeYeah)
		return  "YEAH邮箱";				
}

function getShowRegName(type){
	if(type==type163)
		return  "通行证";
	else if(type==typePopo)
		return  "POPO";
	else if(type==type126)
		return  "126邮箱";
	else if(type==type188)
		return  "188邮箱";		
	else if(type==typeVip)
		return  "VIP邮箱";	
    else if(type==typeYeah)
		return  "YEAH邮箱";				
}

//从cookie得到登录类型、用户名、密码
function getLoginCookie(){
	var a;
	var v = Cookie.get(ckLoginInfoKey);
	if(v){
		a = v.split("|");
		var type = null;
		if(a[0])
			ckLoginInfo.type = parseInt(a[0]);
		if(ckLoginInfo.type == null || ckLoginInfo.type == undefined || ckLoginInfo.type<0 || ckLoginInfo.type>4){
			ckLoginInfo.type = null;
			//类型取不到，用户名和密码为空
			return;
		}
		
		if(a[1] != null && a[1] != undefined && a[1] != "null" && a[2] != null && a[2] != undefined){
			ckLoginInfo.name = a[1]; 
			//取密码，从第二个|开始
			var pos = v.indexOf('|',2);
			ckLoginInfo.pass = v.substring(pos+1);
		}
	}
}

//设置cookie登录类型(which=0)、用户名(which=1)、密码(which=2)
function setLoginCookie(which, value){
	getLoginCookie();
	if(which==0)
		ckLoginInfo.type = value;
	else if(which==1)
		ckLoginInfo.name = value;
	else if(which==2)
		ckLoginInfo.pass = value;
		
	Cookie.clear(ckLoginInfoKey, ckPath);
	//cookie value将以ascii编码传输，类似url encoding,服务器端需要decode
	Cookie.set(ckLoginInfoKey, ckLoginInfo.type + "|" + ckLoginInfo.name + "|" + ckLoginInfo.pass, 30, ckPath, ckDomain);			
}

//清除ckLoginInfoKey的cookie，同时也清除ckLoginInfo的name和pass，但保留type
function clearLoginCookie(){
	ckLoginInfo.name = null;
	ckLoginInfo.pass = null;
	Cookie.clear(ckLoginInfoKey, ckPath);
	if(ckLoginInfo.type != null && ckLoginInfo.type != undefined && ckLoginInfo.type != "null")
		Cookie.set(ckLoginInfoKey, ckLoginInfo.type, 30, ckPath, ckDomain);			
}

var Cookie = {
	set : function(name, value, expirationInDays, path, domain) {
		var cookie = escape(name) + "=" + escape(value);
		if (expirationInDays) {
			var date = new Date();
			date.setDate(date.getDate() + expirationInDays);
			cookie += "; expires=" + date.toGMTString();
		} 

		if (path) {
			cookie += ";path=" + path;
		}
		if (domain) {
			cookie += ";domain=" + domain;
		}
		
		document.cookie = cookie;

		if (value && (expirationInDays == undefined || expirationInDays > 0) && !this.get(name)) {
			return false;
		}
	},

	clear : function(name, path) {
		this.set(name, "", -1, path, ckDomain);
	},
	
	get : function(name) {
		var pattern = "(^|;)\\s*" + escape(name) + "=([^;]+)";
		var m = document.cookie.match(pattern);
		if (m && m[2]) {			
			return unescape(m[2]);
		}else{ 
			return null;
		}
	}
}   

        
//快速登录
var quicklogin_jst = 
'<div>'+
'   <form name="frmLogin"  id="frmLogin"  method="post">'+
'						<div class="g_tab_btn03">'+
'						  <div class="g_f_hov"  id="tab_0">网易通行证</div>'+
'							<div class="g_f_hov" id="tab_2">126邮箱</div>'+
'							<div class="g_f_hov" id="tab_1">POPO</div>'+
'							<div class="g_f_hov" id="tab_3">188邮箱</div>'+
'							<div class="g_f_hov" id="tab_4">VIP邮箱</div>'+
'							<div class="g_f_hov" id="tab_5">YEAH邮箱</div>'+
'						</div>'+
'						<!-- 通行证 -->'+
'						<div class="case">'+
'							<div class="mgntxt clr02" id="notice_bar" style="display-left:0px;"></div>'+
'						    <div class="input"><label for="text0">用户名：</label><input class="g_h_ipt" type="text" name="in_username" id="in_username"/>&nbsp;<span id="account_suffix">@163.com</span></div>'+
'							<div class="input"><label for="text1">密　码：</label><input class="g_h_ipt" type="password" name="in_password" id="in_password"/>&nbsp;<a class="a_a d_d" href="http://reg.163.com/RecoverPasswd1.shtml" target="_blank" id="getPass_add">忘记密码了?</a></div>'+
'							<div class="btnbar"><input type="checkbox"  name="setCookieCheck" id="setCookieCheck" ><label for="setCookieCheck">自动登录</label>&nbsp;<input type="button" class="btncm btnok" value="登录网易博客"  id="qLoginButt"/></div>'+
'					    </div>'+
'						<div class="bottom">'+
'						  <span>还没有网易博客?</span>&nbsp;<input type="button" class="btncm btncc" value="立即注册" onclick="window.open(\'http://reg.163.com/reg/reg0.jsp?url=http://blog.163.com/ntesRegBlank.html\');" />'+
'						</div>'+
'   </form><span id="reg_add" style="display:none;" href="#">ww</span>'+
'</div>';

function UserBean() { }
UserBean.clearSession = function(callback){    DWREngine._execute('/dwr', 'UserBean', 'clearSession', false, callback);}
UserBean.check = function(p0, p1, callback) {DWREngine._execute('/dwr', 'UserBean', 'check', p0, p1, false, false, false, callback);}
UserBean.getProvinceAndCity = function(callback) {	DWREngine._execute('/dwr', 'UserBean', 'getProvinceAndCity', false, false, callback);}  	          


//将忘记密码了这个改为a标签
/****************************** 以上内容从博客 js/netease/QuickLogin.js 同步过来, 以下为博客活动专用代码***********************************************************************/
NetEase.QuickLoginOther  = NetEase.QuickLogin
NetEase.QuickLoginOther.prototype.showWindow = function(){
		 var clientHeight = document.documentElement.clientHeight;
	    var scrollTop= document.documentElement.scrollTop ;
	    if (this!=top){
	    	try{scrollTop = top.document.documentElement.scrollTop;
	    	clientHeight = top.document.documentElement.clientHeight;}catch(e){}	
	    }
		var posTop = scrollTop + ( clientHeight- 400)/2;	
		if(posTop < 10)
			posTop = 10;	
		var left = (document.documentElement.clientWidth - 600)/2;
		if(left < 10)
			left = 10;	
		$("$_qLoginDiv").style.left =  left + "px";
		$("$_qLoginDiv").style.top =  posTop + "px";		
		$("$_qLoginDiv").style.display = "";
}

UserBean.check=function(p0,p1,callback){DWREngine._execute('/activities/dwr','UserBean','check',p0,p1,false,false,false,callback);}
function fnLoadInitOther(){
	new NetEase.QuickLoginOther(null, null, true,  {err:false});
}

