//new DBGrid(null);
function DBGrid(parent)   //构造函数
{
  var pdiv;if(parent){pdiv=parent;}else pdiv=document.body;//获取父块
  var obj=new Div(pdiv);
  obj.style.overflow = 'auto';
  obj.style.borderWidth=1;
  obj.style.borderStyle='solid';
  obj.style.borderColor=clGray;

  obj.style.width = 300;
  obj.style.height = 100;
  obj.RowHeight = 21;
  obj.onscroll = DG_scrolldraw;
  obj.Rows = null;//调用表的所有行
  obj.RowsCount = 0;  //当前表中的记录总数
  obj.StateCells = null;//表格状态条
  obj.Cells = null;     //所有的单元格
  obj.Headerdiv = null;//包含表头的块
  obj.Header = null;//表示表头的表
  obj.ColsCount=0;//表的列数
  obj.Parent = null; //对象的容器
  obj.EditMode = null; //编辑状态
  obj.Enabled = false; //是否可用 
  obj.Visible = true;  //是否可见
  obj.Bodydiv = null; //表体的块
  obj.Body = null;    //表体本身,最重要的部分
  obj.Table = null;  //用户直接操作的部分
  obj.Id = '';        //对象的唯一的标示
  obj.DataSet = null;//数据集
  obj.Fields = null;//字段集
  obj.Isinit = true;//标记是否为初始化
  obj.CurrentCell = null
  obj.EditErrCell = null;  //保存当前编辑错误的项
  obj.Auto = false; //是否显示多有的项
//公有方法
  obj.SetDataSet = DG_setdataset;    //设置数据库
  obj.Show = DG_show;                //构造显示整个初始化后的表        
  obj.DeleteRow = DG_deleterow;      //删除一个指定的行
  obj.Refresh = DG_refresh;          //表结构刷新，整个结构重新构造
  obj.AppendRow = DG_appendrow;      //添加一个空行
  obj.HandleMessage = DG_handlemessage;//扑捉消息
  obj.UpdateRow = DG_updaterow;        //更新行
  obj.Clear = DG_clear;  //清除表格中的所有内容   
  obj.ClearRows = DG_clearrows; //清除表格中的所有的行
//私有方法
  obj._CreateBody = _DG_createbody;    //创建表及其容器块
  obj._BodyShow = _DG_bodyshow;        //显示表体的具体内容
  obj._appendCell = _DG_appendcell;    //添加一个空的单元格
  obj._ArrayRemove = _arrayremove;  //用于数组处理，从数组中删掉指定的元素
  obj._GetDataSetInfo = _DG_getdatasetinfo; //获得数据库信息
  obj._ValidFieldName = _DG_validfieldname; //校验字段
  if(isIE)
	obj.onpropertychange=_DG_onpropertychange
  else
	addEventTimerListener(obj,DC_onpropertychange);
  obj._CreateRow = DG_N_Row;
  obj.StateCells = new Array();
  obj.Cells = new Array();
  obj.Rows = new Array();
  obj.Captions = new Array();
  obj.Columns = new Columns(pdiv);
  obj.Columns.Auto = true; //是否显示多有的项
  obj.Columns.Parent = obj;         //取得父亲节点
  obj.OnCellClick;
  obj.OnCellKeyDown;
  obj.OnCellFocus;
  obj.OnCellBlur;
  obj.OnCellDblClick;
  obj.OnCustomCell;
  //构造基本的块，开始调用私有方法
  obj._CreateBody();
  return obj;
}
function _DG_createbody()//创建表体DIV
{
   if(!this.Bodydiv){
    this.Bodydiv=document.createElement('div');
    this.appendChild(this.Bodydiv);
    this.Bodydiv.style.position='relative';   
//    this.Bodydiv.style.top = 1;
//    this.Bodydiv.style.left = 1;
//    this.Bodydiv.style.paddingRight = 2;
   }
   if(!this.Table){
     this.Table = document.createElement('table');
     this.Table.style.position='relative';  
     this.Bodydiv.appendChild(this.Table);
   }
   this.Table.border='1';
   this.Table.cellSpacing="0";
   this.Table.cellPanding='0';
   this.Table.borderColor=clGray;//clSilver;
   this.Table.style.tableLayout='fixed';
   this.Table.style.borderCollapse='collapse';//表线的格式
   this.Table.style.borderTopWidth=0;
   this.Table.style.borderLeftWidth=0;
   this.Header = document.createElement('thead');
   this.Header.style.backgroundColor = "#DEDFDE";
   this.Header.style.height = this.RowHeight-1;
   this.Table.appendChild(this.Header);
   this.Header.onmousemove=DG_HEAD_ondrag;
   this.Header.onmouseup=DG_HEAD_onmouseup;
   this.Bodydiv.onmousemove=DG_HEAD_ondrag;
   this.Bodydiv.onmouseup=DG_HEAD_onmouseup;
   this.Header.owner=this;
   this.Bodydiv.owner=this;

   this.HeaderRow = document.createElement('tr');
   this.Header.appendChild(this.HeaderRow);
   //这里是状态列标题
   var cell = document.createElement('td');
   this.HeaderRow.appendChild(cell);
   cell.style.width=10;
   cell.innerHTML=' ';
   cell.style.borderTopWidth=0;
   cell.style.borderLeftWidth=0;
   this._BodyShow();//创建表体 
}
// mouse在表头draging的事件
function DG_HEAD_ondrag(event){
	if(!event)event=window.event;
	if(event.button==1){//left button
		if(this.owner.currCol){
     	  this.style.cursor='E-resize';
	      this.owner.currCol.style.cursor='E-resize';
		  var x=event.x;
		  if(!this.owner.oldDragX)
		  	  this.owner.oldDragX=x;
		  var width=this.owner.currCol.style.pixelWidth+x-this.owner.oldDragX;;
		  if(width>0)
	    	  this.owner.currCol.style.width=width;
	  	  this.owner.oldDragX=x;
		}
	}
}
// mouseup in header
function DG_HEAD_onmouseup(){
  this.style.cursor='default';
  if(this.owner.currCol){
      this.owner.currCol.style.cursor='default';
	  var index=this.owner.currCol.Index;
	  var rowcount=this.owner.RowsCount;
	  for(var i=0;i<rowcount;i++){
		this.owner.Cells[i][index].style.width=this.owner.currCol.style.pixelWidth-3;
	  }
	  this.owner.currCol=null;
  }
  this.owner.oldDragX=null;
}

