
//替换所有,添加到字符串的方法中
String.prototype.replaceAll = stringReplaceAll;
function  stringReplaceAll(AFindText,ARepText){
  raRegExp = new RegExp(AFindText,"g");
  return this.replace(raRegExp,ARepText)
}

//通过值得到下拉框显示的Text
function getSelectText(value,selectID){
	try{
		var selectObj = document.getElementById(selectID);
		for(var i=0;i<selectObj.options.length;i++){
			if($N(value,"") == selectObj.options[i].value)
				return selectObj.options[i].text;
		}
		return "";
	}catch(e){
		return "NULL";
	}
		
}

function disableButton(obj,state){
	try{
		//可能没有权限，以致此button不存在，而可能发生错误
		document.getElementById(obj).disabled = state;
	}catch(e){
	
	}
}
//获取符合like条件的值，在为空的时候返回空，让Ibatis可以提高查询效率
function getLikeValue(obj){
	var result = DWRUtil.getValue(obj);
	if(isEmpty(result)) return "";
	else return "%"+result+"%";
}

 //<script>
function thisDocHeight(){
 return eval((window.navigator.appVersion.indexOf("5.5")>0)?"((this.frameElement!=null)?this.frameElement.scrollHeight:this.document.documentElement.scrollHeight)" :"document.documentElement.scrollHeight");
}

