/**
 * config
 */
var G_MAX_POST_LEN = 5000;
var G_MAX_REPLY_LEN = G_MAX_POST_LEN;

isFun 	 = function(a){ return typeof a == "function"; };
isNull 	 = function(a){ return typeof a == "object" && !a; };
isNumber = function(a){ return typeof a == "number" && isFinite(a);};
isObject = function(a){ return (a && typeof a == "object") || isFun(a);};
isString = function(a){ return typeof a == "string";};
isArray  = function(a){ return isObject(a) && a.constructor == Array; };
isUndef  = function(a){ return typeof a == "undefined";};
DoNothing = function(){};
var g_level = [ "新生野人", "饥寒野人", "温饱野人", "小康野人", "新来土著", "无知土著", "生疏土著", "懂行土著", "年轻采集者", "熟练畜牧者",
"强壮狩猎者", "勇敢守卫者", "聪明小巫师", "智慧大法师", "荣誉的贵族", "资深的祭司", "敬仰的前辈", "英雄", "传奇", "神话" ];

$E=$ = function () {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string'){
      element = document.getElementById(element);
   }
    if (arguments.length == 1) 
      return element;

    elements.push(element);
  }

  return elements;
}

$P = function(parameter, url)
{
	url = isUndef(url) ? location.href : url;
	var result = url.match(new RegExp("[\#|\?]([^#]*)[\#|\?]?"));
	url = "&" + (isNull(result) ? "" : result[1]);	
	result = url.match(new RegExp("&"+parameter+"=", "i"));
	return isNull(result) ? undefined : url.substr(result.index+1).split("&")[0].split("=")[1];
};
var Class = {
	create: function(){
		return function(){
			this.initialize.apply(this, arguments);
		}
	},
	
	extend: function(destination, source){
		for (property in source) {
    		destination[property] = source[property];
  		}	
		return destination;
	}
}
var Delegate = {
	create: function (obj, func){
		var f = function()	{
			var target = arguments.callee.target;
			var func = arguments.callee.func;
			return func.apply(target, arguments);
		}
		f.target = obj;
		f.func = func;
		return f;
	}
};
var Insertion = {
        _insertContent: function(element, content, where){
                element = $(element);
                if (isString(content)){
                        element.insertAdjacentHTML(where, content);
                        return;
                }
                if (isObject(content)){
                        element.insertAdjacentElement(where, content);
                        return;
                }
        },

        before: function(element, content){
                Insertion._insertContent(element, content, "beforeBegin");
        },

        top: function(element, content){
                Insertion._insertContent(element, content, "afterBegin");
        },

        bottom: function(element, content){
                Insertion._insertContent(element, content, "beforeEnd");
        },

        after: function(element, content){
                Insertion._insertContent(element, content, "afterEnd");
        }
};
if (window.HTMLElement){
	if (!window.HTMLElement.prototype.insertAdjacentElement){
		window.HTMLElement.prototype.insertAdjacentElement
		= function(where, element){
			switch (where){
				case "beforeBegin":
					this.parentNode.insertBefore(element, this);
					break;
				case "afterBegin":
					this.insertBefore(element, this.firstChild);
					break;
				case "beforeEnd":
					this.appendChild(element);
					break;
				case "afterEnd":
					if(this.nextSibling)
						this.parentNode.insertBefore(element, this.nextSibling);
					else
						this.parentNode.appendChild(element);
					break;
			    }
		};

	}

	if (!window.HTMLElement.prototype.insertAdjacentHTML){
		window.HTMLElement.prototype.insertAdjacentHTML = function(where, htmlText){
			var rng = this.ownerDocument.createRange();
			rng.setStartBefore(this);
			this.insertAdjacentElement(where, rng.createContextualFragment(htmlText));
		}
	}
}

String.prototype.trim = function()
{
	return this.replace(new RegExp("(^[\\s]*)|([\\s]*$)", "g"), "");	
}

