if (typeof(rootdir)=='undefined') var rootdir='';
var loadingStr='<img src="'+rootdir+'image/smallicon/loading.gif" />Loading...';
var IE = (document.all) ? 1 : 0;
var formWin_finish_cb=new Array();
var iframeCount=0;
var serverTime;

function getCookie(k)
{
	var pairs=document.cookie.split(";");
	for (var i=0;i<pairs.length;i++){
		var j=0;
		while(pairs[i].charAt(j)==" ") j++;
		pairs[i]=pairs[i].substring(j,pairs[i].length-j+1);
		var pairSplit=pairs[i].split("=");
		if (pairSplit[0]==k && pairSplit.length>1){
			return pairSplit[1];
		}
	}
	return "";
}
//============Com Instant (AJAX)===========================
var channel_count=10;
var xmlObj=new Array(channel_count);
var ci_status=new Array(channel_count);
var ci_error=new Array(channel_count);
var ci_callback=new Array(channel_count);
var ci_onerrorcallback=new Array(channel_count);
var ci_timerHandle=new Array(channel_count);

//const
var ci_READY=0;
var ci_BUSY=1;

//INIT
if (!getNewXmlObj()) {
	alert ("您的浏览器不支持xmlHttpRequest");
}

for (var i=0;i<=channel_count;i++) {
	ci_status[i]=ci_READY;
	ci_error[i]=false;
}

function getNewXmlObj() {
	var request = false;
	try {
  	request = new XMLHttpRequest();
	} catch (trymicrosoft) {
  	try {
    	request = new ActiveXObject("Msxml2.XMLHTTP");
  	} catch (othermicrosoft) {
    	try {
      	request = new ActiveXObject("Microsoft.XMLHTTP");
    	} catch (failed) {
      	request = false;
    	}
  	}
	}
	return request;
}

//request(channel , asp , callback_Success , callback_Error , timeout ,key1,val1.....)
function request() {
	showLoading();
	var arg=request.arguments;
	var channel=arg[0];
	if (channel=="" || channel==null) channel=getFreeChannel();
	if (channel<0) return -1;
	if (ci_status[channel]==ci_READY) {
		xmlObj[channel]=getNewXmlObj();
		ci_status[channel]=ci_BUSY;
		ci_callback[channel]=arg[2];
		ci_onerrorcallback[channel]=arg[3];

		var asp=arg[1];
		var keyvalues="ComIns=true&ci_channel="+channel;
		count=Math.floor((arg.length-5)/2);	
		if (count==0 && typeof(arg[5])!="undefined"){
			for (var i=0;i<arg[5].length;i++) {
				key=arg[5][i][0];
				msg=arg[5][i][1];
				keyvalues+=("&" + encodeURIComponent(key) +"=" +encodeURIComponent(msg));
			}
			count=i;
		}else{
			for (var i=0;i<count;i++) {
				key=arg[5+2*i];
				msg=arg[6+2*i];
				keyvalues+=("&" + encodeURIComponent(key) +"=" +encodeURIComponent(msg));
			}
		}
		var timeout=arg[4];		
		if (timeout=="" || timeout==null) timeout=60000;

		setTimeout("checkResponse("+channel+")",100);
		if (timeout>0)
			ci_timerHandle[channel]=setTimeout("comTimeout("+channel+")",timeout);
		else
			ci_timerHandle[channel]=-1;
		if (count>0) {
			xmlObj[channel].open("POST",asp,true);
			xmlObj[channel].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlObj[channel].send(keyvalues);
		}else{
			xmlObj[channel].open("GET",asp,true);
			xmlObj[channel].send(null);
		}
		return channel
	}else{
		return -1
	}
}

function release(channel) {
	try {
		xmlObj[channel].abort();
	}catch (e){;}
	xmlObj[channel]=null;
	ci_status[channel]=ci_READY;
	ci_error[channel]=false;
	
	var i;
	for (i=0;i<=channel_count;i++) {
		if (ci_status[i]!=ci_READY) break;
	}
	if (i==channel_count+1) hideLoading();
}