function thisDocWidth(){
  return eval((window.navigator.appVersion.indexOf("5.5")>0)?"((this.frameElement!=null)?this.frameElement.scrollWidth:this.document.documentElement.scrollWidth)" :"document.documentElement.scrollWidth");
}
function string_escape(strVal){
	if(strVal == null || strVal == "")	return "";
	var strValue = strVal;
	strValue	=strValue.replace(/\&/g,"*");
	strValue	=strValue.replace(/\//g,"*");
	strValue	=strValue.replace(/\</g,"*");
	strValue	=strValue.replace(/\>/g,"*");
	strValue	=strValue.replace(/\'/g,"*");
	strValue	=strValue.replace(/\"/g,"*");
	strValue	=strValue.replace(/\;/g,"*");
	strValue	=strValue.replace(/\#/g,"-");
        strValue	=strValue.replace(/,/g,"??");
        strValue	=strValue.replace(/;/g,"??");
	return Trim(strValue) ;
}
function Trim(str){
	if (typeof(str) != 'string') return str;
	if (str == "") return "";
    var I,L ;
    I =0;
    L = str.length-1;
    while ((I<=L) && ( str.substr(I,1)==' ')) I++;
    if (I>L) return '';
    else {
        while ( str.substr(L,1)==' ') L--;
        return str.substring(I,L+1);
    }
	
}
//四舍五入数字,因为Math.round()有时会有问题
function  NumRound(num,size){  
	return Math.round  (num*Math.pow(10,size))/Math.pow(10,size);  
}  

function formatDecimal(value,defvalue){
	if(typeof defvalue=='undefined')
		value = $N(value,"0.00");
	else
		value = $N(value,defvalue);
	if(value == "0.00"||value=="") return value;
	return FormatFloat(value,2);
}

function FormatFloat(afloat,afterpoint) {
	var tmpfloat = parseFloat(afloat);
	var tmpint = parseInt(afterpoint);
	if (isNaN(tmpfloat) || isNaN(tmpint)) return "0"
	else return tmpfloat.toFixed(tmpint);
}

//取 uri的参数值,相当于jsp中的request.getParameter(),不过只能取get方式
function getParameter(key){
	var param = window.location.search;
	if(param!=null&&param.length>0){
		param = param.substr(1);
		var ps = param.split("&");
		for(var i=0;ps!=null&&i<ps.length;i++)
			if(ps[i].indexOf(key+"=")==0)
				return ps[i].substr((key+"=").length);
	}
}

//以下为列表中关于鼠标事件的代码
var oldColor = null;

function  MouseoverFunc(src){
   oldColor = src.style.backgroundColor;
   src.style.backgroundColor="#eeeeee";
}

function MouseoutFunc(src){
	if (oldColor != null)
	   src.style.backgroundColor = oldColor;
	else
	   src.style.backgroundColor="";
}

//---------------------------------------------------------
// 判断一个值是否为空,为空返回"",如有默认值参数则返回默认值
//---------------------------------------------------------
var $N = function(value,dv){
   if(isEmpty(value))
   	value = isEmpty(dv)?"":dv;
   return value;
}

//---------------------------------------------------------
// 判断是否为空
//---------------------------------------------------------
function isEmpty(value){
	try{
   		return (typeof value=='undefined'||value == null||(typeof value =="string" && value==""));
   	}catch(e){
   		//alert(e);
   		return true;	//如果异常，也表示空
   	}
}

function isMail(email){
    var pattern = /^([a-zA-Z0-9_\.-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    return pattern.test(email);
}
//---------------------------------------------------------
// 以下为table所需要的
//---------------------------------------------------------
//curElement为当前选中的页面元素,curObject为当前页面元素对应的数据对象
var curElement = null;
var curObject = null;

//---------------------------------------------------------
// 定义一个类，编辑后的数据,
//---------------------------------------------------------
function EditData(){
   this.succ = [];
   this.containIds = "";
   //操作失败的数据处理
   this.addFail = [];
   this.updFail = [];
   this.delFail = [];
}

//定义行跟列
var options = {
 rowCreator:function(options) {
	 var row = document.createElement("tr");
	 row.height = "20px";
	 row.onmouseover=function(){return MouseoverFunc(this);};
	 row.onmouseout=function(){return MouseoutFunc(this);};
	 row.onactivate=function(){return ClickFunc(this);};
	 row.ondblclick = function(){return f_DoubleClick(this);};
	 row.onclick=function(){return ClickFunc(this);};
	 return row;
	}
};
var failOptions = {
   rowCreator:function(options) {
    var row = document.createElement("tr");
    row.height = "18px";
    row.onmouseover=function(){return MouseoverFunc();};
    row.onmouseout=function(){return MouseoutFunc();};
    row.onactivate=function(){return ClickFunc(this);};
    row.onclick=function(){return ClickFunc(this);};
    row.ondblclick = function(){return f_DoubleClick(this);};
    row.style.backgroundColor="red";
    row.style.fontWeight="bold";
    return row;
  }
};
function f_DoubleClick(src){
	return;
}
//修改单元格，同时修改table框架中数据
function OnchangeFunc(src,field,callback){
   src.style.fontWeight="bold";
   var index = curElement.sectionRowIndex;
	curObject[field]=src.value;
   table.updateRow(index);
   if(!isEmpty(callback)) callback();
}
//修改单元格，同时修改table框架中数据,指定value(有时field的值不一定就是src.value)
function OnchangeFunc2(value,field,callback){
   var index = curElement.sectionRowIndex;
   
	var arrField = field.split('.');
   var cur = "curObject."+field;
	eval(cur+"='"+value+"'");
   table.updateRow(index);
   if(!isEmpty(callback)) callback();
}

//把当前记录标记为修改过的
function makeChanged(index){
	if(isEmpty(index))
		index = curElement.sectionRowIndex;
	table.updateRow(index);
}

function f_clickFunc(){}

//点击事件处理
function ClickFunc(src,callback) {
  if(src == curElement)
      return;
   curObject = table.data[src.sectionRowIndex];
   src.style.backgroundColor="#dddddd";
   oldColor = src.style.backgroundColor;
   if (curElement != null && curElement.tagName =='TR') 
      curElement.style.backgroundColor='';
   curElement = src;
   if(curObject==null||curObject==undefined)
   	curObject = cloneObject(table.data[0]);
   
   //TODO:以下为扩展,可能不同页面有其他一些扩展操作
   f_clickFunc(src);
}

//没有数据时
function  ClickFuncNull(){
	curObject = cloneObject(curObject);
	f_clickFunc();
}

var _emptyObject = new Object;
//新增一行,一行空数据,格式按前面定义好的
function NewBtnClick(callback){
   if(isEmpty(table)) table = new Table(null);
   if(typeof curObject!='undefined'){
   	_emptyObject = curObject;
   }else{
	   if(typeof _emptyObject =='undefined')
	   	  _emptyObject = new Object;
   }
   var data = cloneObject(_emptyObject);
   DWRUtil.insertRow(tableElement,data,cellFuncs,options);
   table.addRow(data);
   if(!isEmpty(callback)) callback();
   clickFirst();
}
//新增一行,Copy当前行数据,格式按前面定义好的
function CopyNewBtnClick(callback){
	if(isEmpty(table)) table = new Table(null);
	var data = copyObject(curObject);
	var arrData = new Array();
	arrData[0]=data;
	DWRUtil.addRows(tableElement,arrData,cellFuncs,options);//最后一行
	table.appendRow(data);
	if(!isEmpty(callback)) callback();
	clickFirst();
}
//在最后新增一行,格式按前面定义好的
function AppendNewBtnClick(callback){
	if(isEmpty(table)) table = new Table(null);
	var data = cloneObject(table.data[0]);
	var arrData = new Array();
	arrData[0]=data;
	DWRUtil.addRows(tableElement,arrData,cellFuncs,options);//最后一行
	table.appendRow(data);
	if(!isEmpty(callback)) callback();
	clickLast();
}
function DeleteBtnClick(callback){
   if(!isEmpty(callback)) callback();
   if (curElement && curElement!=null && curElement.tagName =='TR') {
      var index = curElement.sectionRowIndex;
      $(tableElement).deleteRow(index);
      table.deleteRow(index);
		if($(tableElement).rows(index))
      	$(tableElement).rows(index).click();
      else
      	clickFirst();
   }
}

//重新载入当前行的数据.
function ReloadRow(index,callback){
	var cellIndex = 0;
	try{
		var curCell = window.event.srcElement;
		curCell = curCell.parentElement;
		cellIndex = curCell.cellIndex%$(tableElement).rows[index].childNodes.length;
		if(window.event.keyCode == 13 && cellIndex>=0)  cellIndex--; //如果是回车，将不跳入下一个
	}catch(e){}
	options.rowData = table.data[index];
	var tr = DWRUtil._addRowInner(cellFuncs, options);
	var t = $(tableElement).rows[index];
	$(tableElement).replaceChild(tr,t);
	//ClickFunc(tr);
	//SetFocus(tr,cellIndex);	//设置光标到下一个输入框
	if(!isEmpty(callback)) callback;
}
//设置光标到从几列开始的下一个有效输入框
function SetFocus(tr,index){
	try{
	if(typeof index == 'undefined') index = 0;
	else index++;
	for(var i=index;i<tr.childNodes.length;i++){
		var nodes = tr.childNodes[i].getElementsByTagName("input");
		for(var j=0;j<nodes.length;j++){
			var node = nodes[j];
			if(node&&node.tabIndex!=-1&&node.tagName=='INPUT'){
				if(!node.readOnly && !node.disabled){ //输入框是否有效输入
					node.focus();
					node.select();
					return;
				}
			}
		}
	}
	}catch(e){}
}


//---------------------------------------------------------
//		分页
//---------------------------------------------------------
function nextBtnClick(){
	page += 1;
	refreshPage();
}
function priorBtnClick(){
	page -= 1;
	refreshPage();
}
function firstBtnClick(){
	page = 1;
	refreshPage();
}
function lastBtnClick(){
	page = totalPage;
	refreshPage();
}
function gotoClick(){
	page = parseInt(DWRUtil.getValue("page"));
	pageSize = document.getElementById("_pageSize").value;
	refreshPage();
	manager.getCount(o,showPageFoot);
}

//设置翻页的一些值
function showPageFoot(count){
	totalRecord = count;
	totalPage = Math.round(totalRecord/pageSize);
	if(totalRecord%pageSize<pageSize/2)
		totalPage+=1;
	DWRUtil.setValue("allRecord",totalRecord);
	DWRUtil.setValue("totalPage",totalPage);
	DWRUtil.setValue("page",page);
	DWRUtil.setValue("_pageSize",pageSize);
}
//刷新页面数据
function refreshPage(){
	DWRUtil.useLoadingMessage("<img src='../images/loading.gif' style='position:relative;top:3px;'>  Loading...");
	if(typeof(pageSize) =="undefined" || pageSize==0){//如果不需要分页，直接加载数据
		manager.find(o,pageReload);
	}else{							//加载数据并分页
		if(page>totalPage)
			page = totalPage;
		if(page<1)
			page = 1;
		o.previousCount = pageSize*(page-1);
		o.pageSize = pageSize;
		manager.find(o,pageReload);
		DWRUtil.setValue("page",page);
	}
}

var editData = new EditData();
var swRefresh = 0;//页面刷新开关
var swSave = false;//防止重复保存
//=========================================================
//	保存修改，把页面的增、删、改的数据一起处理。处理完后重新显示
//========================================================
function SaveBtnClick(beforeSave){
	if(swSave) return;
	swSave = true;
   if(!validate(table.addRows)||!validate(table.updateRows)){
   		swSave = false;
   		return;
   }
   	
   if(table.addRows.length==0&&table.updateRows.length==0&&table.deleteRows.length==0){
   	  swSave = false;
      return; 
     }
   //保存之前，整理数据
   if(!isEmpty(beforeSave)) beforeSave();
   
   DWRUtil.useLoadingMessage("  数据保存中......");
   editData = new EditData();
   
   //增加,删除原有数据，将从服务器操作后的数据显示出来
   if(table.addRows.length>0){
   	swRefresh++;
      manager.creates(table.addRows,function(data){
         for(var i=0;i<data.length;i++){
            if(data[i].operateFlag==1){
            	data[i].operateFlag=0;
               editData.addFail[editData.addFail.length]=data[i];
            }
            else{
               editData.succ[editData.succ.length]=data[i];
            	editData.containIds+=data[i][key]+",";
            }
         }
         switchRefresh();
      });
   }
   //修改
   if(table.updateRows.length>0){
   	swRefresh++;
      manager.updates(table.updateRows,function(data){
         for(var i=0;i<data.length;i++){
            if(data[i].operateFlag==1){
               editData.updFail[editData.updFail.length]=data[i];
            }else
               editData.succ[editData.succ.length]=data[i];
            if(key != "")	//如果不需要刷新的时候改动行在顶部，可以设置key为空
            	editData.containIds+=data[i][key]+",";
         }
         switchRefresh();
      });
   }
   //删除
   if(table.deleteRows.length>0){
   	swRefresh++;
      manager.deletes(table.deleteRows,function(data){
         table.deleteRows=[];
         for(var i=0;i<data.length;i++)
            if(data[i].operateFlag==1){
               editData.delFail[editData.fail.length]=data[i];
               editData.containIds+=data[i][key]+",";
            }
         switchRefresh();
         });
   }
}

//同步开关.主要作用是保证几个manager的异步操作之后再调用 refreshPage()
function switchRefresh(){
	swRefresh--;
	if(swRefresh==0){
  		editData.containIds = editData.containIds.substr(0,editData.containIds.length-1);
   	o.containIds=$N(editData.containIds);
   	if($("_pageSize")&&$("page"))//仅对需要翻页的页面提供更新记录数的操作
   		manager.getCount(o,showPageFoot);//取当前查询记录数
   	return refreshPage();
	}
}

//---------------------------------------------------------
// 页面编辑保存后重新组织页面数据
//---------------------------------------------------------
function pageReload(data){
   table = new Table(null);
   DWRUtil.removeAllRows(tableElement);
   if((!data||data.length==0)&&(!editData.succ||editData.succ.length==0)){
   		f_pageReload();
   		return;
   }
   var error = "";
   var bNeedTop = true;
   if(typeof(key) == "undefined" || isEmpty(key) || key=="" || typeof(pageSize) =="undefined" ) bNeedTop = false; //如果不需要刷新的时候改动行在顶部，可以设置key为空
   if(!isEmpty(editData.addFail)&&editData.addFail.length>0){
   	if(bNeedTop)	
   		DWRUtil.addRows(tableElement,editData.addFail,cellFuncs,failOptions);
   	for(var i=0;i<editData.addFail.length;i++){
   		if(!isEmpty(editData.addFail[i].operateError)) 	error+= "新增失败原因："  + editData.addFail[i].operateError + "\n";
   		table.addRow(editData.addFail[i]);
   	}
   	error+="有 "+editData.addFail.length+" 条记录添加失败.\n";
   }
   if(!isEmpty(editData.updFail)&&editData.updFail.length>0){
   	if(bNeedTop)
   		DWRUtil.addRows(tableElement,editData.updFail,cellFuncs,failOptions);
   	table.concat(editData.updFail);
   	for(var i=0;i<editData.updFail.length;i++)
	   	table.updateRow(table.size()-editData.updFail.length+i);
   	error+="有 "+editData.updFail.length+" 条记录修改失败.\n";
   }
   if(!isEmpty(editData.delFail)&&editData.delFail.length>0){
   	if(bNeedTop)
   		DWRUtil.addRows(tableElement,editData.delFail,cellFuncs,failOptions);
   	table.concat(editData.delFail);
   	for(var i=0;i<editData.delFail.length;i++)
   		table.deleteRow(table.size()-editData.delFail.length+i);
   	error+="有 "+editData.delFail.length+" 条记录删除失败.\n";
   }
   if(bNeedTop){
	   DWRUtil.addRows(tableElement,editData.succ,cellFuncs,options);
	   table.concat(editData.succ);
	}   
   DWRUtil.addRows(tableElement,data,cellFuncs,options);
   table.concat(data);
	
   if(error!="")
   	alert(error);
   else
   	clickFirst();
	//以下操作是清除本次操作的数据
   o.containIds="";
   editData=new EditData();
   //TODO:扩展:各页面自己的扩展操作
   f_pageReload();
   swSave = false;
}

//---------------------------------------------------------
// 击中首行
//---------------------------------------------------------
function clickFirst(){
   clickRow(0);
}
//---------------------------------------------------------
// 击中末行
//---------------------------------------------------------
function clickLast(){
   clickRow($(tableElement).rows.length-1);
}
//---------------------------------------------------------
// 击中某行
//---------------------------------------------------------
function clickRow(rowNo){
	if(rowNo<0 || rowNo>=$(tableElement).rows.length) {
		ClickFuncNull();
		return;
	}
   if($(tableElement).rows[rowNo]){
      if(document.all)
	      $(tableElement).rows[rowNo].click();
   	  else{//浏览器兼容,TODO:还有问题,有时间再解决
	   		var evt = document.createEvent("MouseEvents");
			evt.initEvent("click", true, true);
			$(tableElement).rows[rowNo].dispatchEvent(evt);
   		}
   	SetFocus($(tableElement).rows[rowNo]);
   }else
   	ClickFuncNull();
}


//传一个对象返回一个此对象的结构.用于在js中自动构造java对象的结构
function cloneObject(src){
	var newObject = new Object;
	if(typeof src == 'undefined'||src==null||typeof src != 'object')
		return newObject;
	for(var porp in src){
//		if(porp = 'creatorName')
//			alert(typeof src[porp]);
//		if(typeof src[porp]=='object'&&src[porp].join){//is Array,TODO,这里还有要完善的地方,暂时只考虑到Array一层,array里面没考虑.
//			newObject[porp] = new Array();
//		}else{
			switch (typeof src[porp]) {
				case 'object':newObject[porp] = '';break;
				case 'string':newObject[porp] = '';break;
				default: newObject[porp]='';
			}
//		}
	}
	return newObject;
}
//传一个对象返回一个此对象的结构及值.用于在js中自动构造java对象的结构
function copyObject(src){
	var newObject = new Object;
	if(typeof src == 'undefined'||src==null||typeof src != 'object')
		return newObject;
	for(var porp in src)
		newObject[porp]=src[porp];
	return newObject;
}
//提示信息
function alertMessage(msg){
	 var disabledZone = $('disabledZone');
    if (!disabledZone) {
      disabledZone = document.createElement('div');
      disabledZone.setAttribute('id', 'disabledZone');
      disabledZone.style.position = "absolute";
      disabledZone.style.zIndex = "1000";
      disabledZone.style.left = "0px";
      disabledZone.style.top = "0px";
      disabledZone.style.width = "100%";
      disabledZone.style.height = "100%";
      document.body.appendChild(disabledZone);
      var messageZone = document.createElement('div');
      messageZone.setAttribute('id', 'messageZone');
      messageZone.style.position = "absolute";
      messageZone.style.top = "0px";
      messageZone.style.right = "0px";
      messageZone.style.background = "red";
      messageZone.style.color = "white";
      messageZone.style.fontFamily = "Arial,Helvetica,sans-serif";
      messageZone.style.padding = "4px";
      disabledZone.appendChild(messageZone);
      var text = document.createTextNode(msg);
      messageZone.appendChild(text);
      disabledZone.style.visibility = 'visible';
    } else {
      $('messageZone').innerHTML = msg;
      disabledZone.style.visibility = 'visible';
    }
    window.setTimeout(function(){disabledZone.style.visibility = 'hidden';},6000);
}


//输入分页按钮
function writeRootPage(){
	document.write("<TD width='*'></TD>");
	document.write("<TD width='40px'><a href='#' onclick='firstBtnClick()' title='"+_tableFooterLabels["firstpage"]+"'>首页</a></TD>");
	document.write("<TD width='40px'><a href='#' onclick='priorBtnClick()' title='"+_tableFooterLabels["previouse"]+"'>上一页</a></TD>");
	document.write("<TD width='40px'><a href='#' onclick='nextBtnClick()' title='"+_tableFooterLabels["nextpage"]+"'>下一页</a></TD>");
	document.write("<TD width='40px'><a href='#' onclick='lastBtnClick()' title='"+_tableFooterLabels["lastpage"]+"'>末页</a></TD>");
	document.write("<TD width='20px'><input id='page' style='border: 0px; border-bottom: 1px solid #333;' value='' style='width:20px;'></TD>");
	document.write("<TD width='10px'>/</TD>");
	document.write("<TD width='30px'><input id=totalPage style='border: 0px;' readonly value='' style='width:20px;'></TD>");
	document.write("<TD width='30px'>页</TD>");
	document.write("<TD width='80px' align='right'>每页：<input id='_pageSize' style='border: 0px; border-bottom: 1px solid #333;' value='' style='width:20px;'></TD>");
	document.write("<TD width='110px' align='left'>&nbsp;/&nbsp;记录数：<span id='allRecord'></span></TD>");
	document.write("<TD width='30px'><input id=GotoBtn type='button' class='Button2' onclick='return gotoClick();' value='Go'></TD>");
}

function writeRootPageNew(){
	document.write("<TD width='*'></TD>");
	document.write("<TD width='140px'><a href='#' onclick='firstBtnClick()' title='First'><img src='../images/button_begins.gif' border='0'></a>&nbsp;&nbsp;&nbsp;&nbsp;");
	document.write("<a href='#' onclick='priorBtnClick()' title='Previous'><img src='../images/button_prvs.gif' border='0'></a>&nbsp;&nbsp;&nbsp;&nbsp;");
	document.write("<a href='#' onclick='nextBtnClick()' title='Next'><img src='../images/button_nexts.gif' border='0'></a>&nbsp;&nbsp;&nbsp;&nbsp;");
	document.write("<a href='#' onclick='lastBtnClick()' title='Last'><img src='../images/button_ends.gif' border='0'></a></TD>");
	document.write("<TD width='120px'><label id='page'></label>");
	document.write("&nbsp;&nbsp;/&nbsp;&nbsp;");
	document.write("<label id='totalPage'></label>");
	document.write("&nbsp;&nbsp;"+_tableFooterLabels["page"]+"</TD>");
	document.write("<TD width='80px' align='right' valign='middle'>"+_tableFooterLabels["perpage"]+":</TD>");
	document.write("<TD width='22px'><input id='_pageSize' class='input4' value='' style='width:20px'></TD>");
	document.write("<TD width='110px' align='left'>/&nbsp;"+_tableFooterLabels["recordcount"]+":<label id='allRecord'></label></TD>");
	document.write("<TD width='30px'><input id='GotoBtn' type='button' class='Button2' onclick='return gotoClick();' value='Go' ></TD>");
}


//判断是否已经存在编号，可以公共
function checkExist(src,field){
   src.style.fontWeight="bold";
   var index = curElement.sectionRowIndex;
   src.value = Trim(src.value);
   curObject[field] = src.value;
   var conditionObject = new Object();
   conditionObject[field] = src.value;
   if(src.value != "") {
      manager.checkExist(conditionObject,function(data){
         if(data==true) {
             alert("输入的记录已存在！请重新填写！");
             src.value = "";
             curObject[field] = "";
             src.focus();
         }
      });  
   }
   table.updateRow(index);
}

//排序,点击列表的标题进行排序(只对页面内容进行排序)
var lastColName=null;
function sortByColumn(src,colName,virDir){
	var imgUp = virDir+"images/sortup.gif",imgDown = virDir+"images/sortdown.gif";
	if(!table.data) return;
	
	var sorted = null;
	if(colName==lastColName){//同一列多次排序
		if(src.all("sortImg")&&src.all("sortImg").src.indexOf(imgUp.substr(5))!=-1)
			src.all("sortImg").src=imgDown;
		else
			src.all("sortImg").src=imgUp;
		sorted = table.data.reverse();
	}else{//第一次击此列,先把其他列上的图片去掉.再加此列向下的图片(默认为升序)
		var img = src.parentElement.all("sortImg");
		if(img)
			img.parentElement.removeChild(img);
		
		img = document.createElement("IMG");
		img.id="sortImg";
		img.src=imgDown;
		src.appendChild(img);
		
		var compareFunc = function(left, right){
			var lname = $N(left[colName]);
	  		var rname = $N(right[colName]);
	  		if (lname < rname) return +1;
		   if (lname > rname) return -1;
		   return 0;
		}
		sorted = table.data.sort(compareFunc);
		lastColName = colName;
	}
	pageReload(sorted);

}

//生成一个Input,用于显示列表时定义内容 
function createCell(value,className,readOnly,name){
	readOnly = typeof readOnly == 'undefind'||readOnly;
	
	var _input = document.createElement("input");
	_input.value=$N(value);
	_input.className=$N(className);
	_input.readOnly=readOnly;
	if(name){
		_input.name = name;
		_input.detachEvent("onchange",function(){OnchangeFunc(this,name);});
	}
	if(readOnly) _input.tabIndex=-1;
	return _input;
}

//选择所有的记录,tag是checkbox的name
function selectAll(src,tag) {
	var templets = document.getElementsByName(tag);
	var checked = src.checked;
	for(var i=0;i<templets.length;++i){
		if(!templets[i].disabled)
	    	templets[i].checked = checked;
	}
}

//取出用户选定的记录
function getOpIDs(tag){
	ids = new Array();
	selectedObj = new Array();
	var orderIDs = document.getElementsByName(tag);
	for(var i=0;i<orderIDs.length;i++)
		if(orderIDs[i].checked){
			ids[ids.length]=orderIDs[i].value;
			selectedObj[selectedObj.length]=table.data[i];
		}
	return ids;
}


//将一个Object[]按提供的属性转化成为一个Map.
//arr:待转化的数组,kp:key的属性名,vp:value的属性名
function array2map(arr,kp,vp){
	var m =new Object();
	if(typeof arr=='undefined'||!arr||arr.length==0) return m;
	
	for(var i=0; i<arr.length; i++) {
		var key = arr[i][kp];
		var value = arr[i][vp];
		m[key]=value;
	}
	return m;
}


/**
 * 离开页面时提示.
 * 提示的条件是当_blnCloseWindow=true或传入一个function判断.
 * 页面调用时将ShowConfirmClose()放到onload中.
 * 页面内容改动时将_blnCloseWindow设为true
 * 
 * 或
 * 在onload中绑定ShowConfirmClose(function),传入判断方法
 *
 * 或 参考 mytime.jsp
 *
 * 目前还不支持firefox
 */
var _strConfirmCloseMessage="Changes have been made to the data. Do you want to save changes before leaving this page?";
var _blnCloseWindow = false;
function ConfirmClose() {
	var func=function(){return _blnCloseWindow;};
	if(arguments.length>0)
		func = arguments[0];
	
	if(func.call()==true)
    window.event.returnValue = _strConfirmCloseMessage;
}

function ShowConfirmClose(func) {
	if(typeof(func)!='undefined'&&typeof(func)=='function')
    	document.body.onbeforeunload = function(){ return ConfirmClose(func)};
	else
		document.body.onbeforeunload = ConfirmClose;
}

function formatPrice(value,defvalue){
	if(typeof defvalue=='undefined')
		value = $N(value,"0");
	else
		value = $N(value,defvalue);
	if(value == "0"||value=="") return value;
	return FormatFloat(value,"0.00");
}

function FormatFloat(afloat,afterpoint) {
	var tmpfloat = parseFloat(afloat);
	var tmpint = parseInt(afterpoint);
	if (isNaN(tmpfloat) || isNaN(tmpint)) return "0"
	else return tmpfloat.toFixed(tmpint);
}

// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	if(typeof date=='undefined'||date==null) return;
	if(typeof format== "undefined") format = _dateFormat;
	if(typeof date != 'object') return;
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	if(result.indexOf("1900")>=0) result = "";	
	return result;
}
	