var Browser = "";
function checkBrowser(){
	var b = navigator.userAgent.toLowerCase();

	// Figure out what browser is being used
	Browser = {
		safari: /webkit/.test(b),
		opera: /opera/.test(b),
		msie: /msie/.test(b) && !/opera/.test(b),
		mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)
	};
}
checkBrowser();

function checkEvent(c){

		if(window.event.ctrlKey && window.event.keyCode == 13){
			c.form.onsubmit();
		}
}
function IsAscii(ch)
{
	if(ch > 0 && ch <= 255)
		return true;
	else
		return false;
}
function isImgUrl(url){
	var reg=/(^http:\/\/\w+)|(^ftp:\/\/\w+)|(^thunder:\/\/\w+)/i;
	if(reg.test(url)) return true;
	else return false;
}
function SubStr(sText, iLength)
{
	var i,iLenOfAscii;
	for (i=0,iLenOfAscii=0; i<sText.length && iLenOfAscii<iLength; i++)
		iLenOfAscii += IsAscii(sText.charCodeAt(i)) ? 1 : 2;	
	if (i == sText.length) return sText;
	else return sText.substring(0, i)+"...";
}

function printf(fmt)
{
	if( !fmt || (typeof fmt != "string")) return undefined;
	var r = fmt.match(new RegExp("\%[0-9]*d", "g"));
	var result = fmt;
	if ( !r || arguments.length < r.length + 1) return undefined;
	for ( var i = 0; i < r.length; ++i){
		var exp = r[i];
		var num = exp.match(new RegExp("[0-9]+"), "g");
		var s = arguments[1 + i].toString();
		if ( num ){
			num = parseInt(num[0]);
			while ( s.length < num ) s = ("0").concat(s);
		}
		result = result.replace(new RegExp(exp), s);
	}

	return result;
}

