/**
 * 云南信息港---首页异步获取新闻内容的AJAX js
 * author:Yninfo-KeepWatcher
 */

//定义内容块缓存
var contentCache = new Object();

var tempref;
var timeOut = 250;
var waitInterval;

/**
 * 根据id获取Element
 * @id
 * return 返回Element节点对象
 */
function getElement(id) {
	return (document.getElementById) ? document.getElementById(id): document.all[id];
}

/**
 * 创建http请求
 */
function getXmlhttp(){
	var http_request;
	
	if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType("text/xml");
		}
	}else {
		if (window.ActiveXObject){
			try {
				http_request = new ActiveXObject("Msxml2.XMLHTTP");
			}catch(e) {
				try {
					http_request = new ActiveXObject("Microsoft.XMLHTTP");
				}catch(e){}
			}
		}
	}
	
	if (!http_request) {
		window.alert("can't create XMLHttpRequest object.");
		return null;
	}
	
	return http_request;
}


//JavaScript gb2utf8 转码函数
function gb2utf8(data){
   var glbEncode = [];
   gb2utf8_data = data;
   execScript("gb2utf8_data = MidB(gb2utf8_data, 1)", "VBScript");
   var t=escape(gb2utf8_data).replace(/%u/g,"").replace(/(.{2})(.{2})/g,"%$2%$1").replace(/%([A-Z].)%(.{2})/g,"@$1$2");
   t=t.split("@");
   var i=0,j=t.length,k;
   while(++i<j) {
       k=t[i].substring(0,4);
       if(!glbEncode[k]) {
           gb2utf8_char = eval("0x"+k);
           execScript("gb2utf8_char = Chr(gb2utf8_char)", "VBScript");
           glbEncode[k]=escape(gb2utf8_char).substring(1,6);
       }
       t[i]=glbEncode[k]+t[i].substring(4);
   }
   gb2utf8_data = gb2utf8_char = null;
   return unescape(t.join("%"));
}

//创建请求
function CreateXMLHttpRequest() {
 xmlhttp=false;
 if(window.XMLHttpRequest) {
       xmlhttp=new XMLHttpRequest();
       if (xmlhttp.overrideMimeType) {
          xmlhttp.overrideMimeType('text/xml');
       }
 } else if(window.ActiveXObject) {
       try{
            xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
       } catch(e) {
            try{
               xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) { }
       }
    }
}

//获得数据
function getHttp(ObjUrl){
	
	//定义内容块缓存
    var ContentCache = new Object();
	if (ContentCache[ObjUrl] == null){
	    CreateXMLHttpRequest();
        if(!xmlhttp) {
		    alert("对不起,服务器有故障,不能传送数据!");
            return ("服务器有故障,不能传送数据!");
        } 
	    else{
            //xmlhttp.onreadystatechange=process;
            //xmlhttp.open('post',URL,false);
		    xmlhttp.Open("GET",ObjUrl, false);
            //xmlhttp.send(null);
            xmlhttp.send();
			ContentCache[ObjUrl]=xmlhttp.responseBody;
		    return gb2utf8(xmlhttp.responseBody);
		}   
	}
	else{
		return gb2utf8(ContentCache[ObjUrl]);
	}
}


/**
 * 根据url获取内容并填充到id为contentId的div中
 * @url 需要获取内容的url
 * @contentId 需要填充内容的div id
 */
function loadContentFromId(url,contentId) {
	var ocontent = document.getElementById(contentId);
	if (contentCache[url] == null) {
		var xhttp=getXmlhttp();
			xhttp.onreadystatechange=function() {
				if (xhttp.readyState == 4 && (xhttp.status == 200 || window.location.href.indexOf("http")==-1)) {
                    var rt = xhttp.responseBody;
					ocontent.innerHTML=gb2utf8(rt);
					//ocontent.innerHTML=xhttp.responseText;
					contentCache[url]=ocontent.innerHTML;
				}
			}
		var getUrl = url + "?timeStamp=" + new Date().getTime();
		xhttp.open("GET",getUrl,true);
		xhttp.send(null);
	}else{
		ocontent.innerHTML=contentCache[url];
	}
}

function loadContentFromId_Stone(StoneDate,contentId) {
	var ocontent = document.getElementById(contentId);
	ocontent.innerHTML = StoneDate;
}

/**
 * 根据传入的css classname获取替换后的css classname
 * 本方法需与css文件配合使用
 * 如原classname为activeW1，则替换后为normalW1
 * @str 当前的css classname
 * @sta 将其中某部分内容替换的目的字符串
 */
function getPrefixName(str,sta){
	if(str.indexOf("active")!=-1 || str.indexOf("normal")!=-1) str=str.substr(6);
		else if(str.indexOf("over")!=-1) str=str.substr(4);
			else str="";
	return sta+str;
}

/**
 * 根据contentId初始化div
 * 对名为contentId的div下的所有li元素进行初始化
 * 包括设置其活动状态，读取其内容以及实现其onmouseover以及onmouseout事件
 * @contentId 需要初始化的div内容块的id
 * @defaultNewsUrl 需要作为初始内容出现在内容块中的url
 *
 */