function DG_show()
{
  if(this.Auto||this.Columns.Auto)
	  this._GetDataSetInfo();
  this.Isinit = false;
  this.Refresh();
}
function DG_clear(){
   this.Isinit=true;   //初始化标志
   if(!this.Cells.length==0)this.Cells.length=0; //清空单元格数组
   if(!this.StateCells.length==0)this.StateCells.length=0;//清空状态单元格
   if(this.Rows.length!=0)this.Rows.length=0;//清空所有的行
   if(this.RowsCount!=0)this.RowsCount=0;
  if(this.Auto||this.Columns.Auto){
     while(this.HeaderRow.childNodes.length>1){
		 var cn = this.HeaderRow.childNodes[1];
		 this.HeaderRow.removeChild(cn);
	 }
     this.Columns.Clear();//清空所有的列
   }
  while(this.TableBody.childNodes.length>0){
   var cn = this.TableBody.childNodes[0];
   this.TableBody.removeChild(cn);
   //cn.removeNode(true);
//   if(cn.parentNode);
//	  cn.parentNode.removeChild(cn);
  }
}
function DG_clearrows() {
  while(this.Rows.length){
     this.DeleteRow(0);
  }
}
function _DG_onpropertychange(sender) {
  var n;
  if(isIE) {
	  n=event.propertyName;
	  sender=this;
  }
  if(isMoz)
	  n='DataSet';
 switch(n){
   case 'DataSet':
     if(sender.OldDataSet){sender.OldDataSet.removeLink(sender);}
     sender.DataSet.LinkObj(sender);
     sender.OldDataSet = sender.DataSet;
	 break;
   case 'readOnly':
     for(var i=0;i<sender.Columns.Count;i++){
		sender.Columns.Column[i].readOnly=sender.readOnly;
	 }
	 break;
 }
}
function _DG_getdatasetinfo() {    //取得数据集的信息
//    this.RowsCount = this.DataSet.RecordCount;  //数据的行数
    if(this.Auto||this.Columns.Auto|| this.Columns.Count == 0){    //判断是否显示所有的行
      //如果是重新初始化列对象
      this.Columns.Clear(); //避免设置了列但是没有设置Auto时的列重复
      for(var i=0;i<this.DataSet.Fields.Count;i++){
          var f = this.DataSet.Fields.Fieldx[i]; 
          if(f.Type!='nested'){     //不是关联字段添加列
		    var column = new Column(f.FieldName,f.DisplayLabel);
		    if(f.FieldKind.toUpperCase() == 'LOOKUP'){
                column.CtlType = 'LOOKUP';
			}
          //构造列
          this.Columns.Add(column);
         }    
      }
    }
}
function _DG_validfieldname(fname) {
    var validflag = false
         for ( var j=0; j<this.DataSet.Fields.Count; j++ ) {
               if(fname == this.DataSet.Fields.Fieldx[j].FieldName && this.DataSet.Fields.Fieldx[j].Type!='nested'){
                  validflag = true;
                  break;
                }                
          }
     return validflag;        
}
function DG_scrolldraw()
{  
//   this.Headdiv.style.pixelTop=this.scrollTop;//让表头始终可见   
}
function _DG_bodyshow()//显示表
{
  this.TableBody = document.createElement('TBody');
  this.Table.appendChild(this.TableBody);
  this.Table.setAttribute('Child',this.TableBody);
}

