/***********************************************
*本对象功能：使html中的table(必须有thead,tbody,tfoot)对象可分页和查询
*author :王建波
*date   :2008-04-15
*version:1.1
***********************************************/
/**对象构造函数config参数格式
{
	el:{Html.Table}oTable         表格对象/对象id
	pageSize:{int}             每页显示行数
	searchField:{Object}       搜索字段名称或索引
	iconPath:{String}    图片默认路径
	panelCssCls:{String}     面板Css样式名称
	isShowSearch:{boolean}      搜索输入框是否显示,可输入true/false
	align:{String}        面板对齐方式left/right
}
**/
function HuidaGrid(config){
	//指定数据源对象
	var _oTable;
	if(typeof(config.el)!="object")
		 _oTable=$(config.el);
	else
 		_oTable=oTable;
	this.datatable=_oTable;

	//指定数据显示区域
	this.dataarea=_oTable.getElementsByTagName("tbody")[0];

	//指定表头对象
	this.header=_oTable.getElementsByTagName("Thead")[0];
	
	//设置每页显示记录条数
	this.setPageSize(config.pageSize);
	   
	//指定搜索列
	this.setSearchField(config.searchField);

	//默认图片路径
	this.setIconPath(config.iconPath)

    //设置css样式
	this.setPanelCssClass(config.panelCssCls);	
	
	//设置是否显示搜索
	this.setSearchDisplay(config.isShowSearch)
		
	//设置面板对齐方式
	this.setPanelAlign(config.align);

	//分页显示属性设置
	this.resultbuff=null;
	this.datamatrix=null;
	this.pageindex=0;
}

/**
*初始化并显示对象
**/
HuidaGrid.prototype.init=function(){		
	//绑定表格的事件处理函数
	this.bindEventHandler();
	
	//从数据源获取数据
	this.getData();
	
	//显示控制界面
	this.DrawPanel();
	
	//显示第一页
	this.showFirst();
	
	//设置表头和表尾的鼠标光标
	var oTds=this.header.getElementsByTagName("td");
	for(var i=0,nLen=oTds.length;i<nLen;i++){
		oTds[i].style.cursor="pointer";
	}
	
	var oTfoot=this.datatable.getElementsByTagName("tfoot")[0];
	var oImgs=oTfoot.getElementsByTagName("img");
	for(var i=0,nLen=oImgs.length;i<nLen;i++)
		oImgs[i].style.cursor="pointer";
}

/**
*从数据源获取数据,并初始化数据矩阵和结果数组(私有方法不推荐外部使用)
**/
HuidaGrid.prototype.getData=function(){
	var oTrs=this.datatable.getElementsByTagName("tbody")[0].rows;
	var arrRet=new Array();
	
	for(var i=0,nTrLen=oTrs.length;i<nTrLen;i++){	
		arrRet.push(oTrs[i].cloneNode(true));	
	}
    
	this.datamatrix=arrRet;
	this.resultbuff=arrRet;
	this.pageindex=0;
}

/**
*绑定表格的事件处理函数(私有方法不推荐外部使用)
**/
HuidaGrid.prototype.bindEventHandler=function(){
	var _oDgrid=this
	this.datatable.onclick=function(e){
		var evt=e||event;
		var srcEl=evt.target||evt.srcElement;
		//绑定搜索处理函数
		if(srcEl.id=="gruid-btn-search"){
			var strWord=$("gruid-txt-search").value;
			_oDgrid.onsearch(evt,strWord);
			return;
		}
		//绑定翻页处理函数
		if(srcEl.id=="gruid-img-pre"){
			if(_oDgrid.pageindex-1>=1){
				var strPage=_oDgrid.pageindex-1;	
				_oDgrid.showPre();
				return;
			}
		}		
		if(srcEl.id=="gruid-img-next"){
			if(_oDgrid.pageindex+1<=_oDgrid.getPageCount()){
				var strPage=_oDgrid.pageindex+1;								
				_oDgrid.showNext();
				return;
			}
		}
		if(srcEl.id=="gruid-img-first"){
			if(_oDgrid.pageindex>1){
				_oDgrid.showFirst();
				return ;
			}
		}
		if(srcEl.id=="gruid-img-last"){
			if(_oDgrid.pageindex<_oDgrid.getPageCount()){
				_oDgrid.showLast();
				return;
			}
		}
		
		//绑定表头单击处理函数
		var oTh,oNode=srcEl,isInTh=false;
		//判断是否是表头单元格内元素触发事件,若是获取单元格对象
		while(oNode.parentNode.tagName!="TABLE"){
			if(oNode.parentNode.parentNode && oNode.parentNode.parentNode.tagName=="THEAD"){
				isInTh=true;
				oTh=oNode
				break;
			}else{
				oNode=oNode.parentNode;
			}	
		}
		
		if(isInTh){
			_oDgrid.onheaderclick(oTh);
		}					
	}
	
	//绑定键盘事件
	this.datatable.onkeypress=function(e){
		var evt=e||event;
		var srcEl=evt.target||evt.srcElement;
		var nKeyCode=evt.keyCode||evt.which;		
		
		if(nKeyCode==13){
			if(srcEl.getAttribute("id")=="gruid-txt-pageinput"){
				var strPage=$('gruid-txt-pageinput').value;
				if(parseInt(strPage)>0)
					_oDgrid.showPageAt(strPage);
				else
					alert("请输入整数页码！");	
			}else if(srcEl.getAttribute("id")=="gruid-txt-search"){
				var strWord=$("gruid-txt-search").value;
				_oDgrid.onsearch(evt,strWord);
			}
		}
	}
}

