var g_Blog_Domain = top.g_NewBlog_Domain;
var msgLife =1000;
var lastModule=null;
var cateLength = 10;
var cateTime = null;
var ButtonIdList=["categoryList","relatedInfo","blogList","blogEditor","blogReader"];
var ImgButtonsIdList=["imgButton2","imgButton3","imgButton4","imgButton5","imgButton6","imgButton7","imgButton8"];
var cssIndex = top.g_StyleID;
var uin = top.g_iUin;
var staticFlag = 23;
var historyList=[];
var historyOffset=-1;
var commentPageSize = 15;
var itemArray;
var blogListKey = 23;
var targetTop=0;
var lastTop = 0;
var toScroll = 0;
var currentPage=1;
var currentBlogId=null;
var initCategory = false;
var signPageSize = (top.QZoneVersion == "4.0" && top.zoneMode != "qzone")?10:((uin==top.g_iLoginUin && top.g_iLoginUin>10000)?5:6);

function blogshowModule(m){
	if (lastModule && document.getElementById(lastModule))
		document.getElementById(lastModule).style.display="none";
	document.getElementById(m).style.display="";lastModule=m;
	closeEditor();
	try{
		if(m!="blogReader")
			document.getElementById("blogContent").innerHTML="";
		else
			document.getElementById("comment_editor").style.display="none";

		if(m=="blogEditor"){
			document.getElementById("blogReader").style.display="none";
			document.getElementById("comment_editor").style.display="none";
		}
	}
	catch(e){}
}

function showModule(m){
	if (lastModule) document.getElementById(lastModule).style.display="none";
	document.getElementById(m).style.display="";lastModule=m;
	var showComment={"blogReader":1,"signReader":1}
	try{if(m!="blogReader") document.getElementById("blogContent").innerHTML="";}catch(e){}
	document.getElementById("comment_editor").style.display = 'none';//(showComment[m])?"":"none"
}


function getRelatedInfo(){//获取最近访客
	if (!top.g_XDoc["relatedInfo"]) window.setTimeout("doGetRelatedInfo()",1000); else getRelatedInfoSucc();
}

function doGetRelatedInfo(){
		var url = "http://"+top.g_Main_Domain+"/fcg-bin/cgi_visitor_related.fcg?uin="+uin;
	top.loadXMLAsync("relatedInfo",url,getRelatedInfoSucc,showError);
}

function getRelatedInfoSucc(){
	if(!(window.isHandlersBinded===undefined))insertTpl(["leftNav"]);//INSERT
	var x = top.g_XDoc["relatedInfo"];
	var nodes=x.selectNodes("//entry");
	for(var i=0;i<nodes.length;i++){
		with(nodes[i]){
			setAttribute("name",selectSingleNode("name").firstChild.nodeValue.toInnerHTML());
		}
	}
	fillDIV("relatedInfo",x);
	try{_qznc.init(document.getElementById("relatedInfo"));}catch(err){}
}


function getOwnerSign(){//获取签名档
	top.ownerSign = "";
		var url = "http://"+top.g_NewBlog_Domain+"/cgi-bin/blog/blog_signature.cgi?uin="+uin;
	top.loadXMLAsync("sign_"+uin,url,setOwnerSign,function(){})
}

function setOwnerSign(){
	var x=top.g_XDoc["sign_"+uin]
	if(x.lastChild.tagName=="error"){
		top.ownerSign = "";
		top.g_XDoc["sign_"+uin]=null;return 
	}
		if(!top.g_XDoc["sign_"+uin].selectSingleNode("signature").firstChild)
			top.ownerSign = "";
		else
			top.ownerSign = ubbReplace(top.g_XDoc["sign_"+uin].selectSingleNode("signature").firstChild.nodeValue,"face anchor image email sign glow_limit font");
}

//缩放导航菜单
function mlineChange(action){
	document.getElementById("mode_tall").style.display="";
	with(document.getElementById("pageSplit"))
	if(action=="hide"||(!action&&className=="mlineon")){
		className="mlineoff";
		previousSibling.style.display="none";
	}else{
		className="mlineon";
		previousSibling.style.display="block";
		try{
			if(document.getElementById("blogReader") && document.getElementById("blogReader").style.display!="none" && typeof sendPV == "function")
				sendPV("blogshowcate")//临时增加的阅读日志是点击分栏的次数统计
		}catch(e){}
	}
	reSizeWidth();
	resizeCategory();
}

