
/*
 * 2006-5-31
 * 
 * 一个table的类,目前主要作用是配合dwr页面表格的数据。与表格的数据同步
 * 操作的时候不需要从页面取而直接操作已有的数据对象
 * 
 * 主要属性:	data--表格数据是一个array,每个元素为一个row,有一个状态标志,_ordPos
 * 			deleteRows--删除掉的行
 * 			addRows--新增的行
 * 			updateRows--修改过的行
 * 主要方法:	getRow(index)--取某一行
 * 			addRow(dto)--增加一行到data
 * 			deleteRow(index)--删除一行
 * 			updateRow(index,dto)--更新
 * 使用方法:	table = new Table(data);--页面初始化载入数据
 * 			table.addRow(dto)--新增数据...
 * 
 */
 
function Table(data){
	if(data == null)
		data = new Array();
 	this.data = data;
 	
 	this.deleteRows = new Array();
 	this.addRows = new Array();
 	this.updateRows = new Array();
 	
 	this.getRow = function(index){
 		if(index>=this.size()||index<0)
 			return null;
 		return data[index];
 	};
 	
 	this.addRow = function(dto){
 		this.data.splice(0,0,dto);
 		this.addRows.splice(0,0,dto);
      for(var i=0;i<this.updateRows.length;i++)
         this.updateRows[i]._ordPos++;
 	};
 	
  	this.appendRow = function(dto){
 		this.data.push(dto);
 		this.addRows.push(dto);
 	};
 	
 	//更新行，页面有一个当前行的对象，那个对象改变也就改变了table.data，所以这里只要对位置操作
 	this.updateRow = function(index){
 		if(index>=this.size()||index<0)
 			return null;
 		var dto = this.data[index];
 		
 		//检查是否为新增的
		if(index<this.addRows.length)
			return;
		for(var i=0;i<this.addRows.length;i++)
			if(this.addRows[i]==dto) return;
		
 		//检查在updateRows里是否存在了
 		for(var i=0;i<this.updateRows.length;i++)
 			if(this.updateRows[i]._ordPos==index)
 				return;
 		
 		dto._ordPos = index;
 		
 		this.updateRows[this.updateRows.length] = dto;
 	};
 	
 	this.deleteRow = function(index){
 		if(index>=this.size()||index<0)
 			return null;
 			
 		var dto = this.data[index];
 		var isAdd = false;
 		for(var i=0;i<this.addRows.length;i++)
 			if(this.addRows[i]==dto) {
 				isAdd = true;
 				this.addRows.splice(i,1);
 				break;
 			}
 		if(!isAdd){//删除的不是新增的.
 			for(var i=0;i<this.updateRows.length;i++)
 				if(this.updateRows[i]==dto)
 					this.updateRows.splice(i,1);
 			
 			this.deleteRows[this.deleteRows.length] = this.data[index];
 		}
 		this.data.splice(index,1);
 		
// 		if(index<this.addRows.length)
// 			this.addRows.splice(index,1);
// 		else
// 			this.deleteRows[this.deleteRows.length] = this.data[index];
 			
// 		this.data.splice(index,1);
 //     for(var i=0;i<this.updateRows.length;i++){
//         if(this.updateRows[i]._ordPos>index)
//            this.updateRows[i]._ordPos--;
//         else if(this.updateRows[i]._ordPos==index)
//            this.updateRows.splice(i,1);
//      }
 	};
 	this.size = function(){
 		return this.data.length;
 	};
   this.concat = function(arr2){
      if(arr2!=undefined&&arr2!=null&&arr2.length>0){
         this.data = this.data.concat(arr2);
      }
   }
   
}