function initContent(contentId,defaultNewsUrl,cookieName) {
	var obj = getElement(contentId);
	var lists = obj.getElementsByTagName("li");
	
	var isInit = false;
	var listCount = 0;
	var firstList;
	var firstListUrl = "";
	var firstListTarget = "";
	
	for (var i=0; i<lists.length; i++) {
		var list;
		var listlink;
		var listurl;
		var listtarget;

		list = lists[i];
		
		if (list.parentNode.parentNode != obj){
			continue;
		}
		
		if (list.getElementsByTagName("a").length==0){
			continue;
		}
		
		listCount++;
		
		listlink = list.getElementsByTagName("a")[0];
		//需要读取的url
		listurl = listlink.getAttribute("urn");
		//填充的目标div
		listtarget = listlink.getAttribute("rel");

		if (firstListUrl == "") {
			firstList = lists[i];
			firstListUrl = listlink.getAttribute("urn");
			firstListTarget = listlink.getAttribute("rel");
		}

		//设置li活动状态的方法，通过调用getPrefixName方法改变其样式
		list.setActive=function(a) {
			if (a) {
				this.status="active";
				this.className=getPrefixName(this.className,"active");
			} else {
				this.status="normal";
				this.className=getPrefixName(this.className,"normal");
			}
		}
		
		//li方法:根据urn读取内容填充进入rel元素
		list.loadTabContent=function() {
			if (this.parentNode.parentNode.activetab!=undefined){
				this.parentNode.parentNode.activetab.setActive(false);
			}
			this.parentNode.parentNode.activetab=this;
			this.setActive(true);
			//注：此处需注意，由于listlink值在最后会变化
			//因此该方法只能再次使用getElementsByTagName("a")方法来获取当前li中的a标签信息	
			var ulistlink=this.getElementsByTagName("a")[0];
			loadContentFromId(ulistlink.getAttribute("urn"),ulistlink.getAttribute("rel"));
		}
		
		//onmouseover事件实现
		list.onmouseover=function() {
			//alert(this.status);
			if (this.status == "active") {
				return;
			}else {
				tempref = this;
				clearTimeout(waitInterval);
				waitInterval = window.setTimeout("tempref.loadTabContent()",timeOut);
				//tempref.loadTabContent();
			}
			//setCookie("subscibe_" + this.parentNode.parentNode.id,this.getElementsByTagName("a")[0].getAttribute("urn"));
		}

		//onmouseout事件实现
		list.onmouseout=function() {
			clearTimeout(waitInterval);
			if (this.status == "normal")
				return;
			//this.setActive(false);
		}
		
		//当该li为初始内容时，则从其url中读取内容填充进入div
		if (listurl.indexOf(defaultNewsUrl) != -1) {
			list.setActive(true);
			obj.activetab=list;
			isInit = true;
			loadContentFromId(listurl,listtarget);
		}else {
			list.setActive(false);
		}
		
	}
		
	if (isInit == false && listCount>0 && firstListUrl!="") {
		setCookie(cookieName,firstListUrl);
		firstList.loadTabContent();
		//loadContentFromId(firstListUrl,firstListTarget);	
		//initContent(contentId,firstListUrl,cookieName);
	}
}

//读取XML文件数据生成文章列表
//stone.ke@163.com
/*
  XMLUrl-----------数据源文件
  TopNum-----------显示的记录数
  PageNum----------每页显示的记录数
  LineNum----------列数
  TitleNum---------标题显示字数
  TimeInterval-----更新服务器数据的间隔时间，单位为小时
  MapStatus--------是否显示页码控制地图，1-显示，0-不显示，X-不显示
*/