function _DG_computVisview(objcell) { //判断所给出的单元格是否在视区之内
   var isInView = 0;
   var vCellRight =objcell.parentNode.offsetLeft + objcell.parentNode.offsetWidth;
   var vCellLeft = objcell.parentNode.offsetLeft;
   var vViewRight = this.scrollLeft + this.offsetWidth;
   var vViewLeft = this.scrollLeft;
   if(objcell.y == 0){
     this.scrollLeft = 0;
   }
   else{
     if(vCellRight > vViewRight-2){
       this.scrollLeft = vCellLeft;
     }
   }   
}
function DG_oncellkeydown(event)
{
	if(!event)event=window.event;
	switch(event.keyCode)
	{
		case 38://当按动向上箭头
			if(this.x>0)
		    {
              this.parent.Cells[this.x-1][this.y].focus();
			}
		    break;
		case 40://当按动向下箭头
			if(this.x<this.parent.Cells.length-1)
		    {
			  this.parent.Cells[this.x+1][this.y].focus();
		    } 
			else
		    {
			  this.cellputvalue();
              if(!this.Field.Err){
				this.parent.DataSet.Append();
			    if(this.parent.Rows[this.x+1])this.parent.Cells[this.x+1][0].focus();
			  }
			}
		    break;
		case 33://当按动向上翻动页面
			this.parent.doScroll('scrollbarPageUp');
		    break;
		case 34://当按动向上翻动页面
			this.parent.doScroll('scrollbarPageDown');
		    break;
	}
	if(this.parent.OnCellKeyDown){
	  this.parent.OnCellKeyDown(this,this.x,this.y,event.keyCode);
	}
}
function _DG_appendcell(cellflag,x,y,colobj)
//添加一个单元格，CELLFLAG标志可以表示它是不是表示状态的单元格
//ctlstring为元素的类型，typestring为子元素的类型针对input类型
{
 //*********************************************//
   var onecell = document.createElement('TD'); //构造一个单元格

   if(colobj){
     var ctlstring = null;var typestring = null;
	 var coltype=colobj.CtlType.toUpperCase();
     if(coltype=='TEXT'||coltype=='PASSWORD'||coltype=='CHECKBOX'){
       ctlstring = 'input';
       typestring = colobj.CtlType;
     }
     else{
       ctlstring = colobj.CtlType;
     }
   }
  //****************检测列的类型****************//
	
	var hidecell,cellbak;
	if(cellflag)
	{
		//////此处添加编辑单元格
		
		//*********************************************//
      if(ctlstring.toUpperCase() == 'SELECT' || ctlstring.toUpperCase() == 'LOOKUP'){//如果师复选框则要添加两种类型     
		  
		  ctlstring = 'input';//再将类型变成text;
		  typestring = 'TEXT';
		}
	
		//************首先处理为combobox的情况**********//
		
		//*****************所有类型相同的处理***********//
	   cellbak = document.createElement(ctlstring);//添加一个指定元素
	   if(typestring){            //如果有子类型设置子类型，主要针对input
        cellbak.type = typestring;
        if(typestring.toUpperCase() == 'CHECKBOX'){
           cellbak.DefaultValue = colobj.DefaultValue;
        }
      }

	   cellbak.style.cssText = colobj.style.cssText;
//	   cellbak.style.borderStyle ='solid';
	   cellbak.style.borderWidth =0;
   	   setFont(cellbak);
	   //控制单元格的格式
       cellbak.parent = this;
	   cellbak.x = x;  //单元格行坐标属性
	   cellbak.y = y;  //单元格列坐标属性
	   cellbak.Field=this.DataSet.Fields.Field[colobj.DataField];
	   cellbak.readOnly=this.Columns.Column[y].readOnly;
       //为单元格添加新的属性
	   cellbak.onclick=Cell_onclick;
       cellbak.onfocus = DG_oncellfocus;
	   cellbak.onblur = DG_oncellblur;
	   cellbak.onchange = DG_onchange;
	   cellbak.ondblclick=function(){if(this.parent.OnCellDblClick)this.parent.OnCellDblClick(this,this.x,this.y);}
      if(ctlstring != 'A'){
        cellbak.onkeydown = DG_oncellkeydown;
	     cellbak.cellputvalue = DG_cellputvalue;
	   }
	   //添加事件的处理
	   cellbak.style.height=this.RowHeight;
	   onecell.style.height=this.RowHeight;
	   onecell.appendChild(cellbak);	   
	   //*****************所有类型相同的处理***********//	   
	}
	else
	  {
		  onecell.innerHTML=' ';
		  onecell.setAttribute('x',0);
		  onecell.setAttribute('parent',this);
		  onecell.setAttribute('isEdit',false);
		  //此处为状态列的单元格
	  }
	 if(this.OnCustomCell)this.OnCustomCell(onecell,x,y);
	 return onecell;
}