/**
*清除显示(私有方法不推荐外部使用)
**/
HuidaGrid.prototype.clearDataArea=function(){
	try{
		var oTbody=this.dataarea;
		while(oTbody.childNodes.length>0){
			oTbody.removeChild(oTbody.childNodes[0]);
		}
	}catch(err){
		alert("执行clearDataArea时发生错误:"+err.message);
	}
}

/**
*显示某一页数据(私有方法不推荐外部使用)
*@para {int}nPageNum   要显示的页的页码
**/	
HuidaGrid.prototype.showPage=function(nPageNum){
	try{	
		var oTrs=this.resultbuff;
		var nPCount=this.getPageCount();
		var nPSize=this.pagesize
		var nBuffLen=this.resultbuff.length;
		var nPStart,nPEnd;

		nPageNum=parseInt(nPageNum);
		if(nPageNum<1){
			nPageNum=1;
		}else if(nPageNum>nPCount){
			nPageNum=nPCount;
		}

		//计算起始记录和结束结束记录序号
		nPStart=(nPageNum-1)*nPSize;
		nPEnd=nPageNum*nPSize-1;
		
		//追加显示记录
		var oTbody=this.dataarea;
		for(var i=nPStart;i<=nPEnd && i<this.resultbuff.length;i++){
			oTbody.appendChild(oTrs[i]);
		}
		//改变显示页面索引
		this.pageindex=nPageNum;
		this.updatePageNumber();
	}catch(err){
		alert("执行showPage函数时发生错误:"+err.message);
	}
}

/**
*显示指定页
**/
HuidaGrid.prototype.showPageAt=function(strPage){
	try{
		//若不为空显示指定页
		if(this.resultbuff.length>0){
			var nPage=parseInt(strPage);
			if(isNaN(nPage))
				nPage=1;
			if(this.pageindex!=nPage){
				//清除显示
				this.clearDataArea();
				this.showPage(nPage);
			}
		}else{
				this.pageindex=0;
			this.updatePageNumber();
		}
	}catch(err){
		alert("执行showPageAt时发生错误:"+err.message);
	}
}


/**
*显示第一页
**/
HuidaGrid.prototype.showFirst=function(){
	try{
		//若不为空显示第一页
		if(this.resultbuff.length>0){
			if(this.pageindex!=1){
				//清除显示
				this.clearDataArea();
				this.showPage(1);
			}
		}else{
			this.clearDataArea();
			this.pageindex=0;
			this.updatePageNumber();
		}
	}catch(err){
		alert("执行showFirst时发生错误:"+err.message);
	}
}

/**
*显示最后一页
**/
HuidaGrid.prototype.showLast=function(){
	try{
		//若不为空显示最后一页
		if(this.resultbuff.length>0){
			if(this.pageindex<this.getPageCount()){
				//清除显示
				this.clearDataArea();
				this.showPage(this.getPageCount());
			}
		}else{
			this.pageindex=0;
			this.updatePageNumber();
		}
	}catch(err){
		alert("执行showLast时发生错误:"+err.message);
	}
}

/**
*显示上一页
**/
HuidaGrid.prototype.showPre=function(){
	try{
		//若不为空显示上一页
		if(this.resultbuff.length>0){
			if(this.pageindex>1){
				//清除显示
				this.clearDataArea();
				this.showPage(this.pageindex-1);
			}
		}else{
			this.pageindex=0;
			this.updatePageNumber();
		}
	}catch(err){
		alert("执行showPre时发生错误:"+err.message);
	}
}

/**
*显示下一页
**/
HuidaGrid.prototype.showNext=function(){
	try{
		//若不为空显示下一页
		if(this.resultbuff.length>0){
			if(this.pageindex<this.getPageCount()){
				//清除显示
				this.clearDataArea();
				this.showPage(this.pageindex+1);
			}
		}else{
				this.pageindex=0;
			this.updatePageNumber();
		}
	}catch(err){
		alert("执行showNext时发生错误:"+err.message);
	}
}