function pgv(url)
{
	var o = document.createElement("iframe");
	o.width = 0; o.hight = 0; o.style.visibility = "hidden";
	document.body.appendChild(o);
}
function g_getCookie(name){
	var reg = new RegExp("(\\b" + name + "=" + "[^;]*);?");
	var r = null;
	if ( r = document.cookie.match(reg)){
		return unescape(r[1].split("=")[1]);
	}
	else
		return "";
} 
function g_setCookie(name,value,hours){
	if(arguments.length>2){
		var expireDate=new Date(new Date().getTime()+hours*3600000);
		document.cookie = name + "=" + escape(value) + "; path=/; domain=xunlei.com; expires=" + expireDate.toGMTString() ;
	}else
		document.cookie = name + "=" + escape(value) + "; path=/; domain=xunlei.com"; 
}
function g_setCookieToday(name,value){
	var now = new Date();
	var year=now.getYear();
	var month=now.getMonth();
	var date=now.getDate()+1;
	var expireDate=new Date(year,month,date);
	document.cookie = name + "=" + escape(value) + "; path=/; domain=xunlei.com; expires=" + expireDate.toGMTString() ;
}
function g_getUserInfo(){
	try{
	return g_getCookie('sessionid');	
	}catch(e){alert(e);}
}
function g_collectDataByArray(a){
	var aId=new Array(a.length);
	var myForm=document.createElement("<form id='myForm' action='' method='post' dispaly='none' />");
	for(var i=0;i<a.length;i++){
		aId[i]=a[i].idx;
		switch(g_typeById(aId[i])){
			case "textarea":
				myForm.innerHTML+="<textarea name="+a[i].idx+" id="+a[i].idx+" value='"+a[i].value+"'/>";
				break;
			default:
				myForm.innerHTML+="<input type='text' name="+a[i].idx+" id="+a[i].idx+" value='"+a[i].value+"'/>";
				break;
		}
	}
	document.body.appendChild(myForm);
}
function g_postData(url){
	myForm.action=url;
	myForm.submit();
	document.body.removeChild(myForm);
}
function g_typeById(s){
	//var str_tb=/_tb$/;
	var str_ta=/_ta$/;
	//var str_sb=/_sb$/;
	if(str_ta.test(s)) {return "textarea";}
	//if(str_sb.test(s)) {return "select";}
	else {return "text";}
}
function getLogInfo(){
	if(g_getUserInfo()){
		userInfo_a();
		isLogin=true;
		g_sendLoginInfo();
	}else{
		var choice = confirm("发起悬赏必须登录，要登录吗?");
		if(choice){
			var toUrl = 'http://bbs.xunlei.com/login.html?u1='+location.href;
			window.location = toUrl;
		}
	}
}
function g_logout(){
	g_setCookie('sessionid','',0);
	frames['rightFra'].location.reload();
	frames['userFra'].location.reload();
}
function ScriptReplace(srcString) {
		//过滤注入脚本
		srcString = srcString.replace(/&#(\d+);?/g,function(a,b){return String.fromCharCode(b)}).replace(/&#x(\d+);?/ig,function(a,b){return String.fromCharCode(parseInt(b,16))}).replace(/(\Won)(\w+\s*=)/ig,"$1<wbr>$2").replace(/(\Wexpres)(sion\()/ig,"$1<wbr>$2").replace(/(\Wbehav)(ior\s*:)/ig,"$1<wbr>$2").replace(/(obj)(ect)/ig,"$1<wbr>$2").replace(/(scr)(ipt)/ig,"$1<wbr>$2").replace(/(emb)(ed)/ig,"$1<wbr>$2").replace(/\r\n/g,"bbrr").replace(/\t/g," &nbsp; &nbsp;");
		return srcString;
}
function htmlReplace(str){
	return str.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");	
}
function g_getUserName(){
	if(g_getUserInfo()){
		g_getClubRole();
		return	g_getCookie('usrname');
	}else
	{
		return	'游客';
	}
}

function g_sendUrlByIfr(u,succCallback){
	var ifr=document.createElement('iframe');
	ifr.width = 0;
	ifr.Height = 0;
	document.body.appendChild(ifr);
	ifr.src=u;
	addEvt = ifr.attachEvent || function(a1,a2){ifr.addEventListener(a1, a2, true);};
	addEvt('onload', function (){eval(succCallback);
									   document.body.removeChild(ifr);
									   
									   });		
}
function g_HttpGetByIfr(u,c){
	var ifr=document.createElement('iframe');
	ifr.width = 0;	ifr.Height = 0;	ifr.src=u;
	ifr.style.visibility = "hidden";
	var f = function (){ 
		if(c)c();
		document.body.removeChild(ifr);							   
	};	
	if(Browser.msie)ifr.attachEvent('onload', f)
	else ifr.addEventListener("load", f, true);
	document.body.appendChild(ifr);
}

function g_setTimePrevent(cn,t){
	g_setCookie(cn,'live',t/3600)
}
function g_getTimePrevent(cn){
	if(!g_getCookie(cn))
		return true;
	else
		return false;
}
function DoCopy(url){
 var clipBoardContent=url; 
 window.clipboardData.setData("Text",clipBoardContent);
 alert("复制成功！粘贴到QQ/MSN上发送给好友吧：）");
}

function g_checkLen(len, max)
{
	if ( len >= max - 1)
		alert("对不起，字数不能超过 " + max);
	return len < max - 1;
}

function g_getType(type)
{
	var main = type % 100;
	var sub = Math.floor( type / 100);
	
	var mainTypeName = "";
	var subTypeName = "";
	for ( i in g_type){
		var m = g_type[i];
		if ( m.idx == main){
			mainTypeName = m.name;
			for ( j  in m.subType){
				var s = m.subType[j];
				if ( s.idx == type){
					subTypeName = s.name;
					break;
				}
			}

			break;
		}
	}

	return {main: mainTypeName, sub: subTypeName};
}

function Template(urlTpl){
	this.before_block = '';
	this.first = '';
	this.first_grey = '';
	this.prev = '<a href="[%link_href%]">上一页</a>&nbsp;';
	this.prev_grey = '';
	this.next = '&nbsp;<a href="[%link_href%]">下一页</a>';
	this.next_grey = '';
	this.last = '';
	this.last_grey = '';
	this.listTpl = '[==link<a href="[%link_href%]">[[%page_num%]]</a>==]';
	this.listItemSep ='&nbsp;';
	this.listCurItemTpl ='<a style="text-decoration:none;color:#000000;">[%page_num%]</a>';
	this.after_block = '';
	this.destUrlTpl = urlTpl;
}

function PageList( template, cur, total, max_item_num, ctl)
{
	var defctl = { show_edge: false};
	if ( isUndef(template)){
		throw new Error("template not specified");
	}

	var setDefTpl =function(tplAttr)
	{
		if ( isUndef(tplAttr)) tplAttr = "";
	};
	
	this.tpl = template;
	for ( var name in this.tpl){
		setDefTpl(this.tpl[name]);
	}

	this.cur = cur;
	this.total = total;
	this.ctl = isUndef(ctl) ? defctl : ctl;
	this.MAX = isUndef(max_item_num) ? 3 : max_item_num;
}
PageList.prototype = {
	getPageListHTML: function ()
	 {
		 var html = "";
		 html += this.tpl.before_block;
		 var iBeg = this.cur - parseInt(this.MAX / 2); 
		 iBeg = (iBeg < 1 ) ? 1 : iBeg;

		 var iEnd = this.cur + parseInt(this.MAX / 2);
		 iEnd = ( iEnd > this.total ) ? ( this.total ) : iEnd;

		 if ( this.cur > 1 ){			
			 var firstUrl = this.tpl.destUrlTpl.replace("[%page%]", 1);
			 var prevUrl = this.tpl.destUrlTpl.replace("[%page%]", this.cur - 1);
			 html += this.tpl.first.replace("[%link_href%]", firstUrl);
			 html += this.tpl.prev.replace("[%link_href%]", prevUrl);
		 }
		 else if( this.ctl.show_edge){  // 当前页为第一页
			 html += this.tpl.first_grey;
			 html += this.tpl.prev_grey;
		 }
		 var result = this.tpl.listTpl.match(/\[==link(.*)==\]/);

		 var beforeLink = "", link = "", afterLind = "";
		 if ( result != null){
			 beforeLink = this.tpl.listTpl.substring(0, result.index - 0);
			 link = result[1];
			 afterLink = this.tpl.listTpl.substring(result.index + result[0].length);
		 }

		 html += beforeLink;
		 for (var page = iBeg; page <= iEnd; ++page) {
			 var url = this.tpl.destUrlTpl.replace('[%page%]', page);
			 if ( page != this.cur)
				 html += link.replace("[%link_href%]", url).replace("[%page_num%]", page);
			 else
				 html += this.tpl.listCurItemTpl.replace("[%page_num%]", page);
			 if ( page != iEnd) html += this.tpl.listItemSep;
		 } 

		 html += afterLink;
		 if ( this.cur < this.total ){			
			 var lastUrl = this.tpl.destUrlTpl.replace("[%page%]", this.total);
			 var nextUrl = this.tpl.destUrlTpl.replace("[%page%]", this.cur + 1);
			 html += this.tpl.next.replace("[%link_href%]", nextUrl);
			 html += this.tpl.last.replace("[%link_href%]", lastUrl);
		 }
		 else if( this.ctl.show_edge){  // 当前为最后一页，不显示“最后页”链接和,"下一页 "链接 
			 html += this.tpl.next_grey;
			 html += this.tpl.last_grey;
		 }
		 html += this.tpl.after_block;
		 return html;
	 }	
};

function ClubUserInfo(cookie){
	this.c = cookie;
}
ClubUserInfo.prototype = {
	__get:function(name){
		var c = this.c;
		if(isUndef(c)) return "";
		var result = c.match(new RegExp( "\W?" + name + "/([^,]*),?"));
		return isNull(result) ? "" : result[1];
	},
	
	role:function(){return this.__get("role");},
	level: function(){return g_level[this.__get("level")];},
	levelNum: function(){return this.__get("level");},
	ccoin: function(){return this.__get("ccoin");},
	nlNeedPost:function(){return this.__get("nlNeedPost");},
	nlNeedRpl:function(){return this.__get("nlNeedRpl");},
	nlNeedGPost: function(){return this.__get("nlNeedGPost");},
	effectivePostNum:function(){return this.__get("ePost");},
	goodPostNum:function(){return this.__get("gPost");},
	postNum:function(){return this.__get("post");},
	replyNum:function(){return this.__get("reply");},
	vip:function(){return this.__get("vip");},

	NoNeedVerifyCode: function(){var uRole = this.role(); return (this.levelNum() >= 6 || uRole.indexOf("service") != -1 || uRole.indexOf("offical") != -1 || uRole.indexOf("global_common_admin") != -1);}
};

// index
function idx_rotationSWF(swf, focus_width, focus_height, text_height, pics, links){
	var swf_height = focus_height +text_height;
	var texts = '';
	var str='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '
		+'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" '
		+'width="'+ focus_width +'" height="'+ swf_height +'">'
	 +'<param name="allowScriptAccess" value="sameDomain">'
	 +'<param name="movie" value="' + swf + '">'
	 +'<param name=wmode value=transparent><param name="quality" value="high">'
	 +'<param name="menu" value="false"><param name=wmode value="opaque">'
	 +'<param name="FlashVars" '
	 	+'value="pics='
	 	+pics 
	 	+'&links='+links
	 	+'&texts='+texts
	 	+'&borderwidth='+focus_width
	 	+'&borderheight='+focus_height
	 	+'&textheight='+text_height+'">'
	 +'<embed src="' + swf + '" wmode="opaque" '
	 	+'FlashVars="pics='+pics
	 		+'&links='+links
	 		+'&texts='+texts
	 		+'&borderwidth='+focus_width
	 		+'&borderheight='+focus_height
	 		+'&textheight='+text_height
	 		+'" menu="false" bgcolor="#DADADA" quality="high" '
	 	+'width="'+ focus_width +'" height="'+ swf_height 
	 	+'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'  
	 +'</object>';
	 
	 return str;
}
function idx_showRotationSwf(id){
	var eurls = [];
	for ( var i in g_rotationPics.urls)
		eurls.push(encodeURIComponent(g_rotationPics.urls[i]));
		
	document.getElementById(id).innerHTML = idx_rotationSWF('http://bbs.xunlei.com/images/player.swf',290, 184, 0,
						g_rotationPics.pics.join('|'),
						eurls.join('|'));;
}

//user
function user_embedFlashStr(src, id)
{
return '<object id="' + id +'" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '
+ 'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="50" height="50"  align="middle">'
+'<param name="allowScriptAccess" value="always" /><param name="wmode" value="transparent" />'
+'<param name="movie" value="' + src +'" />'
+'<param name="quality" value="high" />'
+'<param name="bgcolor" value="#ffffff" />'
+'<embed id="' + id + '" src="' + src + '" quality="high" bgcolor="#ffffff"  width="50" height="50" wmode="transparent" '
+'align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" wmode="transparent" '
+'pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>';
}
function user_showCCoinSwf(blkId, src, swfId)
{
	$(blkId).innerHTML = user_embedFlashStr(src, swfId);
}
function appendCacheTime(str)
{
	var ctm = new Date().getTime();
	if ( str.indexOf('cachetime') != -1) str = str.replace(/cachetime=[^&]+/, 'cachetime=' + ctm);
	else if ( str.indexOf('?') != -1) str += '&cachetime=' + ctm;
	else str += '?cachetime=' +ctm;
		
	return str;
}

/**
* 取得‘访问过此论坛的人还访问过的论坛’的数据文件
*/
function getOVCUrl(uniq_club_id)
{
	return "http://bbs.xunlei.com/ovc/" + parseInt(uniq_club_id) % 256 + "/" + uniq_club_id + ".html";
}

/**
 * 取得'本类热门论坛'的数据文件
 */
function getClublistUrlOfType(type, page)
{
	page = page ? parseInt(page) : 1;
	return "http://bbs.xunlei.com/list/" + parseInt(type) % 100 + "/" + type + "/clublist_" + page + ".html";
}