function Cell_onclick() {     //click事件处理
 if(this.parent.DataSet.Active){
   var type = this.parent.Columns.Column[this.y].CtlType;
   switch(type.toUpperCase()){
    case 'CHECKBOX' :
       if(this.checked){
         this.value = this.parent.Columns.Column[this.y].CheckedValue;
       }
       else{
         this.value = this.parent.Columns.Column[this.y].NoCheckValue;
       }
    break;    
    case 'LOOKUP':         //显示LOOKUP
	 if(!this.readOnly){
        var col = this.parent.Columns.Column[this.y];//取列
		this.focus();
        this.style.width = 0;  //隐藏text
		if(!col.ComboBox){//lookup||combobox
          col.ComboBox = new DBLookupSelect(this.parentNode);  //添加行
          col.ComboBox.Items = col.ComboItems;  //添加选项
          col.ComboBox.onblur = _Combo_blur;    //设置失去焦点事件处理
	  var f=this.parent.DataSet.Fields.Field[col.DataField];
	  col.ComboBox.ListField=f.LookupResultField;
	  col.ComboBox.KeyField=f.LookupKeyField;
	  col.ComboBox.DataField=f.KeyField;
	  col.ComboBox.ListDataSet=f.LookupDataSet;
	  col.ComboBox.DataSet=this.parent.DataSet;
        }
        else{
            this.parentNode.appendChild(col.ComboBox);
        }
        this.Brother = col.ComboBox;
        col.ComboBox.Brother = this;
        var comstyle = col.ComboBox.style;
        comstyle.visibility = 'visible';
        comstyle.width = col.CaptionCell.style.width;
//        comstyle.top = this.parentNode.style.top;
//        comstyle.left = this.parentNode.style.left;
		col.ComboBox.RecordMove();
        col.ComboBox.focus();
	 }
     break;  
    case 'SELECT':         //显示SELECT
	 if(!this.readOnly){
        var col = this.parent.Columns.Column[this.y];//取列
		this.focus();
        this.style.width = 0;  //隐藏text
		if(!col.ComboBox){//lookup||combobox
          col.ComboBox = new DBSelect(this.parentNode);  //添加行
		  col.ComboBox.options.Clear();
          for(var i=0;i<col.PickList.Count;i++){
			  col.ComboBox.options.Add(col.PickList.Strings[i], col.PickList.Strings[i]); //添加选项
		  }
          col.ComboBox.onblur = _Combo_blur;    //设置失去焦点事件处理
     	  col.ComboBox.DataField=col.DataField;
	      col.ComboBox.DataSet=this.parent.DataSet;
        }
        else{
            this.parentNode.appendChild(col.ComboBox);
        }
        this.Brother = col.ComboBox;
        col.ComboBox.Brother = this;
        var comstyle = col.ComboBox.style;
        comstyle.visibility = 'visible';
        comstyle.width = col.CaptionCell.style.width;
//        comstyle.top = this.parentNode.offsetTop;
//        comstyle.left = this.parentNode.offsetLeft;
        col.ComboBox.focus();
		col.ComboBox.Locate();
	 }
     break;  
   }
 }
  if(this.parent.OnCellClick){  //如果用户自定义事件处理存在那么执行
     this.parent.OnCellClick(this,this.x,this.y);
  }
}
function _Combo_blur() {
	if(!this.Brother)return;
    this.style.width = 0;
    this.Brother.style.visibility = 'visible'; //显示edit
    this.style.visibility = 'hidden'; //隐藏combobox
    this.Brother.style.width = this.Brother.parent.Columns.Column[this.Brother.y].width-4; //设置edit宽度
//	this.Brother.value=this.options[this.selectedIndex].value;
    this.Brother.parentNode.removeChild(this);
    this.Brother = null;
}
//添加一个空行，initflag标志是否是在表初始化的时候添加行，进行不同的处理
function DG_appendrow(initflag)
{
  var cellarray = new Array();
  //一个临时的保存一行单元格的数组
  var deep=this.StateCells.length;
  //返回但前的行长度
  this.Rows[deep]= null;
  this.Rows[deep] = this._CreateRow();
  if(!initflag )//如果不是初始化构造表，那么要对当前数据集做必要处理
  {
//	  this.DataSet.First();	 
  }

  var rowcolor;
  if(isOddNumber(deep))
    rowcolor=clWhite;
  else
    rowcolor=clHightGray;
  var v,f,f_ahref;
  for(var i=0;i<this.Columns.Count+1;i++)
  {//处理单元格
    if(i>0 )
    {  
	    var cellflag = true;v=null;f=null;
        var  childcell = null;    	   
	     var col =this.Columns.Column[i-1];
	     childcell = this._appendCell(cellflag,deep,i-1,col);
	     //列控制
	     cellarray[i-1] = childcell.firstChild;
	     col.Cells[deep] = cellarray[i-1];
		 if(this.DataSet)if(this.DataSet.Active) {
			 f=this.DataSet.Fields.Field[col.DataField];
		 }
	     if(f)v = f.GetValue();
	     if(v != null){
	        if(col.CtlType == 'A'){
	           cellarray[i-1].innerHTML = v;
  			   f_ahref=this.DataSet.Fields.Field[col.A_hrefField];
			   if(f_ahref) v=f_ahref.GetValue();
	           cellarray[i-1].href = v;;
	        }
	        else{ 	               
	           if(col.CtlType.toUpperCase() == 'CHECKBOX'){	 
	               cellarray[i-1].defaultValue = v; 
	                cellarray[i-1].value = v;	                           
	               if(v == col.CheckedValue){	 
	                  cellarray[i-1].defaultChecked = true;                 
	                  cellarray[i-1].checked = true;
	               }
	              
	           }	
	             cellarray[i-1].value = v;
	        }	         
	     }
	    else{
	       var tp = col.CtlType;
	       if(tp == 'A'){
	           cellarray[i-1].innerHTML = null;
	       }
	       if(tp.toUpperCase() == 'CHECKBOX'){
	           cellarray[i-1].defaultValue = col.NoCheckValue;
	       }
	       if(tp.toUpperCase() == 'SELECT' || tp.toUpperCase() == 'PASSWORD'|| tp.toUpperCase() == 'TEXT' || tp.toUpperCase() == 'LOOKUP'){
	           cellarray[i-1].value = '';
	       }
       }
	   if(col.CaptionCell.style.pixelWidth)
	       cellarray[i-1].style.width = col.CaptionCell.style.pixelWidth-3;
	   cellarray[i-1].style.backgroundColor=rowcolor;
	   cellarray[i-1].title=v;
	 }
	 else
	 {
	   var cellflag = false;
	   var childcell = this._appendCell(cellflag,deep);
	   childcell.width = 10;
	   childcell.style.backgroundColor=rowcolor;
	   childcell.align='center';
	   setFont(childcell);
	   this.StateCells[deep] = childcell;
      //添加状态列单元格
	 }
    this.StateCells[deep].style.borderLeftWidth=0;
    this.Rows[deep].appendChild(childcell); 
  }
  this.Cells[deep]=cellarray;//表的单元格
  this.Rows[deep].Cells=cellarray;//行的单元格控制
  this.TableBody.appendChild(this.Rows[deep]);//将此行添加到对象中
  this.Rows[deep].style.backgroundColor=rowcolor;
  this.RowsCount = this.RowsCount+1; 
  return this.Rows[deep];
}