function checkResponse(channel) {
	if (ci_error[channel]) return;
	if (xmlObj[channel].readyState==4) {
		setTimeout(ci_callback[channel].replace(/%channel%/,channel),1)
		if (ci_timerHandle[channel]>0) clearTimeout(ci_timerHandle[channel]);
	}else{
		setTimeout("checkResponse("+channel+")",100);
	}
}

function comTimeout(channel) {
	xmlObj[channel].abort();
	ci_error[channel]=true;
	setTimeout(ci_onerrorcallback[channel].replace(/%channel%/,channel),1);
}

function getFreeChannel() {
	for (var i=0;i<=channel_count;i++)
		if (ci_status[i]!=ci_BUSY) return i;
	return -1;
}

function showLoading()
{
	var left=document.body.clientWidth-100;
	var tmp=openEx("loading",left,0,20,100);
	setOpacity(tmp.style,0.7);
	updateHTML("loading",loadingStr);
}

function hideLoading() {	closeEx("loading");}
function getVar(node,key)
{
	if (node==null) return null;
	var tmp=node.getElementsByTagName(key);
	if (tmp.length==0) return "";
	tmp=tmp[0];
	if (!tmp.hasChildNodes()) return "";
	return tmp.firstChild.nodeValue;
}
//============End of Com Instant (AJAX)===================

//=============MM Image Swap==============
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//==========End of MM Image Swap========

//============Common==============
function getServerTime(channel) {
	var xmlDoc=xmlObj[channel].responseXML;
	var tmpNodes=xmlDoc.getElementsByTagName("serverTime");
	if (tmpNodes.length>0) {
		var tmpNode=tmpNodes[0];
		serverTime=strToDate(tmpNode.firstChild.nodeValue);
	}
}

function strToDate(str)
{
	var tmp;
	try {
		tmp=eval("new Date("+str+")");
	}catch (err){
		tmp=new Date(1980,1,1);
	}
	return tmp;
}

//t2是t1的...
function timeDiffStr(t1,t2)
{
	var diff=(t1-t2)/1000;
	var suf=((diff>=0)?"前":"后");
	diff=Math.abs(diff);
	var diff1=diff;
	
	if (diff<=30) return "几秒钟" +suf;
	diff1=Math.round(diff/60);
	if (diff1<=60) return diff1 + "分钟" +suf;
	diff1=Math.round(diff/3600);
	if (diff1<=24) return diff1 + "小时" +suf;
	diff1=Math.floor(diff/86400);
	if (diff1<60) return diff1 + "天" +suf;
	diff1=Math.floor(diff/86400/30);
	if (diff1<=12) return diff1 + "个月" +suf;
	diff1=Math.floor(diff/86400/365);
	if (diff1<5) return diff1 + "年" +suf;
	return "很久以" +suf;
}

//Time Difference String of server time and str
function timeStr(str){
	return timeDiffStr(serverTime,strToDate(str));
}

//Size String
function sizeStr(size){
	var size1=size;
	if (size1<2048) return size1+" 字节";
	size1=Math.round(size/102.4)/10;
	if (size1<1500) return size1+" KB";
	size1=Math.round(size/1024/102.4)/10;
	return size1+" MB";
}

//Handle Error
function hasError(channel)
{
	var xmlDoc=xmlObj[channel].responseXML;
	if (!xmlDoc || !xmlDoc.hasChildNodes) {
		if (xmlObj[channel].responseText.indexOf("not xml")<=0) {
			alert ("通讯错误!  原因未知");
			return true;
		}else
			return false;
	}
	
	var errornode=xmlDoc.getElementsByTagName("error");
	if (errornode.length>0) {
		errornode=errornode[0];
		var msg=errornode.getElementsByTagName("msg")[0].firstChild.nodeValue;
		alert ("错误!  原因是: "+msg);
		return true;
	}
	var forevernode=xmlDoc.getElementsByTagName("forever");
	if (forevernode.length==0) {
		alert ("通讯错误!  原因未知");
		return true;
	}
	return false;
}

