/**
 * HTML文件内容获取对象（新版），用于获取远程链接的HTML内容
 */

//该对象把需要获取的HTML链接储存到一个数组中，一个一个获取，获取完一个后执行相应的操作函数再去获取下一个
function XHConn2()
{
  var xh = false;
  try { xh = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xh = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xh = new XMLHttpRequest(); }
  catch (e) { xh = false; }}}
  if (!xh) return null;
  
  this.xmlhttp = xh;
	
	this.jobs = [];
	this.jobIndex = -1;
	
	this.ready = true;
	
  return this;
}

//为了保持XHConn2对象的唯一性，请使用getXHConn2()函数获得该对象
var xhConn2_instance = null; 
function getXHConn2(){
	if(xhConn2_instance == null) xhConn2_instance = new XHConn2();
	return xhConn2_instance;
}

//链接获取作业对象
//其中fnDone是操作函数，形式是fnDone(xmlHttp){}
function XHConnJob(fnDone, sURL, sEncoding, sMethod, sVars){
	this.doneFunction = fnDone;
	this.url = sURL;
	this.encoding = sEncoding;
	this.method = sMethod;
	this.vars = sVars;
	
	this.connection = null; //point to a XHConn object
	
	if(!this.method || this.method.toUpperCase() != "POST"){
		this.method = "GET";
	}
	
  return this;
}


//增加一个链接获取作业
XHConn2.prototype.addJob = function(fnDone, sURL, sEncoding, sMethod, sVars){
  if (!this.xmlhttp) return false;
	
	if(this.jobIndex >= this.jobs.length){
		this.jobs = [];
		this.jobIndex = -1;
	}
	
  var job = new XHConnJob(fnDone, sURL, sEncoding, sMethod, sVars);
	job.connection = this;
	this.jobs[this.jobs.length] = job;
  return true;
};


//开始获取
XHConn2.prototype.start = function(){
  if(!this.ready) return false;		//running
  if(!this.xmlhttp) return false;
	if(this.jobs.length == 0) return false;  //no job
	if(this.jobIndex >= this.jobs.length) return false;  //jobs done
  var xh = this.xmlhttp;
	
	
	this.jobIndex++;
	var job = this.jobs[this.jobIndex];
	if(!job || !job.url || job.url == ""){
		this.ready = true;
    this.start(); //next job
    return false;
	}
	
	this.ready = false;  //start tag
	try{
		xh.open(job.method, job.url, true);
		
    if (!job.encoding){   
        xh.setRequestHeader("Content-Type", "text/xml");   
    }else{   
        xh.setRequestHeader("Content-Type", "text/xml; charset=" + job.encoding);   
    }
    
		xh.onreadystatechange = function(){
      if (xh.readyState == 4){
				job.doneFunction(xh);
				job.connection.ready = true;    //job done, change the state tag
				job.connection.start();
      }
    };
		
		//todo: job.vars
    xh.send(job.vars);
  } catch(z) {
		job.doneFunction(null);
		this.ready = true;
		this.start();
    return false;
  }
  return true;
}