function DG_deleterow(index)
{
	this.TableBody.removeChild(this.Rows[index]);
	//前台处理，去掉这一行的显示
	//以下为后台处理，主要是单元格的管理
	//this.Rows[index].removeNode(true);
	var row=this.Rows[index];
	if(row.parentNode)
		row.parentNode.removeChild(row);
	this.Rows=this._ArrayRemove(this.Rows,index);
	//删除当前行数组
	this.Cells=this._ArrayRemove(this.Cells,index);
	//删除指定行的所有的单元格
	this.StateCells=this._ArrayRemove(this.StateCells,index);
	var count=this.Columns.Count;
	for(var i=0;i<count;i++)
	{
	   this.Columns.Column[i].Cells = this.Columns.ArrayRemove(this.Columns.Column[i].Cells,index);
	}
	//删除状态列单元格
	//数组管理
   this.CurrentCell=null;
//	this.doScroll('scrollbarUp');
	
	if(index!=(this.RowsCount-1))
		//对每个单元格的x，即其行标属性进行更改
	{
      var counterx=this.Cells.length;//取得行数
 	   var countery=this.Columns.Count;;   //取得列数
	 
	   for(var i=index;i<counterx;i++)
	   {
		   for(var j=0;j<countery;j++)
		   {
			   this.Cells[i][j].x=i;//改变所有编辑单元格的行数标示
			   if(this.Cells[i][j].Brother){
			      this.Cells[i][j].Brother.x = i;
			   }
		   }
		   this.StateCells[i].x=i;//改变状态列单元格
	   }
	}
	this.RowsCount=this.RowsCount-1;	
	if(this.RowsCount==0) this.DataSet.Last();
}
function DG_oncellfocus()//当编辑单元格获的焦点
{
	var p=this.parent;
	var ispost=false;  
	if(this.x!=p.DataSet.RecNo)
	{	      
      p.DataSet.SetPos(this.x);
	}
   p.CurrentCell=this;
   if(this.select)this.select();
//   p._ComputVIsView(this);
   if(this.parent.OnCellFocus){  //如果用户自定义事件处理存在那么执行
       this.parent.OnCellFocus(this,this.x,this.y);
   }
   
}
function DG_oncellblur()//当编辑单元格失去焦点
{
   if(this.parent.OnCellBlur){  //如果用户自定义事件处理存在那么执行
       this.parent.OnCellBlur(this,this.x,this.y);
   }
}
function DG_cellputvalue()
{
	var p=this.parent;var m=0;
	var f=this.Field;
	f.Err=null;
	var re,v;
	if(!f.OldValue) v=''
	else v = f.OldValue;
  if(this.value!=v)
  {
	if(p.Rows[this.x].State==1){
		m=1;p.nomsg=1;
		if(!p.DataSet.Fields.State)p.DataSet.Append();
		p.nomsg=null;p.Rows[this.x].State=0;
	}
    if(p.DataSet.Fields.State!=4){p.DataSet.Edit();f.Value=this.value;}
	else if(this.value)f.Value=this.value;   //赋值 
	if(f.Err)
	{
	 p.CurrentCell=this;
	 this.focus();
	 re=f.Err;
//	 f.Err=null;
	}
    if(m==1){p.HandleMessage(p.DataSet,6,p.DataSet.RecNo);}
  }
	return re;
}
function DG_onchange(event)
{	
	if(!event)event=window.event;
	var re=this.cellputvalue();
    if(re)event.returnValue=false;
}
function DG_setdataset(dataset)
{

	if(dataset)
	{
	   dataset.LinkObj(this);//将对象和dataset关联起来，以便dataset可以控制此对象
	   this.DataSet = null;
		this.DataSet=dataset; //引用数据库		
		this.Fields=dataset.Fields;		 //引用数据库
		//this._GetDataSetInfo();
		return true;
		
	}   
}
function DG_refresh()//整个表全部重构
{
  if(this.Rows.length)this.ClearRows();
  var count =this.DataSet.RecordCount;
  //添加表的内容
   if(count!=0)
   {
     this.DataSet.AutoControl = false;
     var recno = this.DataSet.RecNo;
     this.DataSet.First();
     for(var i=0;i<count;i++)
     {
         var row = this.AppendRow(true);
		 if(row!=null)
	         row.State = 0;	
         this.DataSet.Next();
     }
     this.DataSet.AutoControl = true;
     this.DataSet.SetPos(recno);
   }
   else
   {
     var row = this.AppendRow(false); 
     row.State = 1;
     this.StateCells[0].innerHTML = '>';
   }
}
function DG_updaterow(recno,fieldno)//更新
{
	var v = this.DataSet.Fields.Fieldx[fieldno].GetValue(); //取字段值	
	var name = this.DataSet.Fields.Fieldx[fieldno].FieldName;//取字段名称
	var colorder = new Array();
	var concount = 0;
	for(var i = 0;i<this.Columns.Count;i++){  //取列号
	   if(this.Columns.Column[i].DataField == name){
	      colorder[concount] = i;
		  concount ++;
	   }
	}
	if(colorder.length != 0){
	  for(var i = 0;i<colorder.length;i++){
          var j = colorder[i];
		  
	      var c = this.Columns.Column[j];
	      if(v == null){ 
	         v = ''; //否则变为空
	      }
  	      this.Cells[recno][j].title=v;
	      if(c.CtlType != 'A'){  //不是连接的情况
	         this.Cells[recno][j].value=v; //如果值不为空，给单元格赋值

	         if(c.CtlType.toUpperCase() == 'CHECKBOX') {  //CHECKBOX的情况
	            if(c.CheckedValue == v){    //如果值等于选中时候的值，置状态为选中
	               this.Cells[recno][j].checked = true;
	            }
	            else{         //否则置状态为非选中
	               this.Cells[recno][j].checked = false;
	            }	          
	         }
	      }
	     else{  //如果是连接的情况那么不是VALUE而是INNERTEXT
	       this.Cells[recno][j].innerHTML = v;
	       this.Cells[recno][j].herf = v;
	     }
	  }
	}
}
function DG_handlemessage(sender,message,recno,fieldno)//消息捕捉函数
{
	if(this.nomsg)return;
	if(message!=null)
	{
		switch(message)
		{
			case 0://初始化消息
			    this.Show();
			    break;
			case 1://添加一行的消息
 		   if(this.DataSet.RecordCount<=1){
			      this.Rows[0].State = 0;
                for(var i=0;i<this.Columns.Count;i++)
			    {
				   var j;
				   j = this.DataSet.Fields.Field[this.Columns.Column[i].DataField].Index;
				   this.UpdateRow(0,j);
				 }
  		      return;
			}   
			var lastrow = this.AppendRow(false);
//			lastrow.scrollIntoView(false);
			this.EditMode=1;
			this.HandleMessage(this.DataSet,3,this.DataSet.RecNo);
			   break;
			case 2://删除一行的消息
			    if(recno!= null){
					this.DeleteRow(recno);
					if(recno == 0 && this.DataSet.RecordCount == 0){
					  var firstrow = this.AppendRow(false);
					  firstrow.State = 1;
					}
				 }
				 else{
				   if(this.Cells.length >=1){
					   this.DeleteRow(0);
					}
			   }
				break;
			case 3://移动一行的消息 
				if(!this.Isinit && this.Cells.length==this.DataSet.RecordCount &&this.Cells.length !=0)
			    {
			        var s=this.StateCells[recno];
				     for(var i=0;i<this.StateCells.length;i++) {				       
					     if(this.StateCells[i].innerHTML!=' ')
						  this.StateCells[i].innerHTML=' ';
					  }
//				  this._ComputHIsView(recno);
                  if(s)s.innerHTML='*';//数据不可编辑
				  var rowcolor;
				  for(var i=0;i<this.Rows.length;i++){
					if(isOddNumber(i))
					 rowcolor=clWhite;
					else
					 rowcolor=clHightGray;
					this.Rows[i].style.backgroundColor=rowcolor;
				    this.StateCells[i].style.backgroundColor=rowcolor;
					for(var j=0;j<this.Columns.Count;j++){
					 this.Cells[i][j].style.backgroundColor=rowcolor;
					}
				  }
				  this.Rows[recno].style.backgroundColor=clBlue0;
  				  this.StateCells[recno].style.backgroundColor=clBlue0;
				  for(var i=0;i<this.Columns.Count;i++){
					 this.Cells[recno][i].style.backgroundColor=clBlue0;
				  }
		        }
				break;
			case 4://更新field
			   if(recno != null){
//				   alert(this.DataSet.Fields.Fieldx[fieldno].Value);
					this.UpdateRow(recno,fieldno);
			   }
				break;
			case 5://全部刷新调用Refresh();
			   this.Refresh();
				break;
		    case 6://编辑操作
             for(var i=0;i<this.Columns.Count;i++)
			    {
				   
				   var j;
				   j = this.DataSet.Fields.Field[this.Columns.Column[i].DataField].Index;
				   this.UpdateRow(recno,j);
				 }
			    break;
			case 7://关闭数据集
			    this.Clear();
				break;
		   case 8://提交到服务器成功
		      break;
		   case 9://取消操作
		      this.Refresh();
		      break;
		}
	}
}
function DG_N_Row()//一个建立row的函数，N代表不是DG的成员函数
{
	var row = document.createElement('TR');
	var arr=new Array();
	row.setAttribute('State',0);//行状态
	row.setAttribute('Cells',arr);//行所包含的单元格
	row.setAttribute('IsFocus',R_isFocus);//检验当前行是否具有焦点
	return row;
}
function R_isFocus()//检测当前行是否失去焦点
{
	var cells=this.Cells;var r_focusflag=false;
	if(cells)
	{
		for(var i=0;i<cells.length;i++)
		{if(cells[i].FocusFlag){r_focusflag=true;break;}}//检验每一个单元是否都失去了焦点
	}
	return r_focusflag;
}

