/*
单输入元素即时编辑ajax代码
整理: zengfy 2007-11-14
示例: <span onclick="mouse(this,数据一,数据二,处理页地址,文本输入控件行数,列数,校验长度数)">文字</span>
上面的数据一,数据二将以以下方式发送给处理页 op=数据一&opid=数据二
一般情况是: 数据一用来确认操作方式,数据二表示查找编辑这条记录的唯一ID
文本输入控件行数,默认是一行,文本多时指定
*/

function mouse(obj,op,opid,url,inputRows,inputCols,checkLen){
	var tag = obj.firstChild.tagName;
	if(!inputRows) inputRows = 1;
	if (typeof(tag) != "undefined" && tag.toLowerCase() == "input"){
		return;
	}
	
	/* 保存原始的内容 */
	var org = obj.innerHTML;
	var oldclick = obj.onclick;
	var val = obj.innerText ? obj.innerText : obj.textContent;
	/* 创建一个输入框 */
	//var txt = document.createElement("INPUT");
	var txt = document.createElement("TEXTAREA");
	txt.value = val;
	if(inputCols > 0){
		txt.style.width = (inputCols*14) + "px" ;
	}else{
		txt.style.width = (obj.offsetWidth) + "px" ;
	}
	txt.rows = inputRows ;
	if(inputRows>1){
		txt.style.overflow='auto';
	}else{
		txt.style.overflow='hidden';
	}
	
	/* 隐藏对象中的内容，并将输入框加入到对象中 */
	obj.innerHTML = "";
	obj.appendChild(txt);
	obj.onclick = "";
	txt.focus();
	
	/* 编辑区输入事件处理函数 */
	txt.onkeypress = function(e){
		var evt = (typeof e == "undefined") ? window.event : e;

		if (evt.keyCode == 27){
			reset();
		}
		if (evt.keyCode == 13){
			if(inputRows==1){
				return false;
			}
		}
	}
	
	/* 编辑区失去焦点的处理函数 */
	txt.onblur = function(e){
		if(txt.value == org){
			reset();
		}else if(confirm("确认提交修改吗?")){
			if(trim(txt.value)==""){
				alert("内容不能为空");
				txt.focus();
			}else if(checkLen && len(txt.value) > checkLen){
				alert("内容长度不能超过"+(checkLen/2)+"个汉字");
				txt.focus();
			}else{
				var editvalue = bin2hex(txt.value);
				var pars = 'op=' + op + '&inputvalue=' + editvalue + '&opid=' + opid;
				if(url.indexOf('?')){
					pars += '&'+url.substr((url.indexOf('?')+1));
				}
				var myAjax = new Ajax.Request(
				url,
				{ 
				method: 'get',
				parameters: pars,
				onComplete: showspecialid
				});
			}
		}else{
			reset();
		}
	}
	 
	function showspecialid(originalRequest){
		reset(originalRequest.responseText);
	}
	
	function reset(responseText){
		if(responseText){
			if(responseText.indexOf("{#ERR#}")==0){
				alert(responseText.substr(7));
				obj.innerHTML = org;
			}else{
				obj.innerHTML = responseText;
			}
		}else{
			obj.innerHTML = org;
		}
	    $(obj).onclick = oldclick;		
	}
}