//重新计算样式宽度
function reSizeWidth(id){ 
	try{
		var pS=document.getElementById("pageSplit")
		with(document.styleSheets[1]){
			if (uin==top.g_iLoginUin && top.g_iLoginUin>10000){
				(isIE?rules:cssRules)[4].style.width=(pS.className=="mlineon")?"270px":"395px";
				(isIE?rules:cssRules)[5].style.width=(pS.className=="mlineon")?"330px":"465px";
			}
			 else{
			 	(isIE?rules:cssRules)[4].style.width=(pS.className=="mlineon")?"343px":"480px";
			 	(isIE?rules:cssRules)[5].style.width=(pS.className=="mlineon")?"423px":"560px";
			 }	 
			 (isIE?rules:cssRules)[6].style.width=(pS.className=="mlineon")?"510px":"640px";
			 //(isIE?rules:cssRules)[7].style.width=(pS.className=="mlineon")?"539px":"669px";
		}
	}catch(e){}
}

function resizeCategory(){
	var cItem = document.getElementById("categoryItem");
	if (!cItem) {return;}
	var listLength = cateLength;
	var listPixel = listLength * 20;
	if (cItem.scrollHeight > (listPixel+2)){
		cItem.style.overflow = "hidden";
		cItem.style.height = listPixel + "px";
		document.getElementById("arrowDiv1").style.display="";
	}
	else document.getElementById("arrowDiv1").style.display="none";
	initCategory = true;
}

function cateMove(flag){	
	var cItem=document.getElementById("categoryItem");
	targetTop += flag*20*cateLength;
	clearTimeout(cateTime);
	toScroll = targetTop - lastTop;
	setcateTop();	
}

function setcateTop(){
	cateTime = window.setTimeout("setcateTop()",10);
	var cItem=document.getElementById("categoryItem");
	var percentTop=0.1*toScroll;
	if (percentTop>0) percentTop=Math.ceil(percentTop); else percentTop=Math.floor(percentTop);
	cItem.scrollTop = parseInt(cItem.scrollTop,10) + percentTop;
	lastTop = lastTop + percentTop;
	toScroll -= percentTop;
	if (targetTop == lastTop) {
		//stop scroll
		if (targetTop<0) {lastTop = targetTop = 0;}
	    if (targetTop>parseInt(cItem.scrollTop,10)) {lastTop = targetTop = cItem.scrollTop;}
		clearTimeout(cateTime);
	};
}

function focusTop(id){try{document.getElementById(id).focus()}catch(e){}}

function showError(st,back){ //错误提示
	if(st) showOpratingMsg(st); else showOpratingMsg("您暂时无法连接到服务器,请您稍候再试...");
	if(back)
		opratingMsgTimeout = setTimeout("hideOpratingMsg();top.guideButton(1)",msgLife+500);
	else
		opratingMsgTimeout = setTimeout("hideOpratingMsg()",msgLife+500);
}

function setLoginStatus(){
	with(document.styleSheets["trueStyle"]){
		(isIE?rules:cssRules)[1].style.display=(uin==top.g_iLoginUin && top.g_iLoginUin>10000)?"":"none";
		(isIE?rules:cssRules)[2].style.display=top.g_iLoginUin>10000?"":"none";
		(isIE?rules:cssRules)[3].style.display=uin!=top.g_iLoginUin?"":"none";
	}
	if(top.setLoginStatus) top.setLoginStatus();
}

window.loginCallback = function(){
	if((/blog_mood\.html/).test(location.href))
		verifyCounter[0].change();
	else
		changeVerifyCode("verifycodeImg_comment");

	setLoginStatus();
	document.getElementById("comment_editor").style.display="none";
	hideLoginDiv();
	try{
		document.getElementById("hideVerifyCode").style.display="";
		document.getElementById("showAnon").style.display="none";
	}catch(e){};
}

function getSignLength(){//获取签名档长度
	if(!!top.g_XDoc["blogRoot"] && (top.g_XDoc["blogRoot"].emotionCount!==undefined)){
		top.g_XDoc["signLength"]=parseXML('<?xml version="1.0" encoding="gb2312"?><data><count>'+top.g_XDoc["blogRoot"].emotionCount+'</count></data>');
		getSignLengthSucc();
		return;
	}
	  var url="http://"+top.g_Emotion_Domain+"/cgi-bin/cgi_emotion_indexcount.cgi?uin=" + uin;
	  top.loadXMLAsync("signLength",url,getSignLengthSucc,showError);
}

function getSignLengthSucc(){
	if(!(window.isHandlersBinded===undefined))insertTpl(["leftNav"]);//INSERT
	var x = top.g_XDoc["signLength"];
	if(x.selectSingleNode("//count")){
		var n = x.selectSingleNode("//count")[isIE?"text":"textContent"]-0;
	 	if (!top.g_XDoc["aLoader"]) top.g_XDoc["aLoader"]=[];
  		if (!top.g_XDoc["aLoader"]["signLoader_totalMsg"]) top.g_XDoc["aLoader"]["signLoader_totalMsg"] = n;
		var tN = ((!n || n<0)?0:n);
  		window.signTotalMsg = tN;
  		try{signLoader.totalMsg = tN;}catch(e){}
		document.getElementById("signNum").innerHTML = "("+tN+")";
		try{
		 	document.getElementById("signCount").innerHTML = tN;
		 	document.getElementById("pageCount_sign").innerHTML = Math.ceil(tN/signPageSize);
		}catch(e){}		
	}
}