function ReadXML(XMLUrl,RefreshUrl,TopNum,PageNum,LineNum,TitleNum,TimeInterval,MapStatus){

   var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
   var SelfURL = window.location.href;
   
   //定义内容块缓存
   var XMLContentCache=new Object();

   
   
   xmlDoc.async=false;
   //xmlDoc.async=true;
   //if (XMLContentCache[XMLUrl]==null){
   //	xmlDoc.load(XMLUrl);
   //   XMLContentCache[XMLUrl]=
   //}
   //else{
   //   xmlDoc.load(XMLContentCache[XMLUrl]);
   //}
   xmlDoc.load(XMLUrl);
   
   node = xmlDoc.selectNodes("//YnxjData/YnxjArticle/Article");
   TimeNode=xmlDoc.selectNodes("//YnxjData/CreateTime");
   var CreateTime=new Date(TimeNode[0].text.replace("-","/").replace("-","/"));
   var NowDate=new Date();
   var TimeDiff=parseInt((NowDate.getTime()-CreateTime.getTime())/3600/1000);
   //document.write(TimeDiff);
   
   var Num=0,ArticleTitle,TailStr,ObjURL,Page,PageTotalNum,StartID,EndID,RsNum;
   var adNum = node.length;
   var ListStr="";
   var ListStr1="<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr><td><table cellpadding='0' cellspacing='0' border='0' width='100%'>";
   var ListStr2="</table></td></tr>";
   var ListStr3="</table>";
   
   
   //获得不带参数的页面地址
   if (SelfURL.lastIndexOf("?")==-1){
   	   ObjURL=SelfURL;
	   Page=1;
   }
   else{
   	   ObjURL=SelfURL.substring(0,SelfURL.lastIndexOf("?"));
   	   Page=Request("Page",SelfURL);
   }
   
   
   //判断是否更新远程XML数据
   try {
   if (TimeDiff>=TimeInterval){
       //return "远程数据更新中…";
	   if (getHttp(RefreshUrl)=="stone"){
		   location.href=ObjURL;
		   //break;
	   }
   }
   }
   catch(e){}
   
   //计算总的记录数和页数
   if (TopNum=="" || TopNum>=adNum){
       if (parseInt(adNum/PageNum)==(adNum/PageNum)){
	       PageTotalNum=parseInt(adNum/PageNum);
	   }
	   else{
		   PageTotalNum=parseInt(adNum/PageNum)+1;
	   }
	   RsNum=adNum;
   }
   else{
       if (parseInt(TopNum/PageNum)==(TopNum/PageNum)){
	       PageTotalNum=parseInt(TopNum/PageNum);
	   }

	   else{
	       PageTotalNum=parseInt(TopNum/PageNum)+1;
	   }
	   
	   RsNum=TopNum;
   }
   
   
   //处理传回来的页次参数
   if (Page>PageTotalNum){
       Page=PageTotalNum;
	   location.href=ObjURL+"?Page="+Page;
   }
   else if(Page<1){
       Page=1;  
	   location.href=ObjURL+"?Page=1";
   }
   else if(Page>=1 && Page<=PageTotalNum){
       Page=Page;
   }
   else{
       Page=1; 
	   location.href=ObjURL+"?Page=1";
   }
   
   //计算记录列表的起始ID和结束ID及得出页码地图
   if (Page>1 && Page<PageTotalNum){
	   StartID=PageNum*(Page-1);
	   EndID=Page*PageNum;
       PageMap="<tr><td align='right'>更新时间："+CreateTime+" 合计："+RsNum+" 条记录 "+PageNum+"条/页 页次："+Page+"/"+PageTotalNum+" <a href='"+ObjURL+"?Page="+(parseInt(Page)-1)+"'>上一页</a>|<a href='"+ObjURL+"?Page="+(parseInt(Page)+1)+"'>下一页</a></td></tr>";
   }
   else if (Page==PageTotalNum){
	   StartID=(Page-1)*PageNum;
	   EndID=RsNum;
       PageMap="<tr><td align='right'>更新时间："+CreateTime+" 合计："+RsNum+" 条记录 "+PageNum+"条/页 页次："+Page+"/"+PageTotalNum+" <a href='"+ObjURL+"?Page="+(parseInt(Page)-1)+"'>上一页</a></td></tr>";
   }
   else if (Page==1){
	   StartID=0;
	   //if (Top)
	   EndID=PageNum;
       PageMap="<tr><td align='right'>更新时间："+CreateTime+" 合计："+RsNum+" 条记录 "+PageNum+"条/页 页次："+Page+"/"+PageTotalNum+" <a href='"+ObjURL+"?Page="+(parseInt(Page)+1)+"'>下一页</a></td></tr>";
   }
   else{
	   StartID=0;
	   EndID=PageNum;
       PageMap="<tr><td align='right'>更新时间："+CreateTime+" 合计："+RsNum+" 条记录 "+PageNum+"条/页 页次："+Page+"/"+PageTotalNum+" <a href='"+ObjURL+"?Page="+(parseInt(Page)+1)+"'>下一页</a></td></tr>";
   }
   
   //输出记录列表
   var n=1;
   for(i=StartID;i<EndID;i++)
   {
      ArticleTitle=node[i].childNodes[0].text;
	  
	  //对标题进行处理
	  if (TitleNum>ArticleTitle.length){
	      TailStr="";
	  }
	  else{
	      TailStr="…";
	  }
	  
	  //输出<tr>
	  if (n==1 && (n%LineNum)==1){
	     ListStr="<tr>";
	  }
	  
	  ListStr=ListStr+"<td align='left' title='"+ArticleTitle+"'>·<a href='"+node[i].childNodes[1].text+"' target='_blank'>"+ArticleTitle.substring(0,TitleNum)+TailStr+"</a></td>";
	  //ListStr=ListStr+"<tr><td align='left'>·"+n+"<a href='"+node[i].childNodes[1].text+"' target='_blank'>"+ArticleTitle.substring(0,TitleNum)+TailStr+"</a></td></tr>";
	  
	  //输出</tr>
	  if ((n%LineNum)==0){
          ListStr=ListStr+"</tr>";
	  }
	  
	  n++;
	  
   }
   
   //输出页码控制地图
   if (MapStatus==1){
      PageMapStr=PageMap;
   }
   else{
      PageMapStr="";
   }
   
   //返回最终结果
   return ListStr1+ListStr+ListStr2+PageMapStr+ListStr3;
   
}   

window.onerror=function(){return true}