//Popup Window Opener
function openEx(winname,x,y,h,w)
{
	var winnode=document.getElementById(winname);
	if (winnode==null) {
		winnode=document.createElement("div");
		winnode.setAttribute("id",winname);
		with(winnode.style){
			position="absolute";
			backgroundColor="white";
			if (x!=null) left=x+(typeof(x)=="string"?"":"px");
			if (y!=null) top=y+(typeof(y)=="string"?"":"px");
			if (h!=null) height=h+(typeof(h)=="string"?"":"px");
			if (w!=null) width=w+(typeof(w)=="string"?"":"px");
		}
		//winnode.setAttribute("style",stylestr);
		var bodynode=document.body;
		bodynode.appendChild(winnode);
	}

	setOpacity(winnode.style,0.95);
	return winnode;
}

function closeEx(winname)
{
	var winnode=document.getElementById(winname);
	if (!winnode) return;
	var onclose=winnode.onclose;
	if (!onclose || eval(onclose.replace(/%this%/,'winnode'))) {
		var bodynode=document.body;
		bodynode.removeChild(winnode);
	}
}

function updateHTML(winname,html,h,w)
{
	var winnode=document.getElementById(winname);
	if (winnode!=null) {
		html=html.split("%winname%");
		html=html.join(winname);
		winnode.innerHTML=html;
		//winnode.innerHTML=html.replace(/%winname%/,winname);
		if (h!=null) winnode.style.height=h+"px";
		if (w!=null) winnode.style.width=w+"px";
	}
}

function loadTemplate(fname,tplName,callback,errcallback,tpl_ch)
{
	if (tpl_ch!=null) {
		if (hasError(tpl_ch)) {
			setTimeout(errcallback,10);
		}else{
			var html=xmlObj[tpl_ch].responseText;
			html=html.split("%rootdir%");
			html=html.join(rootdir);
			document[tplName]=html;
			setTimeout(callback,10);
		}
		release(tpl_ch);
		return;
	}
	if (!document[tplName]) {
		request(null,rootdir+"template/"+fname,"loadTemplate(null,'"+tplName+"','"+callback+"','"+errcallback+"',%channel%)",errcallback);
	}
}

function useTemplate(tplName,title,content)
{
	var rhtml=document[tplName];
	rhtml=rhtml.replace(/%winhtml%/,content);
	rhtml=rhtml.replace(/%wintitle%/,title);
	return rhtml;
}

//pop windows of iframe type
function openIFrame(src, wintitle, cb_finish)
{
	var winname="pop_iframe"+iframeCount;
	var win=openEx(winname,150,60,null,150);
	if (!document.POPWIN2) {
		win.innerHTML="Loading...";
		//alert("openIFrame('"+src+"','"+winname+"','"+wintitle+"')");
		loadTemplate("popwin2.inc","POPWIN2",'openIFrame("'+src+'","'+wintitle+'","'+cb_finish+'")',"alert(1)");
	}else{
		var rhtml='';
		rhtml+='<iframe id="iframe_%winname%" name="iframe_%winname%" src="'+rootdir+src+'" width="100%" height="400" align="center" border="0" frameborder="0" onload="iframeResize(this)"></iframe>';
		rhtml+='<p align="center" style="margin-top: 0px; margin-bottom: 0px">';
		rhtml+='	<button onclick="doSubmit('+"'%winname%'"+')"><img src="'+rootdir+'image/smallicon/allow.gif" />确定</button>';
		rhtml+='	<button onclick="closeEx('+"'%winname%'"+')"><img src="'+rootdir+'image/smallicon/deny.gif" />取消</button>';
		rhtml+='	<button onclick="toWindow('+"'%winname%'"+')"><img src="'+rootdir+'image/smallicon/tearoff.gif" />新窗口</button>';
		rhtml+='</p>';
		rhtml=useTemplate("POPWIN2",wintitle,rhtml);
		updateHTML(winname,rhtml,null,600);
		win.fMarginH=60;
		floatMove(winname);
		win.onclose="submitClose(%this%)";
		win.onfinish=cb_finish;
		iframeCount++;
	}
}

function submitClose(win)
{
	if (win.hasStarted) {
		return confirm("正在提交更改，确实要取消么？");
	}else {
		return 1;
	}
}