/**
*重新载入页面(私有方法不推荐外部使用)
**/
HuidaGrid.prototype.reloadPage=function(){
	try{
		//若不为空显示下一页
		if(this.resultbuff.length>0){
			this.clearDataArea();
			this.showPage(this.pageindex);
		}
	}catch(err){
		alert("执行reloadPage时发生错误:"+err.message);
	}
}

/**
*绘制控制面板(私有方法不推荐外部使用)
**/
HuidaGrid.prototype.DrawPanel=function(){
	//获取tfoot,若不存在插入tfoot
	var oTfoot=this.datatable.getElementsByTagName("tfoot")[0];
	if(!oTfoot){
		oTfoot=this.datatable.createTFoot();
	}	
	
	var oTr,oTd;
	if(oTfoot.rows.length>0){
		oTr=oTfoot.rows[0];
		oTd=oTr.cells[0]		
	}else{
		oTr=document.createElement("tr");
		oTd=document.createElement("td");
		oTd.setAttribute("colSpan",100);
		oTr.appendChild(oTd);
		oTfoot.appendChild(oTr);		
	}

	
	if(document.all)
		oTd.className=this.panelcssclass;
	else
		oTd.setAttribute("class",this.panelcssclass);
		
	var strHtml=oTd.innerHTML;		
	oTd.innerHTML=strHtml+"<div id='gruid-div-panel' style='float:"+this.panelalign+"'>"
	     +"<div id='gruid-div-container-search' style='display:"+this.searchdisplay+"'>"
		 +"   <input type='text' id='gruid-txt-search' style='width:88px;'/>"
		 +"   <input type='button' id='gruid-btn-search' value='Search'/>"
		 +"</div>"
		 +"<div id='gruid-div-container-page'>"
		 +"   <img src='"+this.iconpath+"Panel_first.gif' id='gruid-img-first'>"
		 +"   <img src='"+this.iconpath+"Panel_pre.gif' id='gruid-img-pre'>"
		 +"   <div id='gruid-div-pagenumber'>"+this.pageindex+"/"+this.getPageCount()+"</div>"
		 +"   <img src='"+this.iconpath+"Panel_next.gif' id='gruid-img-next'>"
		 +"   <img src='"+this.iconpath+"Panel_last.gif' id='gruid-img-last'>"
		 +"</div>"
		 +"<div id='gruid-div-container-pagechange'>PAGE:"
		 +"   <input type='text' id='gruid-txt-pageinput'/>"
		 +"</div></div>";
}

/**
*事件处理函数(私有方法不推荐外部使用)
*@para {EventObject}e   浏览器event对象
*@para {String}strWord  搜索词
**/	
HuidaGrid.prototype.onsearch=function(e,strWord){
	var arrData=this.datamatrix;
	var arrResult=new Array();
	var nCellIndex=this.searchfield;
	var oReg=/<td.*?>(.*?)<\/.*?>/gi;
	var arrTdHtml;
	
	//查找符合条件的记录
	for(var i=0,nLen=arrData.length;i<nLen;i++){
		arrTdHtml=arrData[i].innerHTML.match(oReg);
		if(arrTdHtml[nCellIndex].indexOf(strWord)!=-1){
			arrResult.push(arrData[i]);
		}
	}
	
	//清空以前的搜索结果
	this.resultbuff=null;
	
	//将搜索结果传递给结果数组
	this.resultbuff=arrResult;
	this.pageindex=0;
	this.pagecount=arrResult.length;
	
	//显示查询结果
	this.showFirst();
}

