//-----------------------档期获取类---------------------------
// version 1.7 Beta
//------------------------------------------------------------
  function archiveLoader(cacheName,sortBy){
 	 this.cacheName = "sign"; 
 	 this.sortBy = "desc";
 	 this.dataURL = "";//数据获取地址,必须定义,否则无法获取数据
 	 this.precision = false;
 	 this.firstArchive = -1;
 	 this.lastArchive = -1;
 	 
 	 this.maxArchive = 0;
 	 this.loadKeyWord = "";
 	 this.pageSize = 13;
 	 
 	 //翻页游标
 	 this.cursorAsc = 0;
 	 this.cursorDesc = 0;
 	 this.cPageAsc = 1;
 	 this.cPageDesc = 1;
 	 this.page = 1;
 	 
 	 this.direct = 0;
 	 this.totalMsg = 0;
 	 this.reloadCounter = 3;
  	 this.reload = this.reloadCounter;
	 this.length = 0;
	 this.debug=null;
 
  }
  
  archiveLoader.prototype.init = function(direct){//初始化数据
	 this.direct = 0;
	 if (this.loadFromCache()) {if (!direct) this.doTurnPage(1); else {this.direct=1;this.doTurnPage(1);}} else {
		 if (!direct)
		      this.doTurnArchive(this.firstArchive,true);
		  else {
		      //反向翻页初始化，必须保证逆向也可以获取最大档期值，否则无法翻页
		  	  this.direct=1;
			  this.doTurnArchive(this.lastArchive,true);
		  }
	 }
  }
  
  archiveLoader.prototype.getDom = function (){
  	  return top.g_XDoc["aLoader"][this.cacheName];
  }
  
  archiveLoader.prototype.saveToCache = function (){
  	 var cacheName = this.cacheName;
  	 top.g_XDoc["aLoader"][cacheName + "_totalMsg"]=this.totalMsg;
 	 top.g_XDoc["aLoader"][cacheName + "_cursorAsc"]=this.cursorAsc;
  	 top.g_XDoc["aLoader"][cacheName + "_cursorDesc"]=this.cursorDesc;
  	 top.g_XDoc["aLoader"][cacheName + "_maxArchive"]=this.maxArchive;
  }
  
  archiveLoader.prototype.loadFromCache = function (){
  	 var cacheName = this.cacheName;
 	 if (!top.g_XDoc["aLoader"]) {top.g_XDoc["aLoader"]=[];top.g_XDoc["aLoader"][cacheName]=null;return false}//建立cache空间 aLoader -> archiveLoader
 	 top.g_XDoc["aLoader"][cacheName] = (top.g_XDoc["aLoader"][cacheName])?top.g_XDoc["aLoader"][cacheName]:null;
 	 if (!top.g_XDoc["aLoader"][cacheName]) return false;
  	 this.cursorAsc = top.g_XDoc["aLoader"][cacheName + "_cursorAsc"];
  	 this.cursorDesc = top.g_XDoc["aLoader"][cacheName + "_cursorDesc"];
  	 this.maxArchive = top.g_XDoc["aLoader"][cacheName + "_maxArchive"];
	 this.length = top.g_XDoc["aLoader"][cacheName].selectNodes("//item").length;
  	 this.totalMsg = top.g_XDoc["aLoader"][cacheName + "_totalMsg"];
 	 return true;
  }
  
  archiveLoader.prototype.clearCache = function (){
  	 var cacheName = this.cacheName;
 	 this.cursorAsc = 0;this.cursorDesc = 0; this.cPageAsc = 1; this.cPageDesc = 1;
  	 top.g_XDoc["aLoader"][cacheName]=null;
  	 top.g_XDoc["aLoader"][cacheName + "_keyWord"]=null;
  	 top.g_XDoc["aLoader"][cacheName + "_cursorAsc"]=null;
  	 top.g_XDoc["aLoader"][cacheName + "_cursorDesc"]=null;
  	 top.g_XDoc["aLoader"][cacheName + "_maxArchive"]=null;
  	 CollectGarbage();
  }

  archiveLoader.prototype.turnArchive = function (flag){
    if (!this.maxArchive) return;
    if (flag) {
	    if ((this.getCursorLen())<=1) {cPage = (!this.direct)?this.cPageAsc:this.cPageDesc;this.doTurnPage(cPage);return;}
	    this.reload--;
		if (this.reload<=0) {cPage = (!this.direct)?this.cPageAsc:this.cPageDesc;this.doTurnPage(cPage);return;}
	}
	
    if (!this.direct) {
	    if (this.sortBy=="desc") {
		    this.cursorAsc--; 
	    }
	    else {
		    this.cursorAsc++;
		    if (this.cursorAsc>=this.maxArchive) {this.doTurnArchive(this.lastArchive,flag);return}
	    }
	    this.doTurnArchive(this.cursorAsc,flag);
    }
    else{
	    if (this.sortBy=="desc") {
		    this.cursorDesc++;
	    }
	     else {
		     this.cursorDesc--;
		     if (this.cursorDesc>=this.maxArchive) {this.doTurnArchive(this.lastArchive,flag);return}
	    }
	    this.doTurnArchive(this.cursorDesc,flag);
    }
  }
 
  archiveLoader.prototype.doTurnArchive = function(a,flag){//获取档期数据
	showOpratingMsg();
	var url = this.dataURL + a;
	var me = this;
    top.LoadXMLDataEx("aLoader_temp",url,
				function(){me.buildArchive(flag);},
                function(){hideOpratingMsg();try{alertSendDataFail();top.guideButton(1)}catch(e){}}
             );
  }
  
  archiveLoader.prototype.buildArchive = function(flag){//构造数据cache
    var cacheName = this.cacheName;
	if(top.g_XDoc["aLoader_temp"].selectSingleNode("/error")){
		showOpratingMsg(top.g_XDoc["aLoader_temp"].selectSingleNode("/error").text);
		top.g_XDoc["aLoader_temp"]=null;
		opratingMsgTimeout = setTimeout(function(){hideOpratingMsg();},1500);
		return;
	}
	if (this.precision) this.totalMsg = top.g_XDoc["aLoader_temp"].selectSingleNode("/rss").firstChild.getAttribute("count").toInt();
  	if (!top.g_XDoc["aLoader"][cacheName]) {//初始化数据
		 if (this.loadKeyWord.length>0) this.setKeyWord(top.g_XDoc["aLoader_temp"]);
		 var archive = this.maxArchive = top.g_XDoc["aLoader_temp"].selectSingleNode("/rss").firstChild.getAttribute("archive").toInt();
  	     if (this.maxArchive<0) {this.maxArchive=1;archive=1;} else this.maxArchive++;
  	  	 top.g_XDoc["aLoader"][cacheName] = parseXML('<rss version="2.0" msgCount="' + this.totalMsg + '" maxArchive="' + this.maxArchive + '"></rss>');
		 if (this.sortBy == "desc") this.cursorAsc = archive; else this.cursorDesc = this.maxArchive + 1
		 if (this.sortBy == "desc" && top.g_XDoc["aLoader_temp"].selectNodes("//item").length == 0) this.cursorDesc = this.maxArchive;
	}
	
	var reDo = [];
	for (var i=0;i<top.g_XDoc["aLoader_temp"].selectNodes("//item").length;i++) {
		archive = top.g_XDoc["aLoader_temp"].selectNodes("//item")[i].getAttribute("archive").toInt();
   		if (archive<=0) archive = this.maxArchive;
 		if (!reDo[archive]) {this.createChannel(archive,flag);reDo[archive]=true;} //cache中不存在档期则自动创建
		top.g_XDoc["aLoader"][cacheName].selectSingleNode("//channel[@archive="+archive+"]").appendChild(top.g_XDoc["aLoader_temp"].selectNodes("//item")[i].cloneNode(true));
	}
	
	this.length = top.g_XDoc["aLoader"][cacheName].selectNodes("//item").length;
	
  	top.g_XDoc["aLoader_temp"] = null;
  	this.saveToCache(); //基本信息保存到cache
  	if (flag) {if (this.targetPage) this.doTurnPage(this.targetPage); else {cPage = (!this.direct)?this.cPageAsc:this.cPageDesc;this.doTurnPage(cPage)};}
  	hideOpratingMsg();
 	this.onbuildArchive(flag);
  }
  
  archiveLoader.prototype.setKeyWord = function(Dom){//保存其它关键字段
	 var cacheName = this.cacheName;
     if (!top.g_XDoc["aLoader"][cacheName + "_keyWord"]) top.g_XDoc["aLoader"][cacheName + "_keyWord"] = [];
     var keys = this.loadKeyWord.split(",");
     for (var i=0;i<keys.length;i++) {
	     top.g_XDoc["aLoader"][cacheName + "_keyWord"][keys[i]] = Dom.selectSingleNode("//" + keys[i]);
     }
  }
  
  archiveLoader.prototype.getKeyWord = function(key){//获取其它关键字段
     return top.g_XDoc["aLoader"][this.cacheName + "_keyWord"][key]
  }
  
  archiveLoader.prototype.firstPage = function(){//返回第一页
    this.direct = 0; this.cPageAsc = 1;	this.doTurnPage(this.cPageAsc);
  }
  
  archiveLoader.prototype.lastPage = function(){//返回最后页
    this.direct = 1; this.cPageDesc = 1;this.doTurnPage(this.cPageDesc);
  }
  
  archiveLoader.prototype.turnPage = function(flag){//翻页
  	if (!this.direct) this.doTurnPage(flag-(-this.cPageAsc)); else this.doTurnPage(this.cPageDesc - flag);
  }
  
  archiveLoader.prototype.removeArchive = function (archive) {
  	 if (!top.g_XDoc["aLoader"][this.cacheName]) return;
  	 if ((archive-0)==0) archive = this.maxArchive;
  	 var targetArchive = top.g_XDoc["aLoader"][this.cacheName].selectSingleNode("//channel[@archive="+archive+"]")
  	 if (targetArchive) targetArchive.parentNode.removeChild(targetArchive);
  }
  
  archiveLoader.prototype.doTurnPage = function(pageNum){//执行翻页
		//判断是否需要从数据库读取档期
  		this.targetPage = pageNum;
	    if (!this.direct) {
	  		var sortFlag = (this.sortBy == "desc")?">=":"<=";
		  	var itemLength = top.g_XDoc["aLoader"][this.cacheName].selectNodes("//channel[@archive"+ sortFlag + this.cursorAsc + "]/item").length
		  	if ((itemLength-(pageNum-1)*this.pageSize)<this.pageSize && (this.getCursorLen())>1 && this.reload>0) {this.turnArchive(true);return}
		}
		else{
	  		var sortFlag = (this.sortBy == "desc")?"<=":">=";
		  	var itemLength = top.g_XDoc["aLoader"][this.cacheName].selectNodes("//channel[@archive" + sortFlag + this.cursorDesc + "]/item").length
		  	var lastItemLength = (!this.totalMsg)?this.pageSize:((!(this.totalMsg % this.pageSize))?this.pageSize:(this.totalMsg % this.pageSize));  //this.totalMsg % this.pageSize <- 除非可以确保数据精确才使用
		  	if (((pageNum - 1)*this.pageSize + lastItemLength)>itemLength && (this.getCursorLen())>1 && this.reload>0) {this.turnArchive(true);return}
		}
    if (pageNum<=0) pageNum = 1;
	
	if ((this.getCursorLen())<=1) {
        this.cPageAsc = 1;
		var itemLength = this.totalMsg = this.length = top.g_XDoc["aLoader"][this.cacheName].selectNodes("//item").length;
		var totalPage = Math.ceil(this.length/this.pageSize);
		if (!totalPage) totalPage=1;
		if (pageNum>totalPage) pageNum = totalPage;
		if (this.direct) {pageNum=Math.ceil(this.totalMsg/this.pageSize)-pageNum+1}
		this.direct = 0;
	}
	
	if (this.totalMsg) this.page = (!this.direct)?pageNum:(Math.ceil(this.totalMsg/this.pageSize)-pageNum+1);
    
	if (!this.direct) this.cPageAsc=pageNum; else this.cPageDesc=pageNum;
	this.reload = this.reloadCounter;
	this.targetPage = 0;
	var pageListDom =parseXML('<rss version="2.0"><channel></channel></rss>');
 	var fillRoot = pageListDom.selectSingleNode("/rss/channel");
	if (!this.direct) { //正向翻页
		 for (var i=0;i<this.pageSize;i++){
	 	 	 if ((i+(this.cPageAsc-1)*this.pageSize)>=itemLength) break;
	 	 	 var item = top.g_XDoc["aLoader"][this.cacheName].selectNodes("//item")[(i+(this.cPageAsc-1)*this.pageSize)].cloneNode(true);
		 	 fillRoot.appendChild(item);
	 	 }
	 	 
	}
	else{ //反向翻页
	     var startPoint = (this.cPageDesc - 1)*this.pageSize + lastItemLength;
	     var stopPoint = (this.cPageDesc -2)*this.pageSize + lastItemLength;
	     if (stopPoint<0) stopPoint = 0;
		 for (var i=startPoint;i>stopPoint;i--){
	 	 	 var item = top.g_XDoc["aLoader"][this.cacheName].selectNodes("//item")[this.length - i].cloneNode(true);
		 	 fillRoot.appendChild(item);
	 	 }
	}
	
	this.onchange(pageListDom);
  }
  
  archiveLoader.prototype.getCursorLen = function() {
  	  if (this.sortBy == "desc") return this.cursorAsc - this.cursorDesc; else return this.cursorDesc - this.cursorAsc
  }
  	  
  archiveLoader.prototype.createChannel = function(archive,flag){//创建档期
  		(channelNode=top.g_XDoc["aLoader"][this.cacheName].createElement("channel")).setAttribute("archive",archive);
	    if (flag) {if (!this.direct) this.cursorAsc = archive; else this.cursorDesc = archive;}
 		this.insertChannel(channelNode);
  }
  
  archiveLoader.prototype.insertChannel = function(channelDom){//往cache中按顺序插入档期
     var cacheName = this.cacheName;
  	 var archive = channelDom.getAttribute("archive")
     if (!top.g_XDoc["aLoader"][cacheName].selectSingleNode("//channel[@archive="+archive+"]")) 
	     {
		    var insertChild = null;
			for (var i=top.g_XDoc["aLoader"][cacheName].selectNodes("//channel").length-1;i>=0 ;i--)
			{   
			    var cArchive = top.g_XDoc["aLoader"][cacheName].selectNodes("//channel")[i].getAttribute("archive").toInt();
			    if ((this.sortBy=="desc" && cArchive > archive) || (this.sortBy!="desc" && cArchive < archive))
				{
				  top.g_XDoc["aLoader"][cacheName].selectSingleNode("/rss").insertBefore(channelDom,insertChild);return;
				}
				insertChild = top.g_XDoc["aLoader"][cacheName].selectSingleNode("//channel[@archive=" + cArchive + "]")
			}
			top.g_XDoc["aLoader"][cacheName].selectSingleNode("/rss").insertBefore(channelDom,insertChild)
	     }
     else {
     	 var oChild = top.g_XDoc["aLoader"][cacheName].selectSingleNode("//channel[@archive="+archive+"]")
		 top.g_XDoc["aLoader"][cacheName].selectSingleNode("/rss").replaceChild(channelDom,oChild);
     }
   }
   
  
  archiveLoader.prototype.doDebug = function(str){
  	try{this.debug=document.getElementById("debugText")}catch(e){}
    if (!this.debug) {
    	this.debug = document.createElement("div");
    	this.debug.id="debugText"
     	this.debug.style.cssText="font-size:12px;border:1px solid #999;background:#fff;height:60px;width:300px;z-index:999;filter:aphla()"
	   	document.appendChild(this.debug);
	   	this.debug.appendChild(document.createElement("<textarea style='padding:3px;width:100%;height:99%;border-width:0px'></textarea>"));
	   	this.debug.appendChild(document.createElement("<div style='padding:2px;border-top:1px solid #999;background:#e5e5e5;text-align:right'></div>"));
	   	this.debug.childNodes[1].innerHTML="<button onclick='top.g_XDoc[\"aLoader\"]=[];location.reload()'>clear Cache</button> "
	   	this.debug.childNodes[1].innerHTML+=" <button onclick='document.getElementById(\"debugText\").childNodes[0].value=\"\"'>clear</button> "
	   	this.debug.childNodes[1].innerHTML+=" <button onclick='document.getElementById(\"debugText\").style.display=\"none\"'>close</button> "
	   	this.debug.count=0;
    }
    this.debug.childNodes[0].value = this.debug.count + " : " + str + "\n" + this.debug.childNodes[0].value;
    this.debug.count++;
  }
 
 

  archiveLoader.prototype.onchange = function(){}
  archiveLoader.prototype.onbuildArchive = function(){}
  String.prototype.toInt=function(){return parseInt(this,10)}//取整