function doSubmit(winname)
{
	var uploadframe=document.getElementById("iframe_"+winname);
	var uploadframewin=window.frames["iframe_"+winname];
	var uploadform=uploadframewin.document.forms[0];
	if (uploadframewin.beforesubmit()) return;

	var uploadwin=openEx(winname,null,null,70,200);
	uploadform.submit();
	uploadframe.style.display='none';
	uploadwin.hasStarted='1';
	
	var para=uploadwin.getElementsByTagName("p")[0];
	var rhtml='';
	rhtml+='	正在提交更改...';
	rhtml+='	<button onclick="closeEx('+"'"+winname+"'"+')">取消</button>';
	open("progress.htm","progress_15forever","menubar=0,location=0,toolbar=0,resizable=1,scrollbars=1,width=400px,height=100px");
	para.innerHTML=rhtml;
}

function submitFinish(winname)
{
	var subDoc=window.frames["iframe_"+winname];
	if (!subDoc) {
		subDoc=open(null,winname);
		if (!subDoc) return;
	}
	subDoc=subDoc.document;
	if (!subDoc) return;
	var win=openEx(winname)
	win.hasStarted=null;
	if (win.onfinish) setTimeout(win.onfinish,100);
	//try{win.progwin.close();}catch(e){;}
	closeEx(winname);
}

function toWindow(winname)
{
	var subFrame=document.getElementById("iframe_"+winname);
	if (!subFrame) return;
	var windiv=openEx(winname);
	if (windiv.hasStarted) {
		alert("正在提交更改，不能打开新窗口");
		return;
	}
	open(subFrame.src,winname,"menubar=0,location=0,toolbar=0,resizable=1,scrollbars=1,width="+windiv.offsetWidth+",height="+windiv.offsetHeight);
	formWin_finish_cb[winname]=windiv.onfinish;
	closeEx(winname);
}

function iframeResize(iframe,iid) {
	if (iid) {
		var pTar=document.getElementById(iid);
		if (!pTar) return;
	}else{
  	var pTar = iframe;
  }
  if (pTar && !window.opera){
    //begin resizing iframe
    
    if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight){
      //ns6 syntax
      var Height=pTar.contentDocument.body.offsetHeight+10;
    	if (Height>430) Height=430;
      pTar.height = Height;
    }else if (pTar.Document && pTar.Document.body.scrollHeight){
      //ie5+ syntax
      var Height=pTar.Document.body.scrollHeight;
    	if (Height>430) Height=430;
      pTar.height = Height;
    }
  }
  setTimeout("iframeResize('','"+iframe.id+"')",500);
}

function setOpacity(s,opc){if (IE) s.filter="alpha(opacity="+parseInt(opc*100)+")"; else s.opacity=opc;}

function showtip(e,cont){
	if (window.delayshow) {
		clearTimeout(delayshow);
	}
	delayshow=setTimeout("showtip1("+e.clientX+","+e.clientY+",'"+cont+"')",300);
}

function showtip1(eventX,eventY,cont){
	if (window.delayhide) clearTimeout(delayhide);
	var menuobj=openEx("poptip",0,0);
	with (menuobj) {
		style.visibility="hidden";
		innerHTML=cont;
		className+=" tip";
		style.backgroundColor="#FFFFE1";
		style.zIndex="1000";
		//setAttribute("onmouseover","hidetip()");
	}
	var contentwidth=menuobj.offsetWidth;
	var contentheight=menuobj.offsetHeight;
	var l=10+(IE? document.body.scrollLeft+eventX : window.pageXOffset+eventX);
	var t=10+(IE? document.body.scrollTop+eventY : window.pageYOffset+eventY);
	if ((l+contentwidth+10)>(IE? document.body.scrollLeft+document.body.parentNode.clientWidth : window.pageXOffset+window.innerWidth)){
		l=(IE? document.body.scrollLeft+document.body.parentNode.clientWidth : window.pageXOffset+window.innerWidth)-contentwidth-10;
	}
	if ((t+contentheight+10)>(IE? document.body.scrollTop+document.body.parentNode.clientHeight : window.pageYOffset+window.innerHeight)){
		t=(IE? document.body.scrollTop+eventY : window.pageYOffset+eventY)-10-contentheight;
	}
	openEx("poptip",l,t);
	delayhide=setTimeout("hidetip()",5300);
	fadein("poptip");
	return false;
}