//处理操作历史
function gotoHistory(n){
	if(!n || !historyList[n]) return;
	if(window.cancelFirstHistory && historyList.length<2) return;
	eval(historyList[n]);
	historyOffset=n;
}

function saveHistory(command){
//	if(historyList[historyOffset]==command)return;  //重复的调用应该限制
	historyOffset++;
	historyList.length=historyOffset;
	historyList[historyOffset]=command;
	//top.document.getElementById('tblog').contentWindow.frames["historyFrame"].location=("http://imgcache.qq.com/qzone/blog/ajaxhistory.htm?"+(historyOffset%2)+"#"+historyOffset);
	top.document.getElementById('tblog').contentWindow.document.getElementById("historyFrame").src=("http://imgcache.qq.com/qzone/blog/ajaxhistory.htm?"+(historyOffset%2)+"#"+historyOffset);
}

/*------------------------------ 空间信息 ------------------------------------*/
function getSpaceInfo(qq){
	if(!qq) qq = uin;
		var url = "http://"+top.g_NewBlog_Domain+"/cgi-bin/blog/blog_getuserinfo.cgi?uin="+qq;
	top.loadXMLAsync("spaceInfo"+qq,url,new Function("getSpaceInfoSucc("+qq+")"),showError);
}

function getSpaceInfoSucc(qq){
	var x = top.g_XDoc["spaceInfo"+qq];
	if(x && x.getElementsByTagName("error").length==0){
		if(qq==uin){
			top.spaceName = x.getElementsByTagName("spacename")[0][isIE?"text":"textContent"].HTML2Text()
			top.ownerNickName = x.getElementsByTagName("nick")[0][isIE?"text":"textContent"].HTML2Text()
		}else{
			document.getElementById("orgPublish").style.display="";
			document.getElementById("orgPublish").firstChild.innerHTML = '本文由　<a href="http://'+
			qq+'.qzone.qq.com" target="_blank" class="username">'+x.getElementsByTagName("nick")[0].text.trim()+'</a>　发表在　<a href="http://'+
			qq+'.qzone.qq.com" target="_blank" class="userblog">'+	x.getElementsByTagName("spacename")[0].text.trim()+'</a>';
		}
	}
}

//------------------没有日志-------------------------
function showEmptyList(){
		var d = document.getElementById("blog_list");
		if(!d.oldHTML) d.oldHTML = d.innerHTML;
		if(uin == top.g_iLoginUin)
			d.innerHTML = "<div class=\"mode_table_main center\"><BR><img src=\"/qzone/client/logo_blog_none.gif\" alt=\"logo\" align=\"absmiddle\" /><a href=\"javascript:;\" onclick=\"createBlog()\"  class=\"a\"><BR><BR>从这里开始，写下您永恒的记录……与朋友分享您生活的点点滴滴……</a>"
		else
			d.innerHTML = "<div class=\"mode_table_main center\"><BR><img src=\"/qzone/client/logo_blog_none.gif\" alt=\"logo\" align=\"absmiddle\" /><BR><BR>您的好友还没有写日志哦!"
		d.style.display="";
		document.getElementById("blogTurnPageDiv").style.display="none";
		blogshowModule("blogList");
		//hidePreview();
		try{showCategoryList();}catch(e){} //显示日志档期列表
		mlineChange("show");
		hideOpratingMsg();
}

/*----------------------------  生成验证码 ------------------------------*/
function changeVerifyCode(id,timeout){
	timeout=(!timeout)?1000:timeout;
	if(event && event.srcElement == document.getElementById(id) && event.type!="error") 
		document.getElementById(id).src = "http://verify.qq.com/getimage?"+Math.random();
	else 
		setTimeout('document.getElementById("'+id+'").src = "http://verify.qq.com/getimage?"+Math.random()',timeout);
	document.getElementById(id).previousSibling.previousSibling.value="";
}
/*------------------------------  日志推荐 -------------------------------------------*/
function showSuggestBlog(){top.loadXMLAsync("qqblogcategory","http://"+top.imgcacheDomain+"/qzone/qqblogcategory.xml",doShowSuggestBlog,showError);}

function doShowSuggestBlog(){
	var x = top.g_XDoc["qqblogcategory"];
	var categories = x.selectNodes("//category");
	var cc=document.getElementById("category0");
	cc[0]=new Option("请选择分类",-1);
	cc.length=1;
	for(var i=0;i<categories.length;i++)
		cc[cc.length]=new Option(categories[i].getAttribute("name"),i)
	document.getElementById("suggestBlogDiv1").style.display="none";
	document.getElementById("suggestBlogDiv2").style.display="";
	showSubCategoryList(document.getElementById("category0").value);
	changeVerifyCode("verifycodeImg_suggest");
}

