/**
 * @author caojj
 */
//--------------------面切换，如有特殊需要，单独覆盖处理------------------
try{NAVFUN}catch(ex){NAVFUN={}};

WONIUCOMMON = (function(){
	(function(){
		/**
		 * 返回字字符串的Unicode编码的长度
		 */
		String.prototype.uniLength = function() {
			return this.replace(/[^\x00-\xff]/g, '**').length;
		};
		
		/**
		 * 按Unicode编码取子字符串，原function uniSubstr (astr, s, len)
		 */
		String.prototype.uniSubstr = function(start, len) {
			var i = 0, ss = start, tempStr, returnStr = "", a;
			while (i < len) {
				tempStr = this.substr(ss, 1);
				if (tempStr == "") {
					break;
				}
				returnStr += tempStr;
				a = tempStr.uniLength();
				i = i + a; 
				ss += 1; 
			}
			return returnStr;	
		};
		/**
		 * 获取最大长度+".."格式的字符
		 * @param {Object} str
		 * @param {Object} len
		 */
		String.prototype.uniLeft = function(len, suffix) {
			if (!suffix) {
				suffix = "";
			}
			return this.uniLength()>len?this.uniSubstr(0, len-suffix.uniLength())+suffix:String(this);	//this.len 要> sufix.len
		};
	})();
	var $ = function(id) {
		return document.getElementById(id);
	};
	
	var Util = {
		getScript : function(name) {
			if (!this.script) {		
				var scripts = document.getElementsByTagName("script");			
				var reg = new RegExp(name||"woniuOfficialNav\.js");
				
				for (var i=0,len=scripts.length-1;i>=0 ;i-- ) {
					var script = scripts[i];
					var src = script.getAttribute("src");			
					if (src&&reg.test(src)) {
						this.script = script;
						break;
					}
				}
							
			}
			return this.script;
		},
		importCss : function() {
			var _link = document.createElement("link");
			_link.href = "http://resimage.woniu.com/comres/js/woniu/style/style.css";
			_link.rel = "stylesheet";
			_link.type = "text/css";
	
			var head = document.getElementsByTagName("head")[0];
			head.firstChild?head.insertBefore(_link,head.firstChild):head.appendChild(_link);
	
			if (this.cls) {
				var _link = document.createElement("link");
				_link.href = this.cls;
				_link.rel = "stylesheet";
				_link.type = "text/css";
				head.appendChild(_link);
			}
	
			delete _link;
		},
		getCookie : function(key) {
			var reg = new RegExp("(^| )"+key+"=([^;]*)(;|$)");
			var arr = document.cookie.match(reg);
			return arr==null? null : decodeURIComponent(arr[2]); //unescape(arr[2]);
		},
		setCookie : function(sName, sValue, oExpires, sPath, sDomain, bSecure){
			var sCookie = sName + "=" + encodeURIComponent(sValue);
			if (oExpires) {
				sCookie += "; expires=" + oExpires.toGMTString();
			}
			if (sPath) {
				sCookie += "; path=" + sPath;
			}
			if (sDomain) {
				sCookie += "; domain=" + sDomain;
			}
			if (bSecure) {
				sCookie += "; secure";
			}
			document.cookie = sCookie;		
		},
		getQuery : function(key) {
			var reg = new RegExp("[?&]+"+key+"=([^\?&]*)[?&]?");
			var ret = location.search.match(reg);
			return ret ? ret[1] : "";
		},
		scriptRequest : function(src,cb) {
			var script = document.createElement("script");
			script.type = "text/javascript";
			if (this.isIE) {		
				script.onreadystatechange = function() {
					if (script.readyState=="complete"||script.readyState=="loaded") {
						script.onreadystatechange = null;
						if(cb) {try{cb();}catch(e){}}
						script.parentNode.removeChild(script);
					}
				};
			} else {
				script.onload = function() {
					if(cb) {try{cb();}catch(e){}}
					script.parentNode.removeChild(script);
				};
			};
			script.src = src;
			document.getElementsByTagName("head")[0].appendChild(script);
	
			//return script;
		}
	};
	
	var Process = {
		
	};
	
	var isIE = /MSIE/i.test(navigator.userAgent);
		
	var loginDoms = NAVFUN&&NAVFUN.loginDoms? NAVFUN.loginDoms :  ["woniunav_login","woniunav_right.logout"];
	var logoutDoms = NAVFUN&&NAVFUN.logoutDoms? NAVFUN.logoutDoms : ["woniunav_logout","woniunav_right.login", "woniunav_right.reg"];
	var User = {},isLogin=false;
	var product, noFoot, cls, noCls, delay;

	function verifyIdentity() {
		var userInfo = {};	
		
		var D1XN_INFO = Util.getCookie("userInfoSNS");
		if (D1XN_INFO) {		
			var info = D1XN_INFO.split(/\+&&&&/g);
			var time = Util.getCookie("lastTime");
			
			userInfo = {
				lastTime : time ? time.split(",")[0] : null,
				userId : info[0],
				account : (info[1]),
				nickName : (info[2]),
				sex : (info[3])
			};
		};

		User = {
			sex : userInfo["sex"],
			nickName : userInfo["nickName"],
			account : userInfo["account"],
			userId : userInfo["userId"],
			userGame : Util.getCookie("userGame")
		};

	};
	
	function update() {
		var doms = loginDoms.concat(logoutDoms);
		for(var i=0;i<doms.length;i++) {
			$(doms[i]).style.display="none";
		}
		var showDom = [];
		
		if (isLogin) {
			showDom = loginDoms;			
		} else {
			showDom = logoutDoms;			
		}
		
		for(var i=0;i<showDom.length;i++) {
			$(showDom[i]).style.display="";
		}
		
		var paras = getParas();
		for(var i in Process) {
			Process[i].get(paras);
		}
	}
	
	function getParas() {
		return {
			product : product,
			noCls : noCls,
			delay : delay,
			
			User : User,
			isLogin : isLogin
		}
	}
	
	function refresh() {
//		debugger;
		//检测状态
		verifyIdentity();
		
		isLogin = User.nickName ? true : false;
		//更新界面
		update();
	}
	
	function init(){
		//...
		(function() {	//检测推广码	
			var PRMT = Util.getQuery("promotParam");
			if (PRMT) {
				Util.setCookie("PRMT",PRMT);
			}
		})();
		
		product = location.host.split(".")[0] ;//Util.getScript().getAttribute("product") || "index";
//		if(product=="aoa") {
//			if(location.pathname.indexOf("/aoahj/")>-1) {
//				product="aoahj";	//机甲世纪怀旧版
//			}
//		}
//		noCls = (Util.getScript().getAttribute("noCls") == "true" ? true : false);
		delay = false;//(Util.getScript().getAttribute("delay") == "true" ? true : false);
		
//		if(!noCls) {
//			Util.importCss("http://resimage.woniu.com/comres/js/woniu/styleNew/newTopStyle.css");
//		}
				
		if (delay) {
			isIE ? (function(){
				document.attachEvent("onreadystatechange", function(){
						if (document.readyState == "complete" || document.readyState == "loaded") {				
							refresh();
						}
				});
			}()) : document.addEventListener("DOMContentLoaded",function(){refresh();}, false);
		} else {
			refresh();
		}
	};
	
	return {
		$ : $,
		refresh : refresh,
		getUser : function() {
			return User;
		},
		setUser : function(user) {
			User = user;
		},
		isLogin : isLogin,
		Process : Process,
		Util : Util,
		
		init : init
	}
})();