function hidetip(){closeEx("poptip");if (window.delayshow) clearTimeout(delayshow);delayshow=null;}

function fadein(objname,s)
{
	var obj=document.getElementById(objname);
	if (!obj) return;
	if (IE){
		with (obj.style){
			filter="BlendTrans(duration=0.25)";
			obj.filters[0].apply();
			visibility="visible";
			obj.filters[0].play();
		}
	}else{
		if (!s){
			obj.style.opacity=0;
			obj.style.visibility="visible";
			obj.fading=true;
		}
		if (!obj.fading) return;
		obj.style.opacity=(parseFloat(obj.style.opacity)+0.2).toString();
		if (obj.style.opacity<1) {
			setTimeout("fadein('"+objname+"',1)",50);
		}else{
			obj.fading=false;
		}
}
}

function addSideBar(id,titleID,contentID,addBefore)
{
	var obj=document.getElementById(id);
	if (obj) return obj;
	obj=document.createElement("div");
	var rhtml='<table id="'+id+'" cellpadding="0" cellspacing="0" style="width:100%;border:0px">';
	if (titleID){
		rhtml+='<tr style="text-align:left;"><td class="title2_l"></td>';
    rhtml+='<td class="title2_m" id="'+titleID+'"><span>&nbsp;</span></td>';
    rhtml+='<td class="title2_r"></td></tr>';
	}
	rhtml+='<tr><td colspan="3" class="contentfont" id="'+contentID+'"></td></tr></table>';
	obj.innerHTML=rhtml;

	var pnode=document.getElementById("R-Bottom");
	if (addBefore)
		var bnode=document.getElementById(addBefore);
	if (bnode)
		pnode.insertBefore(obj,bnode);
	else
		pnode.appendChild(obj);
	return obj;
}

function delElement(id)
{
	var obj=document.getElementById(id);
	if (!obj) return;
	obj.parentNode.removeChild(obj);
}

function floatMove(id)
{
	var obj=document.getElementById(id);
	if (!obj) return;
	var fRWidth = obj.offsetWidth;
	var fRHeight = obj.offsetHeight;

	var fVAlign = obj.fVAlign;
	var fMarginH = obj.fMarginH;
	var fMarginW = obj.fMarginW;
	var tmp=(document.body.scrollTop?document.body.scrollTop:document.documentElement.scrollTop);
	if(!IE){
		if(fVAlign==1)
			obj.style.top=tmp+((document.body.clientHeight>document.documentElement.clientHeight)?document.documentElement.clientHeight:document.body.clientHeight)-fRHeight-fMarginH+'px';
		else
			obj.style.top=tmp+fMarginH+'px';
		if (fMarginW) obj.style.left=((document.body.clientWidth>document.documentElement.clientWidth)?document.body.clientWidth:document.documentElement.clientWidth)-fRWidth-fMarginW+'px';
	}else{
		if(fVAlign==1)
			obj.style.top=tmp+((document.documentElement.clientHeight==0)?document.body.clientHeight:document.documentElement.clientHeight)-fRHeight-fMarginH+'px';
		else
			obj.style.top=tmp+fMarginH+'px';
		if (fMarginW) obj.style.left=((document.documentElement.clientWidth==0)?document.body.clientWidth:document.documentElement.clientWidth)-fRWidth-fMarginW+'px';
	}
	setTimeout("floatMove('"+id+"')",300);
}

function imageSize(size,width,ratio)
{
	size["w"]=parseInt(size["w"]);
	size["h"]=parseInt(size["h"]);
	if (size["w"]*size["h"]==0) return;
	if (size["h"]/size["w"]<ratio) {
		size["h"]=size["h"]/size["w"]*width;
		size["w"]=width;
	}else{
		size["w"]=size["w"]/size["h"]*width*ratio;
		size["h"]=width*ratio;
	}
}

function xmlToText(str,len){
	if (!len) len=45;
	var r=str;
	r=r.replace(/====[^=]([^\x00])*=====/ig,"");
	r=r.replace(/<img([^>^<])*>/ig,"(图)");
	r=r.replace(/<[^>^<]*>/g,"");
	if (r.length>len) {
		r=r.substring(0,len-3) + "...";
	}
	return r;
}
//============End of Common=======