function Column(fieldname,displayname)//建立一个列的函数,N代表不是DG的成员函数
{
   var objcol = document.createElement('Column');
   objcol.CaptionCell = null;//表头单元格
   objcol.Visibled = true;  //是否可见
   objcol.Caption = '';     //标题
   objcol.BlackCell = null;  //空的表头单元格
   objcol.DataField = fieldname;//字段名称
   objcol.Cells = new Array();  //列的所有单元格
   objcol.CtlType = 'TEXT';     //控件的类型
   objcol.ComboBox = null;
   objcol.PickList = new Strings();  //如果类型是ComboBox时的填充字符串集
   objcol.SynchProperty = C_propertysynch;//同步普通属性
   objcol.NoCheckValue = null;
   objcol.CheckedValue = null;
   objcol.DefaultValue = null;
   objcol.Index = 0;         //索引
//   objcol.width = 150;
  if(isIE)
	objcol.onpropertychange=C_colchange
  else
	addEventTimerListener(objcol,C_colchange);

   if(displayname){
      objcol.Caption  = displayname;  
   }
   else{
      objcol.Caption  = fieldname;
   }
   return objcol;
}
// DG_N_Columns object constructor
function Columns(pobj) {
   var objcols = new Object();
   objcols.Column = new Array(); //所有的列
   objcols.DisColCount = 0;      //显示的列的总数
   objcols.DisColIndex = new Array();  //显示的列的索引
   objcols.GetDisIndex = Cs_getdiscol; //获取显示的列的索引
   objcols.Add = Cs_addCol;      //添加一个列
   objcols.Del = Cs_delCol;      //删除一个列
   objcols.pdiv = pobj;         //取得父亲节点
   objcols.ArrayRemove = _arrayremove;  //从数组中移除一个元素
   objcols.Count=0;              //列的总行数
   objcols.Clear = CS_clearCols;
   return objcols;
}
function CS_clearCols() {
   for(var i = 0;i<this.Count;i++){
	this.Del(i);
   }
}
function Cs_getdiscol() {   //取得要显示的列的索引
   for(var i=0;i<this.Count;i++){
      if(this.Column[i].Visibled){
         this.DisColIndex[this.DisColIndex.length] = i;
      }
   }

}
function Cs_addCol(colobj) {
  this.pdiv.appendChild(colobj);//添加列元素，必须要做这个工作
  colobj.Parent=this;
  var deep = this.Column.length; //取得当前列数
  if(colobj.CtlType.toUpperCase()== 'CHECKBOX'){
     if(colobj.NoCheckValue == null) colobj.NoCheckValue = false;
     if(colobj.CheckedValue == null) colobj.CheckedValue = true;
     if(colobj.DefaultValue == null) colobj.DefaultValue = colobj.NoCheckValue;
  }
  this.Column[deep] = colobj;  //添加一列   
  this.Column[deep].Index = this.Column.length -1;  
  this.Count = this.Column.length;//重新列的总数   

  //添加列的标题	
  var cell = document.createElement('td');
  this.Parent.HeaderRow.appendChild(cell);
  cell.align='center';
  cell.innerHTML = colobj.Caption; //改变表头
  cell.style.borderTopWidth=0;

  colobj.CaptionCell=cell;
  cell.Index=colobj.Index;
  cell.Column=colobj;
  colobj.grid=this.Parent;
  if(!colobj.width) {
	  colobj.width=100;
	  cell.style.width=100;
  }
  setFont(cell);
  cell.onmousemove=DG_HEADCELL_onmousemove;
  cell.onclick=DG_HEADCELL_onclick;
}
// mouse在表头moving的事件
function DG_HEADCELL_onclick(event){
	if(this.Column.DataField&&this.Column.grid.DataSet){
      this.style.cursor='wait';
	  this.Column.grid.DataSet.Sort(this.Column.DataField);
	  //显示排序图标
	  this.sortup=!this.sortup;
	  if(!this.Column.grid.sortimg){
        this.Column.grid.sortimg = document.createElement('IMG');
	  }
	  else{
		this.Column.grid.sortimg.parentNode.removeChild(this.Column.grid.sortimg);
	  }
      this.appendChild(this.Column.grid.sortimg);
	  if(this.sortup)
        this.Column.grid.sortimg.src=jcl_ResourceURL+'sort_up.gif'
	  else
        this.Column.grid.sortimg.src=jcl_ResourceURL+'sort_down.gif';
      this.style.cursor='default';
	}
}
// mouse在表头moving的事件
function DG_HEADCELL_onmousemove(event){
	if(!event)event=window.event;
	var x= event.offsetX;
	if(x>this.style.pixelWidth-5){
	  this.style.cursor='E-resize';
	  this.parentNode.parentNode.style.cursor='E-resize';
	  this.parentNode.parentNode.owner.currCol=this;
      this.onclick=null;
	}
	else{
	  if(event.button!=1){
		  if(this.parentNode.parentNode.owner.currCol!=null){
	   	      this.parentNode.parentNode.owner.currCol.style.cursor='default';
			  this.parentNode.parentNode.owner.currCol=null;
			  this.parentNode.parentNode.style.cursor='default';
		  }
		  else this.style.cursor='default';
      this.onclick=DG_HEADCELL_onclick;
	}
	  else{
		  if(this.parentNode.parentNode.owner.currCol!=null)
			  this.style.cursor='E-resize';
	  }
	}
}