WONIUCOMMON.NAVFUN = function(fun) {
	if(WONIUCOMMON.NAVFUN[fun]){
		WONIUCOMMON.NAVFUN[fun]();
	}
};
WONIUCOMMON.NAVFUN.viewMsg = function() {
	NAVFUN.viewMsg ? NAVFUN.viewMsg() :
//			location.assign("http://my.woniu.com/?menuCtrl=Fn_inbox");
			location.assign("http://www.woniu.com/personal/showSNSCommunity?app=model/message");
};

WONIUCOMMON.Process.basic = {
	initFlag : false,
	get : function(paras) {
		this.bindEvent();
		
		var service = location.href.indexOf('service=')<0 ? "?service=" + location.href : "";
		WONIUCOMMON.$("woniunav_right.login").href = "http://www.woniu.com/account/login.do"+service;		
		
		if(!paras.isLogin) return;
		
		this.fillBasicInfo(paras);
	},
	fillBasicInfo : function(infos) {
		var User = infos["User"];
		WONIUCOMMON.$("woniunav_login.nickName").innerHTML = User["nickName"].replace(/</g,"&lt;").replace(/>/g,"&gt;").uniLeft(10,"..");
		WONIUCOMMON.$("woniunav_login.nickName").title = User["nickName"];
		WONIUCOMMON.$("woniunav_login.zone").href = "http://hi.woniu.com/"+User["userId"]+".home";
	},
	bindEvent : function() {
		if(this.initFlag) return;
		
		var _outTimer = null;
		var _hideFun = this.hideQuickList;
		WONIUCOMMON.$("woniunav_listBtn").onmouseover = WONIUCOMMON.$("woniunav_listBtn").onclick = function() {
			if (_outTimer) {clearTimeout(_outTimer);_outTimer=null;};
			setTimeout(function(){
				document.getElementById("woniunav_list").style.display="";
			},50);
		};
		
		WONIUCOMMON.$("woniunav_listBtn").onmouseout = function() {
				_outTimer = setTimeout(_hideFun,500);
		};
		
		if (window.attachEvent) {
			document.attachEvent("onclick",_hideFun);
		} else {
			window.addEventListener("click",_hideFun,false);
		}
		
		this.initFlag = true;
	},
	hideQuickList : function() {
		document.getElementById("woniunav_list").style.display="none";
	}
};