HuidaGrid.prototype.onheaderclick=function(srcEl){
	//指定排序方式
	if(!srcEl.getAttribute("orderby")){
		srcEl.setAttribute("orderby","asc");
	}else{
		if(srcEl.getAttribute("orderby")=="asc")
			srcEl.setAttribute("orderby","desc");
		else
			srcEl.setAttribute("orderby","asc");	
	}
	
	//获取用户点击单元格在该行的索引
	var nCellIndex=(function(oTr,oTd){
		for(i=0,j=oTr.cells.length;i<j;i++){
			if(oTr.cells[i]===oTd)
				return i;
		}
		return -1;
	})(srcEl.parentNode,srcEl);
	var nCellCount=srcEl.parentNode.cells.length;
	
	//进行排序操作
	var boolState=srcEl.getAttribute("orderby")=="asc"?true:false;
	var nPStart=(this.pageindex-1)*this.pagesize;
	var nPEnd=this.pageindex*this.pagesize-1
	var i,j,nMaxItemIndex,nBufLen=this.resultbuff.length;
	var arrTdHtml,oReg=/<td[^>]*?>([\S\s]*?)<\/td[^>]*?>/gi;
	var temp,val_max,val_loop;
	var isAllNumber=true;

	//判断排序字段的数据类型是否为数字
	var nCellValue;
	for(i=nPStart;i<=nPEnd && i<this.resultbuff.length;i++){
		oReg.lastIndex=0;
		arrTdHtml=this.resultbuff[i].innerHTML.match(oReg);
		nCellValue=parseFloat(arrTdHtml[nCellIndex].stripTags());
		if(isNaN(nCellValue)){
			isAllNumber=false;
			break;
		}
	}
	
	//按选择排序法排序
	for(i=nPStart;i<nPEnd && i<nBufLen-1;i++){
		nMaxItemIndex=i;
		for(j=i+1;j<=nPEnd && j<nBufLen;j++){
			//判断是否为搜索列,若是按文本排序,否则按数字排序
			val_loop=this.resultbuff[j].innerHTML.match(oReg)[nCellIndex].stripTags();
			val_max=this.resultbuff[nMaxItemIndex].innerHTML.match(oReg)[nCellIndex].stripTags();		
			
			if(isAllNumber){
				val_loop=parseFloat(val_loop);
				val_max=parseFloat(val_max);				
			}		
			if(val_loop!=val_max && val_loop<val_max==boolState){
				nMaxItemIndex=j;
			}	
		}
		
		if(nMaxItemIndex!=i){
			temp=this.resultbuff[i]
			this.resultbuff[i]=this.resultbuff[nMaxItemIndex];
			this.resultbuff[nMaxItemIndex]=temp;
		}
	}
	
	//将排序后内容重新显示
	this.reloadPage();
}

/**
*得到页数(私有方法不推荐外部使用)
*return 页面数
**/
HuidaGrid.prototype.getPageCount=function(){
	//若未曾计算过，则先计算
	var _nCount=this.resultbuff.length;
	var _nSize=this.pagesize;
	return _nCount%_nSize==0?parseInt(_nCount/_nSize):parseInt(_nCount/_nSize)+1;
}

/**
*更新页号(私有方法不推荐外部使用)
**/
HuidaGrid.prototype.updatePageNumber=function(){
	try{
		//更新移动按钮页码
		$("gruid-div-pagenumber").innerHTML=this.pageindex+"/"+this.getPageCount();	
		//更新页码输入框页码
		$("gruid-txt-pageinput").value=this.pageindex;
	}catch(err){
		alert("执行updatePageNumber时发生错误:"+err.message);
	}
}

/**
*设置每页显示记录条数
**/
HuidaGrid.prototype.setPageSize=function(nPageSize){
	var oReg=/^\d+$/gi;
	if(nPageSize && oReg.test(nPageSize))
	   this.pagesize=nPageSize;
	else
	   this.pagesize=10;
}

/**
*设置搜索列
**/
HuidaGrid.prototype.setSearchField=function(oField){
	var oThead=this.header;
	var nIndex=0;
	if(typeof(oField)=="number"){
		nIndex=oField;
	}else{
		var oCells=oThead.rows[0].cells;
		for(var i in oCells){
			if(oCells[i].innerHTML==oField){
				nIndex=i;
				break;
			}
		}
	}
	this.searchfield=nIndex;
}

/**
*设置底部控制面版样式
*@para {String}strCssClassName
**/
HuidaGrid.prototype.setPanelCssClass=function(strCssClassName){
	this.panelcssclass=strCssClassName;
}

/**
*设置面板的对齐方式
**/
HuidaGrid.prototype.setPanelAlign=function(sPanelAlign){
	if(sPanelAlign && sPanelAlign=="right")
		this.panelalign=sPanelAlign;
	else
	    this.panelalign="left";
}

/**
*设置搜索页面显示或隐藏
**/
HuidaGrid.prototype.setSearchDisplay=function(sState){
	if(typeof(sState)=="string")
		sState=sState.toLowerCase();
		
    switch(sState){
		case "true":
		case true:
		case  1:
		case "display":
			sState="display";
			break;
		case "false":
		case false:
		case  0:
		case "none":
			sState="none";
			break;
 		default:
			sState="display";
	}
	this.searchdisplay=sState;
}

/**
*设置图片路径
*@para {String}sIconPath   图片路径
**/
HuidaGrid.prototype.setIconPath=function(sIconPath){
	if(sIconPath)
		this.iconpath=sIconPath;
	else
		this.iconpath="./images/";
}

/**
*设置面板所在的tfoot的css class
**/
HuidaGrid.prototype.setPanelCssClass=function(strCssClsName){
	if(strCssClsName)
		this.panelcssclass=sPanelCssClass;
	else
		this.panelcssclass="fb_result_head";
}

