var g_XDoc=[];
var g_ready= 0;
var searchTagUin="";
var diarySort=["大杂烩","个性签名","个人日记","天下杂侃","情感天地","休闲搞笑","原创文学","影音数码","体育博彩","游戏动漫","衣食住行"];

var r_single_node = /selectSingleNode match="([^"]+)"/
var r_single_node_content = /<%selectSingleNode[^>]*%>((.|\n)+)<%_selectSingleNode%>/

var r_repeat_match_1 = /repeat_1 match="([^"]+)"/
var r_repeat_content_1 = /<%repeat_1[^>]*%>((.|\n)+)<%_repeat_1%>/

var r_index = /<%=index%>/g
var r_text = /<%=text%>/g
var r_attribute_global = /<%=@(\w+)%>/g
var r_attribute = /<%=@(\w+)%>/

function fillDIV(divId,xDoc){
	var div = document.getElementById(divId);
	if (!div) {alert("指定的模版容器不"+divId+"存在");return;}
	var templetHTML;
	if (div.oldHTML) {
		templetHTML = div.oldHTML;
	}else{
		templetHTML = div.oldHTML = div.innerHTML;
	}
	templetHTML = templetHTML.replace(/\[%/g,"<%").replace(/%\]/g,"%>").replace(/\{%/g,"<%").replace(/%\}/g,"%>").replace(/\<!--%/g,"<%").replace(/%-->/g,"%>")
	div.innerHTML = doFill(templetHTML,xDoc,0);
	div.style.display = ""
}
function doFill(templetHTML,xDoc,xLevel){
	var stRegPrefix = "<%repeat_"+xLevel+"\\s*match=\"([^\"]+)\"[^%]*%>";
	var stRegContent = "<%repeat_"+xLevel+"[^>]*%>((.|\\n)+)<%_repeat_"+xLevel+"%>";

	var r_repeat_match = new RegExp(stRegPrefix);
	var r_repeat_match_global = new RegExp(stRegPrefix,"g");
	var r_repeat_content = new RegExp(stRegContent);
	var r_repeat_match_next_level = new RegExp("<%repeat_"+(xLevel+1)+" match=\"([^\"]+)\"");

	if (templetHTML.match(r_repeat_match)==null){
		alert("没有找到xml节点<%repeat_"+(xLevel)+"%>");
		return;
	}

	var arPrefix = templetHTML.match(r_repeat_match_global);
	var startPosition = 0;
	for (var i=0;i<arPrefix.length;i++){
		var st = arPrefix[i];
		var nodePath = st.replace(/^.*match=\"|\".*$/g,""); //获得xml节点路径
		if (st.indexOf("callback")>0)
			var fnCallBack = eval(st.replace(/^.*callback=\"|\".*$/g,"")); //获得回调函数
		startPosition = templetHTML.indexOf(st);
		var endPosition = templetHTML.indexOf("<%_repeat_"+xLevel+"%>",startPosition);
		var replaceContent = templetHTML.substring(startPosition,endPosition+13)
		startPosition += st.length;
		var repeatContent = templetHTML.substring(startPosition,endPosition); //获得内容模板
		var nodes = xDoc.selectNodes(nodePath); //获得xml节点
		var arContent = [];
		var attributes = repeatContent.match(r_attribute_global);
		if (attributes == null) attributes = [];
		for (var j=0;j<nodes.length;j++){
			var node = nodes[j];
			var content = repeatContent;
			if (repeatContent.match(r_repeat_match_next_level)!=null) //处理子节点
				content = doFill(repeatContent,node,xLevel+1)
			var s = content.replace(r_index,(j+1)).replace(r_text,node.text);
			for (var k=0;k<attributes.length;k++){
				var attrTag = attributes[k].replace(/\W/g,"");
				var attrValue = nodes[j].getAttribute(attrTag);
				if (attrValue==null && nodes[j].selectSingleNode(attrTag)!=null)
					attrValue = nodes[j].selectSingleNode(attrTag).text;
				if (attrValue==null) attrValue = "";
				s = s.replace(attributes[k],attrValue);
			}
			
			arContent[j] = s;
			if (fnCallBack) fnCallBack(node,arContent,j);
		}
		templetHTML = templetHTML.replace(replaceContent,arContent.join(""));
	}
	return templetHTML;
}

function loadXMLAsync(xID, xUrl, callback, err_callback){
		if ( (top.g_XDoc[xID]) && (top.g_XDoc[xID].xml!="") ) {
			if (callback) {
				callback();
			}
			return top.g_XDoc[xID];
		}
		try { top.g_XDoc[xID]= new ActiveXObject("microsoft.XMLDOM");
		}
		catch (e) {
			alert("对不起，您的浏览器不支持Qzone的某些特性。");
		}
		if (callback) {
			top.g_XDoc[xID].async= true;
			top.g_XDoc[xID].onreadystatechange = function() {
				if (top.g_XDoc[xID].readyState == 4) {
					if (top.g_XDoc[xID].parseError.errorCode ==0) callback();
					else if (err_callback) {
						err_callback();
					}
				}
			}
			g_XDoc[xID].load(xUrl);
			
		}
		else {
			top.g_XDoc[xID].async= false;
			top.g_XDoc[xID].load(xUrl);
			if (top.g_XDoc[xID].parseError.errorCode ==0) return top.g_XDoc[xID];
			else if (err_callback) return top.getXmlData(xID);
		}
	}

function getXmlData(itemno, callback) {
	var sUrl= "";
	switch (itemno) {
		case 1: // 搜索
			sUrl+= "http://qzone.qq.com/web/static_pages/xml/data_portal_searchtop.xml";
			break;
		case 2: // 内容
			sUrl+= "http://qzone.qq.com/web/static_pages/xml/portal.xml";
			break;
		case 3: // tagList
			sUrl+= "http://qzone.qq.com/web/static_pages/xml/newtags.xml";
			break;
		case 4: // tagList
			sUrl+= "http://qzone.qq.com/web/static_pages/xml/portal_hottags_xml.xml";
			break;
		case 5: // tagsearch
			sUrl+= "http://qzone-search.qq.com/cgi-bin/tag/cgi_tag_usertagxml?uin="+searchTagUin;
			break;
			default:
			return null;
	}
	if(5==itemno){
		if(typeof(search_loader)=='object')
		search_loader.loadXMLAsync(itemno, sUrl, callback);
	}else
		loadXMLAsync(itemno, sUrl, callback);
}	
function start(){
	getXmlData(1,new Function("fillTag()"));
	}
function fillTag(){
	fillDIV("tagkey",g_XDoc[1]);
	}
function fillCont(){
	var fixObj=preFix(2);
	}
function coreTextSub(obj,nodePath,textName,num){
	var objT=obj.selectNodes(nodePath);
	for(var i=0;i<objT.length;i++){
		var textT=objT[i].selectSingleNode(textName).text.substring(0,num);
		objT[i].setAttribute(textName,textT);
		}
	return obj;
}
function coreTextSubT(obj,nodePath,nodeName,textName,num){
	var objT=obj.selectNodes(nodePath);
	for(var i=0;i<objT.length;i++){
		var objT2=objT[i].selectNodes(nodeName);
		for(var j=0;j<objT2.length;j++){
		var textT=objT2[j].selectSingleNode(textName).text.substring(0,num);
		objT2[j].setAttribute(textName,textT);
		}
	}
	return obj;
}
function coreTextRep(obj,nodePath,textName){
	var objT=obj.selectNodes(nodePath);
	for(var i=0;i<objT.length;i++){
		var textT=objT[i].getAttribute(textName);
		objT[i].setAttribute(textName,diarySort[textT]);
		}
	return obj;
}
function preFix(list){
	var obj=eval('g_XDoc['+list+']')
	if(2==list){
	obj=coreTextSub(obj,"/portalroot/floristlist/florist","spacename",6);
	obj=coreTextSub(obj,"/portalroot/floristlist/florist","nick",3);
	obj=coreTextSub(obj,"/portalroot/itemlist/item","spacename",6);
	obj=coreTextSub(obj,"/portalroot/musiclist/music","spacename",6);
	obj=coreTextSub(obj,"/portalroot/musiclist/music","songname",6);
	obj=coreTextSub(obj,"/portalroot/minihouselist/minihouse","spacename",6);
	return obj;
	}else if(4==list){
	obj=coreTextSubT(obj,"/hot_tags/hot_tag","tag_qzone","qzone_name",10);
	obj=coreTextSubT(obj,"/hot_tags/hot_tag","tag_qzone","qzone_blog",16);
	obj=coreTextSubT(obj,"/hot_tags/hot_tag","tag_qzone","qzone_user",8);
	return obj;
	}
}

// replace with setQzoneCookie() in common.js of V2.0
function setCookie(name,value)
{
	document.cookie = name + "=" + value + "; path=/; domain=qq.com";
}

// replace with getQzoneCookie() in common.js of V2.0
function getCookie(name){
        var search;
        search = name + "=";
        offset = document.cookie.indexOf(search);
        if (offset != -1) {
                offset += search.length;
                end = document.cookie.indexOf(";", offset);
                if (end == -1)
                        end = document.cookie.length;
                return unescape(document.cookie.substring(offset, end));
        }
        else
                return "";
}
function setFileCookie(name,value){
        var expires=new Date();
        expires.setTime(expires.getTime()+10*12*30*24*3600*1000);
        document.cookie = name + "=" + value + ";expires="+expires.toGMTString()
+"; path=/; domain=qq.com";
}

//加了输入检查
function jumpToSpace(uin) {
	var r = /^\d{5,10}$/;
	if ( !r.test(uin) )	{
		alert("输入的QQ号码不正确！");
		return;
	}
	window.top.location="http://user.qzone.qq.com/"+uin;
	return;
}
function openUserSpace(uin){
        var openUrl = "http://user.qzone.qq.com/"+uin;
        if (parseInt(uin)==10){
                alert("该用户使用了隐身草道具，真实身份已被隐藏");
                return;
        }
  if (getCookie("clientver") == "")
     window.open(openUrl);
  else
     window.top.location=openUrl;
}

function startSearch(){
	if(window.location.href.indexOf("?")!=-1){
		var tag=window.location.href.split("?")[1];
		goSearch(tag);
		getXmlData(3,new Function("fillTagSearchKey()"));
	}else{
		getXmlData(3,new Function("fillTagSearchKey()"));
		getXmlData(4,new Function("fillTagSearchCon()"));
	}
}
function fillContS(){
	var fixObj=preFix(2);
	fillDIV("search_con",fixObj);
	}
function fillTagSearchKey(){
	fillDIV("search_tk",g_XDoc[3]);
	}
function fillTagSearchCon(){
	var fixObj=preFix(4);
fillDIV("search_main_con",fixObj);
	}

// 新的日志跳转函数
function openUserSpaceDiary(uin, url) {
	var openUrl = 'http://user.qzone.qq.com/'+uin+'/?url='+url;
	top.location = openUrl;
}
function openUserSpaceDiary(sUin,diaryId,typeId) {
	var openUrl = 'http://user.qzone.qq.com/'+sUin+'/?uin='+sUin+'&url=/client/blog/blog_one.htm%3Fdiaryid%3D'+diaryId;
	window.open(openUrl);
}

function goSearch (hotT){
	s_main_mi.innerHTML="<iframe name='search_resurt' id='search_resurt' width='620' height='450' scrolling='no' border='0' frameborder='0' src='http://qzone.qq.com/web/search_resurt.html?"+hotT+"' ></iframe>"
}
function mall_changeFlower(type,itemno,posx,posy,width,height,zIndex,level)
{
		var iLoginUin = getQQNum();
		if(iLoginUin>10000)
		{
				var openUrl="http://user.qzone.qq.com/"+iLoginUin+"?url=http://imgcache.qq.com/qzone/mall/v3/web/mall/index.htm?target=flower";
        window.open(openUrl, "change_flower", "");
    }
		else
			alert("领养植物前请先登录QQ空间!");
}
function openUserSpaceAlbum(sUin, sUrl) {
	var openUrl = "http://user.qzone.qq.com/"+sUin+"/?url="+escape(sUrl);
    if (getCookie("clientver") == "")
        window.open(openUrl);
    else
        window.top.location=openUrl;
}


function portal_mall()
{
	var iLoginUin = getQQNum();
	if(iLoginUin>10000)
	{
		if (getCookie("clientver") == "")
			window.open("http://user.qzone.qq.com/"+iLoginUin+"/?openmall");
		else
			top.location.href = "http://user.qzone.qq.com/"+iLoginUin+"/?openmall";
	}
	else
	{
		alert("请您先登录!");
    var p=getElementPageOffset((document.body.clientWidth-290)/2,(document.body.clientHeight-250)*2/3);
		window.top.qq_login_form(15000101,'http://qzone.qq.com/');
		var loginDiv = document.getElementById("login_div");
		loginDiv.style.position="absolute";
		loginDiv.style.top=p.y+"px";
		loginDiv.style.left=p.x+"px";
	}
}

function getElementPageOffset(x,y){
    return {x:x+document.body.scrollLeft - 2, y:y+document.body.scrollTop - 2};
}

function JumpQQhome()
{
	var url = 'http://home.qq.com/mall/mall.shtml';
	window.open(url);
}

function JumpQQhomeBBS()
{
	var url = "http://miniwu.bbs.qq.com";
	window.open(url);
}
function GoJB()
{
	window.open("http://qzone.qq.com/web/jb.shtml");
}
function showMyTagInf(uin)
{
	searchTagUin=uin;
	if(window.showMyTagbyJs){
	if(g_ready==1)
		getXmlData(5,new Function("fillMyTagbyJs()"));
	else
		setTimeout("showMyTagInf("+uin+")",100);
	}
}
function fillMyTagbyJs()
{
	var objT=g_XDoc[5].selectNodes("/tags/tag");
	var textStr="";
	for(var i=0;i<objT.length;i++){
		textStr+='<span class="button" onclick="goSearch (\''+objT[i].text+'\')">'+objT[i].text+'</span>&nbsp;&nbsp;';
		}
		var str="";
				str+='<input name="textfield" type="text" id="searchIn" value="请输入关键字(Tag)" onmouseover="if(this.value==\'请输入关键字(Tag)\')this.value=\'\'"/>'
					+'<img onclick="javascript:goSearch(searchIn.value)" src="http://imgcache.qq.com/qzone/portal/bt_search_main.gif" class="bt_search_main" /><br/><br/>'
					+'&nbsp;&nbsp;  <span onclick="gotoAndSetTag()" style="cursor:pointer" class="search_w_1">设置我的QQ空间关键字(Tag)</span><br/>&nbsp;&nbsp;  <span class="search_w_2">我的Tag：</span><span style="cursor:pointer" class="search_w_3">'+textStr+'</span>';
					showMyTagbyJs.innerHTML=str;
}

function gotoAndSetTag()
{
	s_main_mi.innerHTML="<iframe name='search_resurt' id='search_resurt' width='620' height='450' scrolling='no' border='0' frameborder='0' src='http://qzone-search.qq.com/web/tag/tt_set.html' ></iframe>"
}

function go_music()
{
	var iLoginUin = getQQNum();
	if(iLoginUin>10000)
	{
		var openUrl = "http://user.qzone.qq.com/"+iLoginUin;
		if(getCookie("clientver") != "")	//在客户端打开
			window.top.location = openUrl;
		else
			window.open(openUrl);
	}
	else
	{
		alert("请先登录");
		var p=getElementPageOffset((document.body.clientWidth-290)/2,(document.body.clientHeight-250)*2/3);
		window.top.qq_login_form(15000101,'http://qzone.qq.com/');
    var loginDiv = document.getElementById("login_div");
		loginDiv.style.position="absolute";
		loginDiv.style.top=p.y+"px";
		loginDiv.style.left=p.x+"px";
	}
}

function jumpToPortalStarView(uin)		//跳转到用户明星
{	
	var url='http://qzone.qq.com/web/star/index.shtml?goto='+'http://qzone.qq.com/web/static_pages/star/views/'+uin+'.htm';
	window.top.location=url;
}
function jumpToPortalStarList(page)		//跳转到列表
{
	var url='http://qzone.qq.com/web/star/index.shtml?goto='+'http://qzone.qq.com/web/static_pages/star/list_'+page+'.htm';
	window.top.location=url;
}
function jumpToPortalCommendInput()		//跳转到自我推荐
{
	var iLoginUin = getQQNum();
	if (iLoginUin>10000) {
		var url='http://qzone.qq.com/web/star/index.shtml?goto='+'http://dynamic.qzone.qq.com/cgi-bin/portal/portal_commend_inputdata';
		window.top.location=url;
	} else {
		alert("推荐前请先登录QQ空间!");
	}
}
//
function checkQQH(jumpUin,n) {
	if (n == 0 && jumpUin.value == "请输入QQ号码"){jumpUin.value="";jumpUin.style.cssText = "color:#000"}
	if (n == 1){
		if(jumpUin.value == "请输入QQ号码"){jumpUin.value="";}
		jumpUin.style.cssText = "color:#000";
	}
	if (n == 2 && jumpUin.value == ""){jumpUin.value = "请输入QQ号码";jumpUin.style.cssText = "color:#454545"}
}
function checksearchIn(searchIn,n) {
	if (n == 0 && searchIn.value == "请输入关键字(Tag)"){searchIn.value="";searchIn.style.cssText = "color:#000"}
	if (n == 1){
		if(searchIn.value == "请输入关键字(Tag)"){searchIn.value="";}
		searchIn.style.cssText = "color:#000";
	}
	if (n == 2 && searchIn.value == ""){searchIn.value = "请输入关键字(Tag)";searchIn.style.cssText = "color:#454545"}
}

function Cookie(document, name, hours, path, domain, secure)
{
    this.$document = document;
    this.$name = name;
    if (hours)
        this.$expiration = new Date((new Date()).getTime() + hours*3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}

Cookie.prototype.store = function () {
    var cookieval = "";
    for(var prop in this) {
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) 
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + escape(this[prop]);
    }

    var cookie = this.$name + '=' + cookieval;
    if (this.$expiration)
        cookie += '; expires=' + this.$expiration.toGMTString();
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    if (this.$secure) cookie += '; secure';

    this.$document.cookie = cookie;
}

Cookie.prototype.load = function() { 
    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;

    var start = allcookies.indexOf(this.$name + '=');
    if (start == -1) return false;   
    start += this.$name.length + 1;  
    var end = allcookies.indexOf(';', start);
    if (end == -1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);

    var a = cookieval.split('&');    
    for(var i=0; i < a.length; i++) 
        a[i] = a[i].split(':');
    
    for(var i = 0; i < a.length; i++) {
        this[a[i][0]] = unescape(a[i][1]);
    }
    
    return true;
}

Cookie.prototype.remove = function() {
    var cookie;
    cookie = this.$name + '=';
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';
    this.$document.cookie = cookie;
}

function islogon()
{
  var ck=document.cookie;
  if(ck=="" || ck==undefined || ck==null)
  {
    return false;
  }
  var i=ck.indexOf("uin");
  if(i==-1)
  {
    return false;
  }
  var tp="";
  if(i+14>=ck.length)
  {
   tp="";
   return false;
  }else{
    tp=ck.substring(i+4);
  }
  var i1=tp.indexOf(";");
  if((i1<0 && tp.length>0) || i1>0)
  {
    return true;
  }
  return false;
}

// replace with getUserQQ() in common.js of V2.0
function getQQNum()
{
  var iLoginUin = parseInt(getCookie("zzpaneluin"));
	
	if (iLoginUin >10000 && iLoginUin < 1200000000)
	{
    	return iLoginUin;
	}

	var cookie_uin = getCookie("uin");
	var re = /^o(0)*/;
	var tmp_cookie_uin = cookie_uin.replace(re,'');
	var qq = parseInt(tmp_cookie_uin);
	if (qq > 10000 && qq < 1200000000)
	{
		return qq;
	}

	return 0;
}