//填充当前栏目
WONIUCOMMON.Process.product = {
	get : function(paras) {
		if (this.current) {
			WONIUCOMMON.$("woniunav_game."+this.current).className = "WN_ALLNAV_leftMenuOBtn";
		}
		
		this.fillProduct(paras["product"]);
				
		this.fillReg(paras["product"]);
		
		this.fillCharge(paras["product"]);
		
		this.fillLogin(paras["product"]);
	},
	fillProduct : function(product) {
		var dom = WONIUCOMMON.$("woniunav_game."+product);
		if (dom) {
			dom.className = "WN_ALLNAV_leftMenuOBtn WN_ALLNAV_leftMenuOBtnSe";
			this.current = product;
		}
	},
	fillReg : function(product) {
		var dom = WONIUCOMMON.$("woniunav_right.reg");
		var game = WONIUCOMMON.Process.game.gameDict[product];
		if(!game) return;
		
		var regUrl = WONIUCOMMON.Process.game.woniuGameList[game]["reg"];
		if (dom&&regUrl) {
			dom.href = regUrl;
		}
	},
	fillCharge : function(product) {
		var dom = WONIUCOMMON.$("woniunav_right.charge");
		var game = WONIUCOMMON.Process.game.gameDict[product];
		if(!game) return;
		
		var chargeUrl = WONIUCOMMON.Process.game.woniuGameList[game]["charge"];
		if (dom&&chargeUrl) {
			dom.href = chargeUrl;
		}
	},
	fillLogin : function(product) {
		var dom = WONIUCOMMON.$("woniunav_right.login");
		var game = WONIUCOMMON.Process.game.gameDict[product];
		if(!game) return;
		
		var logUrl = WONIUCOMMON.Process.game.woniuGameList[game]["log"];
		if (dom&&logUrl) {
			dom.href = logUrl;
		}		
	}
};

//公会
WONIUCOMMON.Process.guild = {
	get:function(paras) {
		return;
		if(!paras.isLogin) return;
		
		var guild = this.guild = WONIUCOMMON.Util.getCookie("GI_"+paras.User["userId"]);
		if (guild&&guild!=",") {
			var tmp = guild.split(",");
			guild = {
				"guildDomain":tmp[0],
				"guildName":tmp[1]
			}
		}
		(guild) ? this.fillGuild(guild) : WONIUCOMMON.Util.scriptRequest("http://www.woniu.com/newuser/guild.do?account="+paras.User["account"]+"&jsback=WONIUCOMMON.Process.guild.fillGuild"+"&t="+(new Date().getTime()));
	},
	fillGuild : function(guild) {
		if (!guild["guildDomain"]||!guild["guildName"]) {
			return;
		};

		this.Guild = guild;
		var guildBtn = WONIUCOMMON.$("woniunav_login.guild");
		guildBtn.href = "http://gh.woniu.com/"+guild["guildDomain"];

		guildBtn.innerHTML="我的公会";

		WONIUCOMMON.Util.setCookie("GI_"+WONIUCOMMON.getUser()["userId"],[guild["guildDomain"],guild["guildName"]].join(","),null,"/","woniu.com");
	}
};