function Cs_delCol(index) {
  var cn = this.Column[index];
//  this.pdiv.removeChild(cn); 
  if(cn.parentNode)
	 cn.parentNode.removeChild(cn);
  this.ArrayRemove(this.Column,index); //删除该列
  this.Count = this.Column.length; //重新取得总的列数
}
function C_colchange(sender) {
  if(isIE) {
	  sender=this;
	  n=event.propertyName;
  }
  else{
	  if(sender.oldCaption!=sender.Caption){
		n='Caption';
		sender.oldCaption=sender.Caption;
	  }
	  else if(sender.oldwidth!=sender.width){
		n='width';
		sender.oldwidth=sender.width;
	  }
	  else if(sender.oldComboItems!=sender.ComboItems){
		n='ComboItems';
		sender.oldComboItems=sender.ComboItems;
	  }
	  else if(sender.oldDefaultValue!=sender.DefaultValue){
		n='DefaultValue';
		sender.oldDefaultValue=sender.DefaultValue;
	  }
	  else if(sender.oldreadOnly!=sender.readOnly){
		n='readOnly';
		sender.oldreadOnly=sender.readOnly;
	  }
  }

    switch(n)//判断改变的属性的名称
    {
     case 'Caption':
          sender.CaptionCell.innerHTML = sender.Caption; //改变表头
     break;
     case 'width':
          sender.CaptionCell.style.width = sender.width; //改变表头
     break;
     case 'ComboItems':
         sender.ComboBox.ComboItems = sender.ComboItems;
     break;
     case 'DefaultValue':
         if(sender.DefaultValue != sender.NoCheckValue ||sender.DefaultValue != sender.CheckedValue){
            sender.DefaultValue = sender.NoCheckValue;
         }
     break;
	 case 'readOnly':
		 sender.SynchProperty(n);
	 break;
	}
}
function C_propertysynch(propertyname){
	if(propertyname){
	   for(var i=0;i<this.Cells.length;i++){
		   this.Cells[i].setAttribute(propertyname,this.getAttribute(propertyname,1));
	   }
	}
}