function suggestBlog(autos){
	with(document.suggestForm){
		uin.value=window.uin;
		spacename.value=top.spaceName;
		verifycode.value=document.getElementById('verifycodeImg_suggest').previousSibling.previousSibling.value;
		link.value=getBlogURL();
		nick.value=top.ownerNickName;
		title.value=blogForm.blogtitle.value;
		type.value=(!autos?document.getElementById("category1").value:"301");
		content.value= window.suggestContent;
		v.value="2";
		if(autos)
			verifycode.value="ssss";

		if(verifycode.value==""){
			alert("请输入验证码");
			verifycode.focus();
			return;
		}
		if(document.getElementById("category1").value==-1 && !autos){
			alert("请选择分类");document.getElementById("category1").focus();
			if(document.getElementById("category0").value==-1 && !autos) document.getElementById("category0").focus();
			return;
		}
		submit();
	}
	saveHistory("loadBlogList(doReadBlog);")
}

function showSubCategoryList(i){
	var items=[];
	if(i>=0)
		items = top.g_XDoc["qqblogcategory"].selectNodes("//category")[i].selectNodes("item");
	var cc=document.getElementById("category1");
	cc[0]=new Option("请选择分类",-1);
	cc.length=1;
	for(var i=0;i<items.length;i++)
		cc[cc.length]=new Option(items[i].getAttribute("name"),items[i].getAttribute("id"))
}

function showAuthorSign(){//隐藏、显示签名档
	if (top.g_XDoc["hiddensign"]) {top.g_XDoc["hiddensign"]=null;return}
	var s = document.styleSheets["trueStyle"];
	var r = (isIE?s.rules:s.cssRules)[0].style;
	if(r.display=="none"){
		r.display="";
		var tmp=document.getElementById("showSignButton");
		if(tmp)tmp.innerHTML="隐藏签名档";
	}else{
		r.display="none";
		var tmp=document.getElementById("showSignButton");
		if(tmp)tmp.innerHTML="显示签名档";
	}
	setCookie("showSign",r.display)
	if(event && Math.random()<0.001){
		window.tmpImg = new Image();
		window.tmpImg.src="http://"+top.g_NewBlog_Domain+"/cgi-bin/blog/blog_showhideautograph.cgi?"+Math.random();
	}
}


function copyBlogURL(){clipboardData.setData("Text",getBlogURL());showOpratingMsg("本文网址已经复制到剪贴板中");opratingMsgTimeout = setTimeout("hideOpratingMsg()",msgLife);}
function getBlogURL(){return ("http://user.qzone.qq.com/"+uin+"/blog/"+currentBlogId);}
function showLoginDiv(){document.getElementById("loginDiv").style.display="";document.getElementById("loginFrame").src="login.htm";}
function hideLoginDiv(){document.getElementById("loginDiv").style.display="none";document.getElementById("comment_editor").style.display="none";}
//------获取主人信息------
//getOwnerSign();
try{
	top.spaceName =top.g_XDoc[3].getElementsByTagName("spacename")[0].text.HTML2Text().HTML2Text().trim();
	top.ownerNickName =top.g_XDoc[3].getElementsByTagName("nickname")[0].text.HTML2Text().HTML2Text().trim();
}catch(ex){
	getSpaceInfo();
}

function openUserSpace(uin){
	if (isNaN(parseInt(uin,10)) || parseInt(uin,10)<10000 || !uin){
		alert("该用户使用了隐身草道具，真实身份已被隐藏");
		return;
	}
	window.top.location="http://"+uin+".qzone.qq.com/";
}

//--------------------------------------------模版支持-----------------------------
function getSystemTemplet(){ //获取系统模块样板
  var templet = document.getElementById("tplContainer");
  window["tpls"]={};
	var reg = /{(\w+)\$begin}((.|\n)[^}]+){end}/ig;
	while((arr = reg.exec(templet.value)) != null){
		if (top.QZoneVersion == "4.0" && top.zoneMode != "qzone")
			arr[2] = arr[2].replace(/class="bt_page"/g,'class="bt_page full"');
		window["tpls"][arr[1]] = arr[2].replace(/&lt;/g,"<").replace(/[\t\r\n]/g,"");
	}
    removeElement(templet);
}

function insertTpl(tplList){
	for(var i=0;i<tplList.length;i++){
		var des=document.getElementById("tpl_"+tplList[i]);
		if(!window["tpls"][tplList[i]])
			continue;
		else
			des.innerHTML=window["tpls"][tplList[i]];
		replaceElement(des.firstChild,des);
		window["tpls"][tplList[i]]=null;
	}
}