WONIUCOMMON.Process.msg = {
	get:function(paras) {
//		return;
		if(!paras.isLogin) return;
		
		WONIUCOMMON.Util.scriptRequest("http://www.woniu.com/newuser/newmessage.do?m=jsQuery&jsback=WONIUCOMMON.Process.msg.fillMsgInfo&userId="+paras.User.userId+"&t="+(new Date().getTime()));
	},
	fillMsgInfo : function(msgs) {
		var n=0;
		if (msgs) {
			for(var i in msgs){
				n += parseInt(Number(msgs[i]));
			}
		}

		var dom = WONIUCOMMON.$("woniunav_login.msg");
		dom.innerHTML = "(0)".replace("0",n);
		dom.className = n>0 ? "WN_userMsg_Se" : "WN_userMsg";
		
		if(window.fillMsgInfo) {
			window.fillMsgInfo(msgs);
		}
	}
};

WONIUCOMMON.Process.game = {
	gameDict : {"9yin":10,tz:7,dg:12,aoa:13,"5jq":4,vc:1,hero:9,"aoahj":3},
	woniuGameList:{
		10:{name:'九阴真经',url:'http://9yin.woniu.com/',clubId:"http://9yin.woniu.com/bbs/"}, 
		7:{name:'天子',url:'http://tz.woniu.com/',clubId:393,reg:'http://act.woniu.com/reg/tz/reg.html?fromurl=GW.TZ.0.0.0',charge:'http://res.woniu.com/imprest/imprest_main.html?gameId=7'}, 
		12:{name:'帝国文明',url:'http://dg.woniu.com/',clubId:679}, 
		3:{name:'机甲世纪',url:'http://aoa.woniu.com/'},
		6:{name:'机甲世纪Ⅱ',url:'http://aoa.woniu.com/',clubId:703},
		13:{name:'机甲世纪革新版',url:'http://aoa.woniu.com/',clubId:703},
		4:{name:'舞街区',url:'http://5jq.woniu.com/',clubId:215,reg:'http://act.woniu.com/reg/5jq/reg.html?fromurl=GW.5JQ.0.0.0',charge:'http://res.woniu.com/imprest/imprest_main.html?gameId=4'},
		1:{name:'航海世纪',url:'http://vc.woniu.com/',clubId:183,reg:'http://act.woniu.com/reg/vc/reg.html?fromurl=GW.VC.0.0.0',charge:'http://res.woniu.com/imprest/imprest_main.html?gameId=1'},
		9:{name:'英雄之城',url:'http://hero.woniu.com/',clubId:524,charge:'http://res.woniu.com/imprest/imprest_main.html?gameId=9',reg:'http://hero.woniu.com/reg.html?fromurl=GW.HO.0.0.0',log:'http://hero.woniu.com/login.html'}
	},
	get:function(paras) {
		if(!paras.isLogin) return;

		var game = this.game = this.getGame(paras.product);	//paras.User.userGame;		//改为以当前游戏为准
		if (game && game > -1) {
			var gameName = this.woniuGameList[game] ? this.woniuGameList[game]["name"] : null;
		}
		
		if (gameName) {	//如果不是官方游戏
			this.fillUserGame(gameName);			
		}

	},
	
	fillUserGame : function(gameName) {
		//主打游戏
//		var dom = WONIUCOMMON.$("woniunav_myGame");
//		dom.innerHTML =  gameName;
//		var href = this.getHref();
//		href ? dom.href = href : dom.removeAttribute("href");
		
		//主打游戏对应论坛
		var doms = ["woniunav_login.club","woniunav_logout.club"];		
		href = this.getClub('clubId');
		for (var i = 0; i < doms.length; i++) {
			var dom = WONIUCOMMON.$(doms[i]);
			href ? dom.href = href : dom.removeAttribute("href");
		}
	},
	getHref : function() {
		var url = "";
		var game = this.game;
		if (game && game > -1) {
			url = this.woniuGameList[game] ? this.woniuGameList[game]["url"] : null;
		}
		return url;
	},
	getClub : function() {		//获取主打游戏对应的论坛链接
		var url = "";
		var game = this.game;
		if (game && game > -1) {
			url = this.woniuGameList[game] ? this.woniuGameList[game]["clubId"] : null;
		}
		return isNaN(url)?url:"http://club.woniu.com/thread.php?fid="+url;
	},
	getGame : function(productName) {
		return this["gameDict"][productName] || "";
	}
};

WONIUCOMMON.init();
