//localStorage,
var arrLayerIndex = new Array();
var virtualPath=getVirtualPath();
String.prototype.querystring = function(name){var reg = new RegExp("(^|&|\\?)"+ name +"=([^&]*)(&|$)","i"),r; if (r=this.match(reg)){return r[2]; }return ""; }
var _elements = document.getElementsByTagName('script');
var _element=_elements[_elements.length-1];
var _src=_element.getAttribute("src");
var _ver=_src.querystring("ver");

/*基础*/
document.write('<script src="' + virtualPath + 'Scripts/jquery.js"></script>');
document.write('<script src="' + virtualPath + 'Scripts/eketeam.js?ver=' + _ver + '"></script>');
document.write('<script src="' + virtualPath + 'Scripts/Circle.js?ver=' + _ver + '"></script>');
//if(navigator.userAgent.toLowerCase().indexOf("msie")>0) 
if(window.attachEvent)
{
	document.write('<script src="' + virtualPath + 'Scripts/ajaxfileupload.js"><\/script>');
} 
﻿document.write('<script src="' + virtualPath + 'Plugins/eControls/eControls.js?ver=' + _ver + '"></script>');
/*移动端日期控件*/
document.write('<script src="' + virtualPath + 'Scripts/rolldate.min.js"></script>');
/*kindeditor星级控件*/
document.write('<script src="' + virtualPath + 'Scripts/jquery.raty.min.js"></script>');
/*layui*/
document.write('<script src="' + virtualPath + 'Plugins/layui226/layui.all.js"></script>');
document.write('<script src="' + virtualPath + 'Plugins/swiper342/swiper342.min.js"></script>');
document.write('<script src="' + virtualPath + 'Plugins/eViewer/eViewer.js"></script>');

/*AntV报表*/
﻿//document.write('<script src="' + virtualPath + 'Plugins/AntV/g2.min.js"><\/script>');
//document.write('<script src="' + virtualPath + 'Plugins/AntV/data-set.min.js"><\/script>');
/*kindeditor编辑器*/
﻿//document.write('<script src="' + virtualPath + 'Plugins/kindeditor351/kindeditor.js"><\/script>');
/*百度编辑器*/
//document.write('<script src="' + virtualPath + 'Plugins/ueditor1.4.3.3/ueditor.config.js"><\/script>');
//document.write('<script src="' + virtualPath + 'Plugins/ueditor1.4.3.3/ueditor.all.min.js"><\/script>');
//document.write('<script src="' + virtualPath + 'Plugins/ueditor1.4.3.3/lang/zh-cn/zh-cn.js"><\/script>');
/*ACE编辑器*/
﻿//document.write('<script src="' + virtualPath + 'Plugins/ace/ace.js"><\/script>');
//document.write('<script src="' + virtualPath + 'Plugins/ace/ext-language_tools.js"><\/script>');


function getVirtualPath()
{
	var elements = document.getElementsByTagName('script');
	var element=elements[elements.length-1];
	var src=element.getAttribute("src");
	if(src.toLowerCase().indexOf("/")==0)
	{
		var i= src.toLowerCase().indexOf("/scripts/");
		if(i>0)
		{
			return src.substring(0,i+1);
		}
	}
	if(src.toLowerCase().indexOf("http")>-1)
	{
		var i= src.toLowerCase().indexOf("/scripts/");
		if(i>0)
		{
			return src.substring(0,i+1);
		}
	}
	//if(src.startsWith("/")){return "/";}
	if(src.indexOf("/")==0){return "/";}
	var virtualPath="";
	if(src.indexOf("../")>-1)
	{
		for(var i=0;i<src.match(/\.\.\//ig).length;i++)
		{
			virtualPath+="../";
		}
	}
	return virtualPath;
}
function treecheckbox_selectall(obj)
{
	$(obj).parent().find("input[type='checkbox']").prop("checked",true);
}
function treecheckbox_invert(obj)
{
	$(obj).parent().find("input[type='checkbox']").each(function(i,el){
		el.checked=!el.checked;
    });
}
function treecheckbox_cancel(obj)
{
	$(obj).parent().find("input[type='checkbox']").prop("checked",false);
}
function getAction()
{
	return document.location.href.getquerystring("act");
}
function TreeModelUpdate()
{
    if (treefromact == "del") {
        var tr = $("tr[eRowID='" + treefromid + "']");
        var parid = tr.attr("parentid");
        if (parid.length > 0)
        {
            var trs = tr.parents("tbody:first").find("tr[parentid='" + parid + "']");
            if (trs.length == 1)
            {
                var ptr = $("tr[eRowID='" + parid + "']");
                if (ptr.find(".treeItem a").hasClass("open")) { ptr.find(".treeItem a").removeClass("open"); }
                if (ptr.find(".treeItem a").hasClass("close")) { ptr.find(".treeItem a").removeClass("close"); }
            }
        }
        hideTreeModelTrs(tr);
        tr.remove();

    }
    else if (treefromact == "add") {
        var url = document.location.href;
        url = url.removequerystring("page");
        url = url.addquerystring("parid", treefrompid);
        $.ajax({
            type: "get",
            async: false,
            url: url,
            dataType: "json",
            success: function (data) {
                if (typeof (data.trs) != "undefined") {
                    if (treefrompid.length > 0)
                    {
                        var tr = $("tr[eRowID='" + treefrompid + "']");
                        var a = tr.find(".treeItem a");
                        if (!a.hasClass("open") && !a.hasClass("close")) {
                            a.addClass("close");
                            a.attr("onclick", "getTreeModelList(this,'" + treefrompid + "');");
                            //a.attr("onclick", "showTreeModelList(this);");
                        }
                        else {
                            var clickstr = a.attr("onclick");
                            if (a.hasClass("open"))
                            {
                                var url = document.location.href;
                                url = url.removequerystring("page");
                                url = url.addquerystring("parid", treefrompid);
                                $.ajax({
                                    type: "get",
                                    async: false,
                                    url: url,
                                    dataType: "json",
                                    success: function (data) {
                                        if (typeof (data.trs) != "undefined") {
                                            removeTreeModelTrs(tr);
                                            tr.after(data.trs);
                                            var _width = parseInt(a.get(0).parentNode.style.textIndent);
                                            a.parents("tbody:first").find("tr[parentid='" + treefrompid + "'] .treeItem").css("text-indent", (_width + 25) + "px");
                                        }
                                    }
                                });
                                return;
                            }
                            if (a.hasClass("close"))
                            {
                                removeTreeModelTrs(tr);
                                a.attr("onclick", "getTreeModelList(this,'" + treefrompid + "');");
                                return;
                            }
                        }
                    }
                    else
                    {
                        $(".eDataTable tbody tr").remove();
                        $(".eDataTable tbody").append(data.trs);
                    }
                }
            }
        });
    }
    else {
        var tr = $("tr[eRowID='" + treefromid + "']");
        replaceTreeModelTr(tr);
    }
}
function replaceTreeModelTr(tr)
{
    var url = document.location.href;
    url = url.removequerystring("page");
    url = url.addquerystring("rowid", treefromid);
    $.ajax({
        type: "get",
        async: false,
        url: url,
        dataType: "json",
        success: function (data) {
            if (typeof (data.trs) != "undefined") {
                var odiv = tr.find(".treeItem");
                tr.attr("eRowID", treefromid + "_bak");
                tr.after(data.trs);
                tr.hide();
                var ntr = $("tr[eRowID='" + treefromid + "']");
                var ndiv = ntr.find(".treeItem");
                ndiv.attr("style", odiv.attr("style"));
                ndiv.find("a").attr("class", odiv.find("a").attr("class"));
                ndiv.find("a").attr("onclick", odiv.find("a").attr("onclick"));
                tr.remove();
                //tr.prop("outerHTML", data.trs);////data.table.decode()                  
                //var ntr = document.createTextNode();//tr.replaceWith()               
            }
        }
    });
}
function showTreeModelTrs(tr)
{
    var parid = tr.attr("eRowID");
	var trs = tr.parents("tbody:first").find("tr[parentid='" + parid + "']");
	trs.each(function(i,el){
		$(this).show();
		if($(this).find(".treeItem .icon.open").length>0)
		{
			showTreeModelTrs($(this));
		}
	});
}
function hideTreeModelTrs(tr)
{
    var parid = tr.attr("eRowID");
	var trs = tr.parents("tbody:first").find("tr[parentid='" + parid + "']");
	trs.each(function(i,el){
		$(this).hide();
		hideTreeModelTrs($(this));
	});	
}
function removeTreeModelTrs(tr) {
    var parid = tr.attr("eRowID");
    var trs = tr.parents("tbody:first").find("tr[parentid='" + parid + "']");
    trs.each(function (i, el) {       
        removeTreeModelTrs($(this));
        $(this).remove();
    });
}
function showTreeModelList(obj)
{
	var tr=$(obj).parents("tr:first");
	var parid = tr.attr("eRowID");
	var trs = $(tr).parents("tbody:first").find("tr[parentid='" + parid + "']");
	if($(obj).hasClass("close"))
	{
		 $(obj).removeClass("close");
		 $(obj).addClass("open");
		 showTreeModelTrs(tr);
		 return;
	}
	if($(obj).hasClass("open"))
	{
		$(obj).removeClass("open");
		$(obj).addClass("close");
		hideTreeModelTrs(tr);
		return;
	}
};
function getTreeModelList(obj,parid)
{
	if(typeof(event.cancelBubble) != "undefined"){event.cancelBubble=true;if(typeof(event.returnValue) != "undefined"){event.returnValue=false;}}
	else { event.stopPropagation(); event.preventDefault(); }
	var url=document.location.href;
	url = url.removequerystring("page");
	url = url.addquerystring("parid", parid);
	$.ajax({
		   type: "get",
		   async: false,
		   url:url,
		   dataType: "json",
		   success: function(data)
		   {
			   if(typeof(data.trs)!="undefined")
			   {
				   var tr=$(obj).parents("tr:first");	   
				   tr.after(data.trs);				   
				   $(obj).removeClass("close");
				   $(obj).addClass("open");
				   $(obj).attr("onclick","showTreeModelList(this);");
				   var _width=parseInt(obj.parentNode.style.textIndent);				    
				   $(obj).parents("tbody:first").find("tr[parentid='" + parid + "'] .treeItem").css("text-indent", (_width + 25) + "px");
				   if (typeof (etable_init) == "function") {
				       etable_init();
				   }
			   }
		   }
	});
}
function addrToLocation(addr)
{
	var result={};
	var url = virtualPath + "Plugins/Tencent/qqmap/addrToLocation.aspx?addr="+ addr +"&t=" + now();
	$.ajax({
        type: 'get',
        url: url,
		async: false,
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
		result=data;
        },
		error: function (XMLHttpRequest, textStatus, errorThrown) {
		}
    });	
	return result;
}
function addButton(boxid,text,href,fun,target)
{
	var box=$("#" + boxid);	
	if(box.length==0) return;
	if(!text||text.length==0) text="按钮";
	if(!href||href.length==0) href="javascript:;";
	fun=fun||"";
	target=target||"";
	

	var html='';
	if(IsMobile())
	{
	    html = '<a href="' + href + '" class="button" style="padding-left:10px;padding-right:10px;margin-left:5px;"' + (fun.length == 0 ? '' : ' onclick="' + fun + '"') + (target.length == 0 ? '' : ' target="_blank"') + '><span style="margin-right:0px;padding-right:0px;">' + text + '</span></a>';

	}
	else
	{
	    html='<a href="'+ href +'" class="button" style="padding-left:10px;padding-right:10px;margin-left:5px;"'+ (fun.length==0?'': ' onclick="'+ fun +'"' ) + (target.length==0?'':' target="_blank"')+'><span style="margin-right:0px;padding-right:0px;">'+ text+'</span></a>';
	    //html = '<a href="' + href + '" class="Button"' + (fun.length == 0 ? '' : ' onclick="' + fun + '"') + (target.length == 0 ? '' : ' target="_blank"') + '>' + text + '</a>';
	}	
	box.append(html);
}
function number_minus(obj)
{
	var par=$(obj).parent();
	var ipt=par.find(".number");
	var step=ipt.attr("step")||1;
	var val=$(ipt).val()||0;	
	var value=parseFloat(val) - parseFloat(step);
	var minvalue=$(ipt).attr("minvalue");
	if(minvalue && minvalue.length>0 && value<parseFloat(minvalue))value=minvalue;
	ipt.val(value);

}
function number_plus(obj)
{
	var par=$(obj).parent();
	var ipt=par.find(".number");	
	var step=ipt.attr("step")||1;
	var val=$(ipt).val()||0;
	var value=parseFloat(val) + parseFloat(step);
	var maxvalue=$(ipt).attr("maxvalue");
	if(maxvalue && maxvalue.length > 0 && value > parseFloat(maxvalue)) value=maxvalue;
	ipt.val(value);

}
function getDistance(GPSLng,GPSLat,Lng,Lat)
{
	var result = (6378137.0 * Math.acos(Math.sin(GPSLat / 180 * Math.PI) * Math.sin(Lat / 180 * Math.PI) + Math.cos(GPSLat / 180 * Math.PI) * Math.cos(Lat / 180 * Math.PI) * Math.cos((GPSLng - Lng) / 180 * Math.PI))) / 1;
	return result;
}
/*
function getDistance2(lon1, lat1, lon2, lat2) {
    var toRad = (deg) => deg * Math.PI / 180;
    var R = 6371000; // 地球半径（米）
    
    var radLat1 = toRad(lat1);
    var radLon1 = toRad(lon1);
    var radLat2 = toRad(lat2);
    var radLon2 = toRad(lon2);
    
    var dlat = radLat2 - radLat1;
    var dlon = radLon2 - radLon1;
    
    var a = Math.sin(dlat / 2) ** 2 +
              Math.cos(radLat1) * Math.cos(radLat2) * Math.sin(dlon / 2) ** 2;
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    
    return R * c;
}
*/
function hideField(id,area)
{
	//alert($("#M42_F21,#M42_F22").length);
	area=area||$;
	var ipt=area.find("#" + id);
	var par=ipt.parents("li:first");
	ipt.attr("notnull",false);
	par.hide();
}
function showField(id,notnull,area)
{	
	area=area||$;
	var ipt=area.find("#" + id);
	var par=ipt.parents("li:first");
	ipt.attr("notnull",notnull);
	par.show();
	var field=par.find("div:eq(0)");
	if(notnull)
	{		
		if(field.text().indexOf("*")==-1)
		{
			field.prepend("<ins>*</ins>");
		}
	}
	else
	{
		field.find("ins").remove();
	}
}
function setSwitcher(obj)
{
	var prev=$(obj).prev();
	prev.val(obj.checked ? 1 : 0);
	//alert(prev.attr("type"));
}
function setfillValue(id,value,mult)
{
	if(mult)
	{
		var val=$("#" + id).val();
		if(val.length>0) val+="\n";
		val+=value;
		$("#" + id).val(val);
	}
	else
	{
		$("#" + id).val(value);
		layer.close(arrLayerIndex.pop());
	}
}
function fillValue(obj,mult)
{
	var par=$(obj).parent();
	var input=par.find("input,textarea");
	if(input.length==0) return;
	input=input[0];
	var url=document.location.href;
	url=url.removequerystring("id");
	url=url.addquerystring("act","add");
	//url=url.addquerystring("mult",mult);
	url=url.addquerystring("obj",input.name);
	url+="&t=" + now();
	$.ajax({
		type: "GET",
		async: false,
		url: url,
		dataType: "json",
		success: function(data)
		{
			//alert(JSON.stringify(data));
			var html='<ul style="padding:0;margin:0;">';
			$.each(data, function()
			{
				var val=this["value"].encode().replace(/\r/g,"").replace(/\n/g,"\\u000a");
				html+='<li style="padding:8px;border:1px dashed #ccc;margin-bottom:10px;line-height:23px;color:#444;border-radius: 4px;cursor:pointer;" onclick="setfillValue(\'' + input.id + '\',\''+ val +  '\','+ mult +');">' + this["text"] + '</li>'; 
			});
			html+='</ul>';			
			
			layer.open({
			type: 1 //Page层类型
			,title: "内容选择"
			,skin: 'layui-layer-prompt'
			,moveOut:true
			,shadeClose: true
			,btn:[]	
			,area:IsMobile() ? ['95%','80%'] : ["600px" , "450px"]
			,content: html			
			,yes: function(index, layero){
				//layer.close(index);
			}
			,cancel: function(index, layero)
			{
				arrLayerIndex.pop();
			}
			,success: function(layero, index)
			{
				arrLayerIndex.push(index);
			}
			,end : function(index){arrLayerIndex.pop();}
			});
			
			
		}
	});
}
function Resize_eControl(area)
{
	if(!IsMobile()){ return;}
	area=area||document;	
	$(area).find(".eform .filterSelect").each(function (index, val) {
            var td = getParent(this, "td");	
			if(!$(td).is(':visible')){return true;}			
            var ele = $(this);
			ele.css("width",  ($(td).width() - 2) + "px");
	});
	$(area).find(".eform .text").each(function (index, val) {
            var td = getParent(this, "td");
			//if($(td).width()<10){alert($(td).is(':visible')); return true;}
			if(!$(td).is(':visible')){return true;}			
            var ele = $(this);
			if(ele.parent().attr("etype")=="rndcode")
			{
				ele.css("width", "100px");
				return true;
			}
			if(ele.parent().attr("etype")=="password")
			{
				ele.css("width", ($(td).width() - 80) + "px");
				return true;
			}
			if(ele.parent().attr("etype")=="fileselect" || ele.parent().attr("etype")=="pathselect")	
			{
				ele.css("width", ($(td).width() - 106) + "px");
				return true;
			}
			if(ele.parent().attr("etype")=="text" && ele.parent().find("a:contains('选择')").length > 0)	
			{
				ele.css("width", ($(td).width() - 60) + "px");
				return true;
			}
			if(ele.parent().attr("etype")=="datatextbutton")	
			{
				ele.css("width", ($(td).width() - 60) + "px");
				return true;
			}
			if(ele.parent().parent().attr("etype")=="selinput")	
			{
				ele.css("width",  ($(td).width() - 25) + "px");
				return true;
			}
			if(ele.parent().attr("etype")=="searchselect")	
			{
				ele.css("width", "40px");
				return true;
			}
			if(ele.parent().attr("etype")=="dateregion"){
				ele.css("width", "100px");
				return true;
			}
			if(ele.parent().attr("etype")=="date"){
				ele.css("width", $(td).width() + "px");
				return true;
			}
            if (this.getAttribute("eautowidth") == null)
            {
                ele.css("width", $(td).width() + "px");
            }
     });
	$(area).find(".eform i:not([class])").hide();
	$(area).find(".eform select").each(function (index, val) {
            var td = getParent(this, "td");
			if(!$(td).is(':visible')){return true;}
            var ele = $(this);
			if(ele.parent().attr("etype")=="searchselect")	
			{
				ele.css("width", ($(td).width() -70 ) + "px");
				return true;
			}           
            ele.css("width", ($(td).width()) + "px");
    });
	$(area).find(".eform textarea").each(function (index, val) {
            var td = getParent(this, "td");
			if(!$(td).is(':visible')){return true;}
            var ele = $(this);
			//移动端编辑器要去掉
			if(ele.parent().attr("etype")=="textarea")
			{
				if(ele.parent().find("a:contains('选择')").length > 0)
				{
					ele.css("width", ($(td).width() - 60) + "px");
				}
				else
				{
					ele.css("min-width", ($(td).width() - 16) + "px");
					ele.css("width", $(td).width() + "px");
				}
			}
			else
			{
			}            
        });
   $(area).find(".eform iframe").each(function (index, val) {
            var td = getParent(this, "td");
			if(!$(td).is(':visible')){return true;}
            var ele = $(this);
            ele.attr("width", ($(td).width()) + "px");
        });
}
var signid = null;
var signtokenid = null;
var signTime = null;
var signidx=null;
var signlink=null;
function openSignDlg(obj,area)
{
	signlink=obj;
	var url = virtualPath + "Plugins/signMobile.aspx?signtokenid="+ signtokenid +"&signid="+ signid +"&mode=mobile"+"&area=" + area;
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title: '签名',
		moveOut:false,
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
		area:['60%','60%'],
        content: [url,'no'], 
        success: function (layero, index) { arrLayerIndex.push(index); setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);},
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
};
function removeSignTemp()
{
	var url = virtualPath + "Plugins/signMobile.aspx?signtokenid="+ signtokenid +"&signid="+ signid +"&act=removesigntemp&t=" + now();
	$.ajax({
        type: 'get',
        url: url,
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
        }
    });	
};
function checkSign()
{
	clearTimeout(signTime);
	var url = virtualPath + "Plugins/signMobile.aspx?signtokenid="+ signtokenid +"&signid="+ signid +"&act=getsignstate&t=" + now();
	$.ajax({
        type: 'get',
        url: url,
		async: false,
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
			if(data.state=="1" && signidx)
			{
				layer.close(signidx);
			}			
			if(data.base64.length>10)
			{				
				var img = new Image;
				img.onload = function(){
					var canvas = document.getElementById("esign");
					var tow=0,toh=0;
					if (img.width / canvas.clientWidth < img.height / canvas.clientHeight)
					{
						toh = canvas.clientHeight;
						tow = parseInt(img.width * toh / img.height);
					}
					else
					{
						tow = canvas.clientWidth;
						toh = parseInt(img.height * tow / img.width);
					}
					canvas.getContext("2d").clearRect(0, 0,  canvas.clientWidth,  canvas.clientHeight);
      				canvas.getContext("2d").drawImage(img,0,0,tow,toh);
					$(canvas).attr("wCount", 300);
    			};
				img.src = "data:image/png;base64," + data.base64;
				removeSignTemp();
			}
			else
			{
				signTime = window.setInterval(checkSign,2000);
			}
        },
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			signTime = window.setInterval(checkSign,2000);
		}
    });	
	
};
function getDefaultSign(area)
{
	var url = virtualPath + "Plugins/signMobile.aspx?area="+ area +"&act=getdefaultsign";
	$.ajax({
        type: 'get',
        url: url,
		async: false,
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
			//layer.msg(JSON.stringify(data));
			//signid=data.signid;
			//signtokenid=data.signtokenid;
			//baseurl=data.baseurl;
			if(data.base64.length>10)
			{
				var img = new Image;
				img.onload = function(){
					var canvas = document.getElementById("esign");
					var tow=0,toh=0;
					if (img.width / canvas.clientWidth < img.height / canvas.clientHeight)
					{
						toh = canvas.clientHeight;
						tow = parseInt(img.width * toh / img.height);
					}
					else
					{
						tow = canvas.clientWidth;
						toh = parseInt(img.height * tow / img.width);
					}
					canvas.getContext("2d").clearRect(0, 0,  canvas.clientWidth,  canvas.clientHeight);
      				canvas.getContext("2d").drawImage(img,0,0,tow,toh);
					$(canvas).attr("wCount", 300);
    			};
				img.src = "data:image/png;base64," + data.base64;
			}
        }
    });	
};
function getSignToken(area)
{	
	var url = virtualPath + "Plugins/signMobile.aspx?area="+ area +"&act=getsigntoken";
	var baseurl="";
	$.ajax({
        type: 'get',
        url: url,
		async: false,
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
			//layer.msg(JSON.stringify(data));
			signid=data.signid;
			signtokenid=data.signtokenid;
			baseurl=data.baseurl;
        }
    });	
	if(signid.length==0)return;
	var url = virtualPath + "Plugins/URLCode.aspx?scale=3&url="+ encodeURIComponent(baseurl + "Plugins/signMobile.aspx?signid=" + signid + "&signtokenid=" + signtokenid);
	//alert(url);
	//alert(baseurl + "Plugins/signMobile.aspx?signid=" + signid + "&signtokenid=" + signtokenid);
	//return;
	var html='<div style="padding-top:25px;text-align:center;"><img src="' + url + '"></div>';
	signidx=layer.open({
		type: 1,
    	closeBtn:'2',//设置为第二种样式
    	skin:'demo-class',  
		scrollbar:false,

		shadeClose: true,
		area:['240px','240px'],
    	//title:['扫码签名','15px'],
		//title:false,
		title:'扫码签名',
		// shade: true,
		btn:[],
    	content: html,
		success: function(layero, index){
			signTime = window.setInterval(checkSign,2000);
		},
		end: function(){
			signidx=null;
		}
	});
};
function obtainZoom()
 {
    var ratio = 0,
        screen = window.screen,
        ua = navigator.userAgent.toLowerCase();
    if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
    } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
        }
    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
    }
    if (ratio) {
        ratio = Math.round(ratio * 100);
    }
    return ratio;
}
function resizing(){
	
    var m = obtainZoom();
	var v=100/Number(m);
	//document.title=m + "::" + v;
	
	//alert(
    //document.body.style.zoom = 100/Number(m);
	//document.zoom = 100/Number(m);
	return;
    if(Number(m) == 125){
        var bodySize = Number(m)+5+"%";
        //$("body").css("background-size",bodySize+""+bodySize);
    }else{
        var bodySize=Number(m)+"%";
        //$("body").css("background-size",bodySize+""+bodySize);
    }
}
//resizing();
if(window.addEventListener){window.addEventListener("load",function(){resizing();}, false);}else{window.attachEvent("onload",function(){resizing();});}
function readMappingModel(modelid,frmid,idname)
{
	var id=$("#"+frmid).val()||"";
	if(id.length==0)
	{
		layer.msg("请选择数据!");
		return;
	}
	idname= idname || "id";
	var url=document.location.href;
	url=url.removequerystring("id");
	url=url.addquerystring("modelid",modelid);
	url=url.addquerystring("act","mappingview");
	url=url.addquerystring("ajax","true");
	url=url.addquerystring(idname,id);
	url+="&t=" + now();
	var box=$("#mapmodelbody_" + modelid.replace(/-/g,"_"));
	if(box)
	{
		$.ajax({
			type: 'get',
			url: url,	
			dataType: "html",
			success: function(html)
			{
				var reg = /<body[^>]*>([\s\S]+?)<\/body>/i;
				var m = reg.exec(html);
				if(m)
				{
					box.html(m[1]);
				}
				
			}
		});
	}
};
function viewMappingModel(title,modelid,frmid,idname,width,height,value)
{
	var id=value||$("#"+frmid).val()||"";
	if(id.length==0)
	{
		layer.msg("请选择数据!");
		return;
	}
	idname= idname || "id";
	var url=document.location.href;
	url=url.removequerystring("id");
	url=url.addquerystring("modelid",modelid);
	url=url.addquerystring("act","mappingview");
	url=url.addquerystring("ajax","true");
	url=url.addquerystring(idname,id);
	url+="&t=" + now();
	parent.layer.open({
      type: 2,
      title: title,
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
      area :[width,height],
	  // content: [url,'no'], 
	  content: url,
	  success: function(layero, index){parent.arrLayerIndex.push(index);},
	  cancel: function(index, layero){parent.arrLayerIndex.pop();},
	  end : function(index){parent.arrLayerIndex.pop();}
    });	
};
function initCharts(id,type,option,data)
{
	var box=$('#' + id + '_box');	
	var width=box.width();
	var height=box.height();
	var radius=parseInt(box.width()/data.length/2*0.85);//根据宽度计算	
	if(radius > parseInt(height*0.7/2)){radius=parseInt(height*0.7/2);}//根据高度计算
	//alert(parseInt(radius/30 * 5));
	
	var space= parseInt((width-radius * 2 * data.length) /  (data.length+1));
	if(type=="gauge" || type=="roundprogress")
	{
		for(var i=0;i<data.length;i++)
		{
			var item=option.series[0];
			if(i>0)
			{
				item=clone(option.series[0]);
				option.series.push(item);
			}
			item.radius=radius+'px';
			item.center[0]= (space + radius + (i*radius*2) + (i*space)) + 'px';
			item.data[0].name=data[i][0];
			item.data[0].value=data[i][1];
			if(type=="gauge"){continue;}
			var size=parseInt(radius/30 * 5);
			if(size>20){size=20;}			
			item.axisLine.lineStyle.width=size;
			item.progress.width=size;
			
			
			size=parseInt(radius/30 * 8);
			if(size>24){size=24;}
			if(size<12){size=12;}
			item.title.fontSize=size;
			
			size=parseInt(radius/30 * 11);
			if(size>28){size=28;}
			if(size<12){size=12;}			
			item.detail.fontSize=size;
		}
	}
	if(type=="radar")
	{
		if(data[0].length)//一维
		{
			var value=[];
			for(var i=0;i<data.length;i++)
			{
				//alert(data[i][1]);
				var obj={};
				obj["name"]=data[i][0];
				obj["max"]=parseInt(parseInt(data[i][1]) * 1.2);
				option.radar.indicator.push(obj);
				option.legend.data.push(data[i][0]);
				
				value.push(data[i][1]);
			}
			var _data={};
			_data["name"]='';
			_data["value"]=value;
			option.series[0].data.push(_data);
			//console.log(option);
		}
		else//多维
		{
			for(p in data[0])
			{
				if(p=="name"||p=="text"){continue;}
				var obj={};
				obj["name"]=p;
				obj["max"]=0;
				option.radar.indicator.push(obj);
			}
			
			for(var i=0;i<data.length;i++)
			{
				//if(i>0){continue;}
				var value=[];
				var _data={};
				for(p in data[i])
				{
					if(p=="name"||p=="text")
					{
						option.legend.data.push(data[i][p]);
						_data["name"]=data[i][p];
					}
					else
					{						
						value.push(data[i][p]);	
						for(var j=0;j<option.radar.indicator.length;j++)
						{
							if(option.radar.indicator[j]["name"]==p)
							{
								if(option.radar.indicator[j]["max"]<data[i][p]*1.2)
								{
									option.radar.indicator[j]["max"]=parseInt(data[i][p]*1.2);
									//alert(option.radar.indicator[j]["max"]);
								}
								continue;
							}
						}
					}
				}
				_data["value"]=value;
				option.series[0].data.push(_data);
			}
			
			
			//console.log(option);
		}
	}
};
var lastpictureobjid=null;
function openPictureEditor(obj,lastobjid)
{	
	//lastpictureobj=$(obj).siblings("img");
	lastpictureobjid=lastobjid;
	var url = virtualPath + "Plugins/pictureeditor/index.html";
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title: '在线编辑图片',
		moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
		area:['90%','98%'],
        content: [url,'no'], 
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
}
var quickviewIndex = null;
function _parent()
{
    try
    {
        if (parent.layer) {
            return parent;
        }       
    }
    catch (e) {
    }
    return self;
};
function _top() {
    try {
        if (top.layer) {
            return top;
        }
    }
    catch (e) {
    }
    return self;
};
function QuickShoweTab(obj)
{
	var edataid=$("#quickviewbody").attr("edataid");
	var json=$(".eDataTable tr[eRowID='" + edataid + "']").attr("viewdata");
	var json=decode64(json);
	//alert(edataid);
	var data=JSON.parse(json);
	var url=$(obj).attr("_dataurl");
	if(url.indexOf("quick")==-1) url=url.addquerystring("act","quickview");	
	url=url.addquerystring("ajax","true");
	
	//var regex = /{data:(.*?)}/gi;
	//var arr1 = url.match(regex);
	//alert(arr1);
	//alert(url);
	var reg= new RegExp("{data:(.*?)}","gi");
	//alert(url.match(reg));
	//var arr;
	/*
 	while ((arr = reg.exec(url)) != null) //会少项  new RegExp不能带全局
	{		
		var name=arr[1].toLowerCase();
		if(typeof(data[name]) != 'undefined')
		{
			url=url.replace(arr[0],data[name]);			
			//alert(arr[0] + "::" + data[name]);
		}
 	}
	*/
	if(url.match(reg))
	{
		var arr = url.match(reg);
		for(var i=0;i<arr.length;i++)
		{
			var name=arr[i].toLowerCase().split(":")[1].replace("}","");
			if(typeof(data[name]) != 'undefined')
			{
				url=url.replace(arr[i],data[name]);
			}
		}
	}
	var index=$(obj).index();
	var dd=$(obj).parent().parent().children().eq(1);
	var div=dd.children().eq(index);
	//div.html("123");
	var lastid=$(obj).attr("edataid");
	if(lastid!=edataid)
	{
	$(obj).attr("edataid", edataid);
	$.ajax({type: "GET",async: false,url:url,dataType: "html",success: function(html)
		{
			var backstr=html;
			var reg = /<body[^>]*>([\s\S]+?)<\/body>/i;
			var m = reg.exec(html);
			if(m)
			{
			    backstr=m[1];   
			}
			div.html(backstr);
			
		}
	
		});	
	}
	//alert($(obj).index() +":" +url);
	
	showeTab(obj);
};
function QuickView(obj,type,quickviewmodelid,shade,width,height,url,json)
{  
	//var json=decode64(json);
	//alert(json);
	//var data=JSON.parse(json);

	
    if (window.shift || window.ctrl)
    {
        return;
    }
	
    var chk = $(obj).find("input[name='selitem']");
    if (chk.length > 0) {
        if (!chk[0].checked) {
            return;
        }
    }
	
	var _width=typeof(width)=="undefined" ? "80%" : width;
	var _height=typeof(height)=="undefined" ? "80%" : height;	
	var src = getEventObject();
	if (typeof(src) != "undefined" && (src.tagName == "A" || src.tagName == "IMG" || (src.tagName == "SPAN" && src.className=="more") || (src.tagName == "INPUT" && src.name=="selitem")))
	{	   
		return;
	}
	

	if(typeof(event.cancelBubble) != "undefined"){event.cancelBubble=true;if(typeof(event.returnValue) != "undefined"){event.returnValue=false;}}
	else { event.stopPropagation(); event.preventDefault(); }

	//if ($(obj).parents("tbody:first").find("tr[class='select']").length > 1) { return; }
	
	var rowid=$(obj).attr("erowid");
	
	if(window.quickviewID==rowid)
	{
		//return;
	}
	window.quickviewID=rowid;
	if(url.length==0)
	{
		url=document.location.href;
		url=url.addquerystring("id",rowid);
		if(quickviewmodelid.length>0){url=url.addquerystring("quickviewmodelid",quickviewmodelid);}
	}
	if(url.indexOf("=quick")==-1) url=url.addquerystring("act","quickview");	
	url=url.addquerystring("ajax","true");

	if(type==6)
	{
	
		if($("#quickviewbody").find("dd.qv").length>0)
		{
			$("#quickviewbody").attr("edataid", rowid);
			var cur= $("#quickviewbody").find("dd.qv").prev().find(".cur").get(0);
			QuickShoweTab(cur);
			//alert(dt.length);
			return;
		}
		var lastcur=$("#quickviewbody .eTab dt a.cur").index();
		$.ajax({type: "GET",async: true,url:url,dataType: "html",success: function(html)
		{
			var backstr=html;
			var reg = /<body[^>]*>([\s\S]+?)<\/body>/i;
			var m = reg.exec(html);
			if(m)
			{
			    backstr=m[1];   
			}
			if($("#quickviewbody").find("dd.qv").length==0)
			{
				$("#quickviewbody").html(backstr);
			}
			else
			{
				$("#quickviewbody dd.qv div:eq(0)").html(backstr);
			}
			$("#quickviewbody").attr("edataid", rowid);
			if(lastcur>0)
			{
				var lastobj=$("#quickviewbody .eTab dt a:eq("+ lastcur +")").get(0);
				showeTab(lastobj);
			}
		},
	    error: function (XMLHttpRequest, textStatus, errorThrown) 
		{
	       
	    }
		});	
		return;
	}

		
	var _offset= type.toString().replace("1","t").replace("3","r").replace("4","b").replace("2","l").replace("5","auto");//_area[宽,高];
	var _area=[_offset.replace("t","100%").replace("r","25%").replace("b","100%").replace("l","25%") ,_offset.replace("t","33%").replace("r","100%").replace("b","33%").replace("l","100%")];	
	if(_offset=="auto")
	{
		_area=[_width,_height];
	}
    // var parentDOM = top || window;

	if(quickviewIndex)
	{
		layer.iframeSrc(quickviewIndex, url);
		return;
	}
	layer.open({
      type: 2,
      title: "快速查看",
	 // title:['信息提示框','120px'],
	  scrollbar:false,//禁止浏览器出现滚动条
      maxmin: true,
	  resize: true,
	  id:'quickviewDlg',//设定一个id，防止重复弹出
	  shade:(shade == 0 ? 0 : 0.4),
      shadeClose: true, //点击遮罩关闭层
	  //area:IsMobile() ? ['95%','95%'] : ["380px" , "450px"],
	  area:_area,
	  offset: _offset,
	  //area:["100%" , "200px"],   offset: _offset,
	  //area:["100%" , "200px"],   offset: _offset,
	  //area:["380px" , "100%"],   offset: _offset,

	  // content: [url,'no'], 
	  
	  //move: false, //拖拽模式，0或者1


	  content: url,
	  yes: function(index, layero){
	
	  },
	  cancel: function(index, layero){
		  //关闭
		  arrLayerIndex.pop();
	  },
	  success: function (layero, index)
	  {
	      arrLayerIndex.push(index);
	      quickviewIndex = index;
	      setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
	  },
	  end : function(index){quickviewIndex=null;window.quickviewID=null;arrLayerIndex.pop();}
    });	
};
function unPivotConfig()
{
    var url = document.location.href;
    url = url.removequerystring("mode");
    document.location.assign(url);
};
function PivotConfig(area)
{	
	var url= "../Plugins/PivotConfig.aspx?";
	if(typeof(AppItem)=="string" && AppItem.length > 0){url+="AppItem=" + AppItem;}
	if(typeof(ModelID)=="string" && ModelID.length > 0){url+="ModelID=" + ModelID;}	
	var sessionid=document.location.href.getquerystring("sessionid");
	if(sessionid.length>0){url+="&sessionid="+sessionid;}
	if(area){url+="&area=" + area;}
	var arr=document.location.href.getquerys();
	for(var i=0;i<arr.length;i++)
	{
		//url=url.addquerystring(arr[i].name,arr[i].value);	
	}
	//url=url.addquerystring("act","pivot");	
	//url+="&t=" + now();
    layer.open({
      type: 2,
      title: "数据透视",
	 // title:['信息提示框','120px'],
      //maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['95%','95%'] : ["530px" , "450px"],   
	  // content: [url,'no'], 
	  btn: ['确定', '取消'],
	  content: url,
	  yes: function (index, layero) {
	      var doc = layero.find('iframe')[0].contentWindow.document;
		  //alert($(doc).find("tbody select[name='parentid'] option:selected"));		  
		  if($(doc).find("tbody select[name='parentid'] option:selected[value='']").length>0)
		  {
			  layer.msg("请选择自定义的列!");
	          return;
		  }
	      if ($(doc).find("tbody input[name='groups']:checked").length < 1) {
	          layer.msg("请选择分组字段!");
	          return;
	      }
		  layero.find('iframe')[0].contentWindow.saveConfigs(index);
		  //arrLayerIndex.pop();
		  //layer.close(index);
		  //setTimeout(function(){
		  	//document.location.assign(document.location.href.addquerystring("act","pivot")); 
		  //},1000);
	  },
	  btn2: function(index, layero)
	  {
		  arrLayerIndex.pop();
		  var url=document.location.href;
		  if(url.indexOf("pivot")>-1)
		  {
			  url=url.removequerystring("mode");
			  document.location.assign(url);
		  }
	  },
	  cancel: function(index, layero){
		  //关闭
		  arrLayerIndex.pop();
	  },
	  success: function(layero, index){arrLayerIndex.push(index);},	  
	  end : function(index){arrLayerIndex.pop();}
    });	
	
}
function execMethod(obj)
{
	var url = virtualPath + "Plugins/Reflection.aspx";
	var data={};
	$.ajax({
		type: "post",
		async: false,
		data:obj,
        url:url,
        dataType: "json",
        success: function (_data)
		{
			data=_data;
        }
    });
	return data;
}
function saveStream(stream)
{
	//alert(typeof(stream));
	var url = virtualPath + "Plugins/ProUpload.aspx?type=image";
	//if($(obj).parent().attr("MaxWidth").length>1) {url+="&PictureMaxWidth=" + $(obj).parent().attr("MaxWidth");}
	var formData = new FormData();
	formData.append('files', stream, "aaa.png");
	$.ajax({
		type: "post", 
		async: false,
		data:formData,
        url:url,
        dataType: "json",
		contentType: false,
		cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        success: function (data)
		{
			//alert(JSON.stringify(data));
			if(data.errcode=="0")
			{
				var box=$("#" + lastpictureobjid + "_box");				
				if(data.files.length>0)
				{
					$("#" + lastpictureobjid).val(data.files[0].url);
					box.find("img").attr("src",data.files[0].url);
					if(box.find("iframe").length>0)
					{
						var _url=box.find("iframe").attr("src");
						_url=_url.addquerystring("act","finsh");
						_url=_url.addquerystring("file",data.files[0].url);
						box.find("iframe").attr("src",_url);

					}
					//lastpictureobj.siblings("input").val(data.files[0].url);
					//lastpictureobj.attr("src",data.files[0].url);
					//$("#" + $(obj).attr("id").replace("_file","")).val(data.files[0].url);
					
				}
				lastpictureobjid=null;
				layer.close(arrLayerIndex.pop());
			}
			else
			{
				layer.msg(data.message);
			}
			//
			//
			/*
			layer.msg(data.message);
			obj.value="";
			var callback=$(obj).attr("callback");
			if(callback)
			{
				//eval("if(typeof(" + callback + ")=='function'){" + callback + "(" + data.files +  ");}");
				if(data.files)
				{
					eval(callback + "(data.files);");
				}
				else
				{
					eval(callback + "(data);");
				}
			}
			*/
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {}
    });
}
function getWeChatShareData(area)
{
	var url = virtualPath + "Plugins/Tencent/WeChat/getShareData.aspx";
	if(area){url+="?area=" + area;}
	var data=[];
	$.ajax({
		type: "get",
		async: false,
		url: url,
		dataType: "json",
		success: function(_data)
		{
			data=_data.data;
		}
	});
	return data;
}
function WeChatScanQRCode(obj,callback)
{
	if(!window.wx){return;}
	var data=getWeChatShareData();
	if(data.length==0){return;}
	var acc=data[0];
	wx.config({
		debug: false,
		beta: true,
		appId: acc.appid,
		timestamp: parseInt(acc.timestamp),
		nonceStr: acc.noncestr,
		signature: acc.signature,
		jsApiList: ['checkJsApi','scanQRCode'],
		complete:function(ret)
		{
            //alert("wx.config.complete:" + JSON.stringify(ret))
        }
    });
	 wx.error(function (res) {
    	//alert("出错了：" + res.errMsg);//这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
		//alert(JSON.stringify(res));
	 });
	
	wx.ready(function () 
    {
		/*
		wx.checkJsApi({
		  jsApiList: ['scanQRCode'],
		  success: function (res) {
			alert(JSON.stringify(res));
		  }
		});
		*/		
		wx.scanQRCode({needResult:1,scanType: ["qrCode","barCode"],
                success:function(res){
                   // alert(res.resultStr);//alert(JSON.stringify(res));
				   	var arr=res.resultStr.split(",");
					var code=arr.length==1?arr[0]:arr[1]; 
					if(obj){$("#"+obj).val(code);}
					if(typeof(callback)=="function"){callback(code);}
                },
				error:function(res){
					//alert(JSON.stringify(res));
			  	}
        });
		//wx.scanQRCode({needResult:1,desc:"scanQRCode desc",success:function(e){alert(JSON.stringify(e))}});//自己处理
	});
}
function getWxWorkShareData(area)
{
	var url = virtualPath + "Plugins/Tencent/WxWork/getShareData.aspx";
	if(area){url+="?area=" + area;}
	var data=[];
	$.ajax({
		type: "get",
		async: false,
		url: url,
		dataType: "json",
		success: function(_data)
		{
			data=_data.data;
		}
	});
	return data;
}
function WxWorkScanQRCode(obj,callback)
{
	if(!window.wx){return;}
	var data=getWxWorkShareData();
	if(data.length==0){return;}
	var acc=data[0];
	wx.config({
		debug: false,
		beta: true,
		appId: acc.appid,
		timestamp: parseInt(acc.timestamp),
		nonceStr: acc.noncestr,
		signature: acc.signature,
		jsApiList: ['checkJsApi','scanQRCode'],
		complete:function(ret)
		{
            //alert("wx.config.complete:" + JSON.stringify(ret))
        }
    });
	 wx.error(function (res) {
    	//alert("出错了：" + res.errMsg);//这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
		//alert(JSON.stringify(res));
	 });
	
	wx.ready(function () 
    {
		/*
		wx.checkJsApi({
		  jsApiList: ['scanQRCode'],
		  success: function (res) {
			alert(JSON.stringify(res));
		  }
		});
		*/		
		wx.scanQRCode({needResult:1,desc:"scanQRCode desc",
                success:function(res){
                   // alert(res.resultStr);//alert(JSON.stringify(res));
				   	var arr=res.resultStr.split(",");
					var code=arr.length==1?arr[0]:arr[1]; 
					if(obj){$("#"+obj).val(code);}
					if(typeof(callback)=="function"){callback(code);}
                },
				error:function(res){
					//alert(JSON.stringify(res));
			  	}
        });
		//wx.scanQRCode({needResult:1,desc:"scanQRCode desc",success:function(e){alert(JSON.stringify(e))}});//自己处理
	});
}
//调用企业微信扫一扫
function openWxWorkScanQRCode(obj,callback) //未启用
{
	if(!IsMobile())return;
	var url = virtualPath + "Plugins/Tencent/WxWork/scanQRCode.aspx?act=get";
	if(obj){url+="&obj="+ obj;}	
	if(callback){url+="&callback="+ callback;}
	//url+="&fromurl="+  encodeURIComponent(document.location.href.split("?")[0]);
	url+="&fromurl="+  encodeURIComponent(document.location.href);
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title: '扫一扫',
		moveOut:true,
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
		area:['180px','100px'],
        content: [url,'no'], 
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
}
function scanQRCode_callback(result)//未启用
{	
	layer.close(arrLayerIndex.pop());
}
function saveCounterSign(UserArea,itemid,pid)
{
	var url = virtualPath + "Plugins/counterSign.aspx?";
	if(typeof(AppItem)=="string" && AppItem.length > 0){url+="AppItem=" + AppItem + "&";}
	if(typeof(ModelID)=="string" && ModelID.length > 0){url+="ModelID=" + ModelID + "&";}
	url+="UserArea=" + UserArea;
	url+="&itemid=" + itemid;
	url+="&pid=" + pid;
	url+="&id=" + document.location.href.getquerystring("id");	
	var data = eSignIn.getdata();
	$.ajax({
        type: 'POST',
		async: false,
        url: url,
		//data: '{ "imageData" : "' + data + '" }',
		data: {"imageData" :  data  },
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
			parent.layer.msg(data.message);
			if(data.errcode=="0")
			{			
				var html='';				
				$.each(data.data, function()
				{
					html+='<img src="'+ this["url"] +'" style="max-width:100px;max-height:30px;border:0;">'; 
				});
				$("#"+pid+"_box",parent.document).html(html);
				parent.layer.close(parent.arrLayerIndex.pop());
			}
        }
    });
}
function counterSign(UserArea,itemid,pid)
{
	var url = virtualPath + "Plugins/counterSign.aspx?";
	if(typeof(AppItem)=="string" && AppItem.length > 0){url+="AppItem=" + AppItem + "&";}
	if(typeof(ModelID)=="string" && ModelID.length > 0){url+="ModelID=" + ModelID + "&";}	
	url+="UserArea=" + UserArea;
	url+="&itemid=" + itemid;
	url+="&pid=" + pid;
	url+="&id=" + document.location.href.getquerystring("id");
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title: '签名',
		moveOut:true,
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
		area:IsMobile() ? ['100%','280px'] : ["390px" , "280px"],
        content: [url,'no'], 
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
}
function saveSignIn()
{
	var url = virtualPath + "Plugins/SignIn.aspx?";
	if(typeof(AppItem)=="string" && AppItem.length > 0){url+="AppItem=" + AppItem + "&";}
	if(typeof(ModelID)=="string" && ModelID.length > 0){url+="ModelID=" + ModelID + "&";}
	url+="id=" + document.location.href.getquerystring("id");	
	var data = eSignIn.getdata();
 	$.ajax({
        type: 'POST',
		async: false,
        url: url,
		//data: '{ "imageData" : "' + data + '" }',
		data: {"imageData" :  data  },
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
			layer.msg(data.message);
			if(data.errcode=="0")
			{
				var dd=$("#esignin").parent();
				dd.html('<img src="../' + data.signfile +  '">');
			}
        }
    });
}
function delFromLink(obj,id)
{
	 //layer.msg('请输入金额', {icon: 2});
	var evt = event || window.event;
    if (evt.stopPropagation) { evt.stopPropagation(); } else { evt.cancelBubble = true; }
    if (evt.preventDefault) { evt.preventDefault(); } else { evt.cancelBubble = true; }
	
	var input=$("#" + id);
	var index=$(obj).parent().index();	
	layer.confirm('', {btn: ['确定', '取消'], title: "确认要删除吗?",shadeClose: true}, function (idx, layero) {
		var model=input.val().toJson();
		//model.Convert=true;
		model.remove(index);
		input.val(model.toJson());
		$(obj).parent().remove();
		layer.close(idx);
    });	
	//_model.remove(index);	
	//var data=model.get(index);	
	//input.value=model.toJson();	
}
function editFromLink(obj,id)
{
	var index=$(obj).index();
	var input=$("#" + id);	
	var model=input.val().toJson();
	//model.Convert=true;	
	var data=model.get(index);
	
	//alert(data.toJson() + "::" + data.name);
	
	
	//document.title=index;
	//layer.msg(index);
	
	layer.open({
    type: 1 //Page层类型
	,title: "修改连接"
	,skin: 'layui-layer-prompt'
	,moveOut:true
	,shadeClose: true
    ,btn:["确定","取消"]	
    ,area : ["400px" , "260px"]  
    ,content: '<div>地址：<input id="url" type="text" class="layui-layer-input" value="' + data.url + '" onblur="flinkblur(this);" placeholder="连接地址">名称：<input style="margin-top:10px;" id="name" type="text" class="layui-layer-input" value="' +  data.name + '" placeholder="连接名称"></div>'
    ,yes: function(index, layero){
		data["url"]=$(layero).find("#url").val();
		data["name"]= $(layero).find("#name").val();
		input.val(model.toJson());
		$(obj).html($(layero).find("#name").val() + '<a href="javascript:;" class="del" onclick="delFromLink(this,\'' + id + '\');">&nbsp;</a>');
		layer.close(index);
	}
	});
		
}

function getHtmlTitle(url)
{
	var title="";
	$.ajax({
			type: 'post',
			async: false,
			url:  virtualPath + 'Plugins/getTitle.ashx',	
			data:{url:url},
			dataType: "json",
			success: function(data)
			{
				if(data.errcode=="0")
				{
					//alert(JSON.stringify(data));
					title=data.title;
				}
			}
	});	
	
	return title;
}
function flinkblur(obj)
{
	var txt=$(obj).parent().find("input:eq(1)");
	if(txt.val().length>0){return;}

	var url=$(obj).val();
	if(url.toLowerCase().indexOf("http")==0)
	{
		var title=getHtmlTitle(url);
		txt.val(title);
	}
	//alert(url.toLowerCase().indexOf("http"));
}
function addFromLink(obj,id)
{
	//var url="http://www.eketeam.com/";
	//var title=getHtmlTitle(url);
	//alert(title);
	//return;
	var input=$("#" + id);
	var ol=$(obj).parent().find("ol");
	layer.open({
    type: 1 //Page层类型
	,title: "添加连接"
	,skin: 'layui-layer-prompt'
	,moveOut:true
	,shadeClose: true
    ,btn:["确定","取消"]	
   	,area : ["400px" , "260px"]  
    ,content: '<div>地址：<input id="url" type="text" class="layui-layer-input" value="" onblur="flinkblur(this);" placeholder="连接地址">名称：<input style="margin-top:10px;" id="name" type="text" class="layui-layer-input" value="" placeholder="连接名称"></div>'
    ,yes: function(index, layero){
		//为空判断
		var model=input.val().toJson();
		//model.Convert=true;	
		var data=new Object();
		data["url"]=$(layero).find("#url").val();
		data["name"]= $(layero).find("#name").val();
	
		ol.append('<li onclick="editFromLink(this,\'' + id + '\');">' + $(layero).find("#name").val() + '<a href="javascript:;" class="del" onclick="delFromLink(this,\'' + id + '\');">&nbsp;</a></li>');	
		
		model.append(data);	
		input.val(model.toJson());
		layer.close(index);
	  
    }
});
	
}
//文件查看
function viewFile(path,width,height)
{
	if(path.toLowerCase().indexOf("upload/")>0){path=path.substring(path.toLowerCase().indexOf("upload/"));}
	var _width=typeof(width)=="undefined" ? "80%" : width;
	var _height=typeof(height)=="undefined" ? "80%" : height;	
	if(path.indexOf(".mp3")>-1)
	{
		_width="360px";
		_height="160px";
	}
	if(path.indexOf(".mp4")>-1)
	{
		if(IsMobile())
		{
			_width="90%";
			_height="360px";
		}
		else
		{
			_width="680px";
			_height="560px";
		}
	}
	var url = virtualPath + "Plugins/viewFile/default.aspx?path=" + path;
    layer.open({
      type: 2,
      title: "文件预览",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
      area : [_width,_height],
	  // content: [url,'no'], 
	  content: url,
	  success: function(layero, index){},
	  cancel: function(index, layero){},
	  end : function(index){}
    });	
}
//人员选择
var UserSelectParent;
function removeUserSelect(obj)
{
	layer.confirm('', {btn: ['确定', '取消'], title: "确认要清空吗?",shadeClose: true}, function (idx, layero) {
		var box=$(obj).parent().parent();
		$(obj).parent().find(".body").attr('title','');
		$(obj).parent().find(".body").html('');	
		box.find("input").val('');
		layer.close(idx);
    });	
	
};
function openUserSelectN(obj,controlid,area,multi)
{
	var vpath=obj.getAttribute("vpath");
	UserSelectParent=$(obj).parent().parent();//box
	//alert(UserSelectParent.get(0).tagName);
	var title=$(obj).parent().parent().attr("fieldname");
	var url=(vpath == null ? virtualPath : vpath) + "Plugins/UserSelectN.aspx?obj=" + controlid + "&multi=" + multi;
	if(area){url+="&area=" + area;}
	url+= "&t=" + now()
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title: title,//'人员选择',
		moveOut:true,
        maxmin: true,
		btn:["确定"],
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
		area:IsMobile() ? ['95%','80%'] : ["65%" , "85%"],    
        content: url,
        success: function (layero, index) {
			arrLayerIndex.push(index); 
			 setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
			},
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
}
function openUserSelect(obj,controlid,area)
{
	var vpath=obj.getAttribute("vpath");
	UserSelectParent=$(obj).parent().parent();
	var title=$(obj).parent().attr("fieldname");
	var url=(vpath == null ? virtualPath : vpath) + "Plugins/UserSelect.aspx?obj=" + controlid;
	if(area){url+="&area=" + area;}
	url+= "&t=" + now()
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title: title,//'人员选择',
		moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
		area:IsMobile() ? ['95%','80%'] : ["600px" , "500px"],    
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
}
function openDepartmentSelect(obj,controlid,area)
{
	var vpath=obj.getAttribute("vpath");
	UserSelectParent=$(obj).parent().parent();
	var title=$(obj).parent().attr("fieldname");
	var url=(vpath == null ? virtualPath : vpath) + "Plugins/DepartmentSelect.aspx?obj=" + controlid ;
	if(area){url+="&area=" + area;}
	url+= "&t=" + now()
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title:title,// '部门选择',
		moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
		area:IsMobile() ? ['95%','95%'] : ["600px" , "500px"],    
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
	
}

function openCompanySelect(obj,controlid,area)
{
	var vpath=obj.getAttribute("vpath");
	UserSelectParent=$(obj).parent().parent();
	var title=$(obj).parent().attr("fieldname");
	var url=(vpath == null ? virtualPath : vpath) + "Plugins/CompanySelect.aspx?obj=" + controlid ;
	if(area){url+="&area=" + area;}
	url+= "&t=" + now()
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title:title,// '部门选择',
		moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
		area:IsMobile() ? ['95%','95%'] : ["600px" , "500px"],    
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
	
}
function openOrganizationalSelect(obj,controlid,area)
{
	var vpath=obj.getAttribute("vpath");
	UserSelectParent=$(obj).parent().parent();
	var title=$(obj).parent().attr("fieldname");
	var url=(vpath == null ? virtualPath : vpath) + "Plugins/OrganizationalSelect.aspx?obj=" + controlid ;
	if(area){url+="&area=" + area;}
	url+= "&t=" + now()
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title:title,// '部门选择',
		moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
		area:IsMobile() ? ['95%','95%'] : ["600px" , "500px"],    
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
	
}
function getRndCode(picid,type)
{
	 if(type == 0 && document.getElementById(picid).src.indexOf("none.gif") == -1) {
         return;
     }
	document.getElementById(picid).src = virtualPath + "Plugins/RndPic.aspx?t=" + now();
}
//自定义导入程序
function custom_import(title,url)
{
        layer.open({
            type: 2,
            skin: 'layui-layer-rim', //加上边框
            title: title,
			moveOut:true,
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            area: ['400px', '300px'],
            content: url,
            success: function (layero, index) { arrLayerIndex.push(index); },
            cancel: function (index, layero) { arrLayerIndex.pop(); },
            end: function (index) { arrLayerIndex.pop();document.location.assign(document.location.href); }
        });
}
//显示自定义项
function check_InputValue(obj)
{
	var span=$(obj).parent();	
	
	if(span.find("input[inputvalue]").length>0)
	{
		var value=span.find("input[inputvalue]").attr("inputvalue");
		if(obj.tagName=="SELECT")
		{
			//alert($(obj).val());
			if(value==$(obj).val())
			{
				span.find("input[inputvalue]").show();
			}
			else
			{
				span.find("input[inputvalue]").hide();
			}
			return;
		}
		if(span.find("input[value='" + value + "']:checked").length==1)
		{
			span.find("input[inputvalue]").show();
		}
		else
		{
			span.find("input[inputvalue]").hide();
		}
	}
}
//列表选择
function getSelectIDS1()
{
	var sels=$("input[name='selitem']:checked");
	if(sels.length==0) return "";
	var ids="";
	for(var i=0;i<sels.length;i++)
	{
		if(i>0){ids+=",";}
		ids+=sels[i].value;
	}
	return ids;
}
function deleteMore(delmode)
{
	delmode=delmode||0;
	//alert(delmode);
    var ids = getSelectIDS("del");
    if (ids.length == 0) {
        layer.msg("请选择要删除的数据!");
        return;
    }
	var chkall = $("input[name='selallitem']")[0].checked||false;		
    var page = getobj("page");
	var mode= document.location.href.getquerystring("mode");//recycle
    if (delmode == 0 || !chkall) {
        var url = document.location.href;
        url = url.addquerystring("act", "delmore");
        url = url.addquerystring("ids", ids);
        layer.confirm('确认要删除所选数据吗?', {
            title: "删除", shadeClose: true, area: ['220', '160'], btn: ['删除', '取消'],
            btn1: function (idx, layero) {

                if (top != self)//Frame打开
                {
                    delrequest(url);
                    Search();
                    layer.close(idx);
                }
                else {
                    document.location.assign(url);
                }
            }
        });
    }
    else
    {
        
		layer.confirm('确认要删除吗?', {title: "删除",shadeClose: true, btn: ['删除已选', '删除所有', '取消']},
			function (idx, layero)
			{
				//删除已选
				layer.close(idx);
				var url=document.location.href;
				url=url.addquerystring("act","delmore");
				url=url.addquerystring("ids",ids);
				if(top!=self)//Frame打开
				{
					delrequest(url);
					Search();
				}
				else
				{
					document.location.assign(url);
				}
				
			},function(idx, layero)
			{
				//删除所有
				layer.close(idx);
				var url=document.location.href;
				url=url.addquerystring("act","delmore");
				if(top!=self)//Frame打开
				{
					delrequest(url);
					Search();
				}
				else
				{
					document.location.assign(url);
				}
			}
		);		
    }
};
function unselectAll()//取消选择所有
{
    var tbody = getSelectBody();
    var sels = tbody.find("tr[class='select']");
    var qdlg = $("#quickviewbody");
    if (sels.length > 1 || qdlg.length == 0)
    {
        
        if (qdlg.length == 1)
        {
            var edataid = qdlg.attr("edataid");
            sels.each(function (i, elem) {
                var erowid = $(elem).attr("erowid");
                if (erowid != edataid)
                {
                    $(this).attr("class", "");
                    var chk = $(this).find("input[name='selitem']");
                    if (chk.length > 0) {
                        chk.prop("checked", false);
                        chk.attr("checked", false);
                    }
                }
            });
        }
        else
        {
            sels.each(function (i, elem) {
                $(this).attr("class", "");
                var chk = $(this).find("input[name='selitem']");
                if (chk.length > 0) {
                    chk.prop("checked", false);
                    chk.attr("checked", false);
                }
            });
        }
        var chkall = $("input[name='selallitem']");
        if (chkall.length > 0) {
            chkall.prop("checked", false);
            chkall.attr("checked", false);
        }
        selectItems_check(tbody);
    }
};
function selectAll()//选择所有
{
    var tbody = getSelectBody();   
    var sels = tbody.find("tr[etype!='sum']");
    sels.each(function (i, elem) {
        $(this).attr("class", "select");
        var chk = $(this).find("input[name='selitem']");
        if (chk.length > 0) {
            chk.prop("checked", true);
            chk.attr("checked", true);
        }
    });
    var chkall = $("input[name='selallitem']");
    if (chkall.length > 0)
    {
        chkall.prop("checked", true);
        chkall.attr("checked", true);
    }
    selectItems_check(tbody);
};
function prevRecord()//上一条记录
{
    var chkall = $("input[name='selallitem']");
    if (chkall.length > 0) {
        return;
    }
    var tbody = getSelectBody();
    var sels = tbody.find("tr[class='select']");
    if (sels.length == 1)
    {
        if (sels.prev().length == 1)
        {
            sels.attr("class", "");
            sels.prev().attr("class", "select");
            //alert(typeof (sels.prev()[0].click));
            //sels.prev().trigger("click");
            sels.prev()[0].click();
        }
    }
};
function nextRecord()//下一条记录
{
    var chkall = $("input[name='selallitem']");
    if (chkall.length > 0) {
        return;
    }
    var tbody = getSelectBody();
    var sels = tbody.find("tr[class='select']");
    if (sels.length == 1)
    {
        if (sels.next().length == 1)
        {
            var etype = sels.next().attr("etype");

            if (etype != "sum") {
                sels.attr("class", "");
                sels.next().attr("class", "select");
                //sels.next().trigger("click");
                sels.next()[0].click();
            }
        }
    }
};
function getSelectIDS(act)
{
    act = act || "";
    var tbody = getSelectBody();
    var sels = tbody.find("tr[class='select']");
    var ids = "";
    sels.each(function (i, elem) {
        var len = 1;
        if (act.length > 0)
        {
            len = 0;
            if ($(this).find("a[href*='act=" + act + "']").length > 0 || $(this).find("a[_href*='act=" + act + "']").length > 0 || $(this).find("a[ehref*='act=" + act + "']").length > 0) {
                len = 1;
            }
        }
        if (len > 0)
        {
            var _id = $(this).attr("erowid");
            if (_id.length > 0) {
                if (ids.length > 0) { ids += ","; }
                ids += _id;
            }
        }
    });
    return ids;
};
//表头全选事件
function selectAllItems(obj)
{
    //$("input[name='selitem']").prop("checked", obj.checked);
    //selectMore_check();
    var table = $(obj).parents("table:first");
    var tbody = $(table).find("tbody:eq(0)");
    window.selectBody = tbody;
    if(obj.checked)
    {
        selectAll();
    }
    else
    {
        unselectAll();
    }
}
function getSelectBody()
{
	if(typeof(window.selectBody)==="undefined")
	{
		return $(".eDataTable:eq(0) tbody");
	}
	else
	{
		return window.selectBody;
	}
};
function selectItems_check(tbody)
{
	if(!tbody)
	{
		tbody=getSelectBody();
	}
	var sels = $(tbody).find("tr[class='select']");
    
	//var sels = $(tbody).find("input[name='selitem']:checked");
	//document.title = sels.length + "::" + $(tbody).find("input[name='selitem']:checked").length;
	if(sels.length==0)
	{
		$("#btn_PrintMore").hide();
		$("#btn_selMore").hide();
		$("#btn_delMore").hide();
		$("#btn_editMore").hide();
		$(".selectMore").hide();
	}
	else
	{
		//$("#btn_PrintMore").show();
		$(".selectMore").show();
		$("#btn_selMore").show();
		
		var count=0;
		sels.each(function(i,elem)
		{
			count+=$(elem).find("a[href*='act=del']").length;
			count+=$(elem).find("a[_href*='act=del']").length;
			count+=$(elem).find("a[ehref*='act=del']").length;
		});
		if(count<1)
		{
			$("#btn_delMore").hide();
		}
		else
		{
			$("#btn_delMore").show();
		}
		count=0;
		sels.each(function(i,elem)
		{
			count+=$(elem).find("a[href*='act=edit']").length;
			count+=$(elem).find("a[_href*='act=edit']").length;
			count+=$(elem).find("a[ehref*='act=edit']").length;
		});
		if(count<1)
		{
			$("#btn_editMore").hide();
		}
		else
		{
			$("#btn_editMore").show();
		}
		count=0;
		sels.each(function(i,elem)
		{
			count+=$(elem).find("a[href*='act=print']").length;
			count+=$(elem).find("a[_href*='act=print']").length;
			count+=$(elem).find("a[ehref*='act=print']").length;
		});
		if(count<1)
		{
			$("#btn_PrintMore").hide();
		}
		else
		{
			$("#btn_PrintMore").show();
		}
	}
	var chkall = $("input[name='selallitem']");
	//document.title = chkall.length;
	if (chkall.length > 0)
	{
	    var items = $("input[name='selitem']");
	    var notitems = $("input[name='selitem']:not(:checked)");
	    if (notitems.length == 0) {
	        chkall.prop("checked", true);
	        chkall.attr("checked", true);
	    }
	    else
	    {
	        chkall.prop("checked", false);
	        chkall.attr("checked", false);
	    }
        /*
	    if (notitems.length == items.length)
	    {
	        chkall.prop("checked", false);
	        chkall.attr("checked", false);
	    }
	    document.title = items.length + "::" + notitems.length;
        */
	}
	if(typeof(select_callback)=="function")
	{
		select_callback();
	}
};
function selectMore_check()
{

	//alert($("input[name='selitem']:checked").length + "::" + $(".selectMore").length );


	if($("input[name='selitem']:checked").length==0)
	{
		$("#btn_PrintMore").hide();
		$("#btn_selMore").hide();
		$("#btn_delMore").hide();
		$("#btn_editMore").hide();
		$(".selectMore").hide();
	}
	else
	{
		$("#btn_PrintMore").show();
		$(".selectMore").show();
		$("#btn_selMore").show();
		$("#btn_editMore").show();
		var count=0;
		$("input[name='selitem']:checked").each(function(i,elem)
		{			
			count+=$(elem).parents("tr:first").find("a[href*='act=del']").length;
			count+=$(elem).parents("tr:first").find("a[_href*='act=del']").length;
			count+=$(elem).parents("tr:first").find("a[ehref*='act=del']").length;
		});
		if(count==0)
		{
			$("#btn_delMore").hide();
		}
		else
		{
			$("#btn_delMore").show();		
		}
	}
	if(typeof(select_callback)=="function")
	{
		select_callback();
	}		
}
//删除-全选
function selectdelItems(obj)
{
	$("input[name='delitem']").prop("checked",obj.checked);
	deleteMore_check();
}
//是否有可删除项判断
function deleteMore_check()
{
	//alert($("input[name='delitem']:checked").length);
	if($("input[name='delitem']:checked").length==0)
	{
		$("#btn_delMore").hide();
	}
	else
	{
		var count=0;
		$("input[name='delitem']:checked").each(function(i,elem)
		{			
			count+=$(elem).parents("tr:first").find("a[href*='act=del']").length;
			count+=$(elem).parents("tr:first").find("a[_href*='act=del']").length;
			count+=$(elem).parents("tr:first").find("a[ehref*='act=del']").length;
		});
		if(count==0)
		{
			$("#btn_delMore").hide();
		}
		else
		{
			$("#btn_delMore").show();
		}
	}
}
//批量打印
function printMore()
{
    //var ids = getSelectIDS();
	 var ids = getSelectIDS("print");
    if (ids.length == 0) {
        layer.msg("请选择要打印的数据!");
        return;
    }
	//alert(ids);
	//return;
    var url = document.location.href;
    url += url.indexOf("?") > -1 ? "&" : "?";
    url += "act=print&id=" + ids;
    var table = getobj("eDataTable");
    var ajax = parseBool(table.getAttribute("ajax"));
    if (!ajax) {
        //document.location.assign(url);
        //return;
    }
    url = url.addquerystring("ajax", "true");
    var parentDOM = top || window;
    parentDOM.layer.open({
        type: 2
			  , title: "打印"
			  , moveOut: true
			  , shadeClose: true //点击遮罩关闭层
        //,area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"]
        //,offset: [rect.top + "px", rect.left + "px"]
			  , area: ["95%", "95%"]
			  , content: url
			  ,maxmin: true
			  , success: function (layero, index) {
			      parentDOM.arrLayerIndex.push(index);
			      setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
			  }
			  , cancel: function (index, layero) {
			      parentDOM.arrLayerIndex.pop();
			  }
               , end: function (index) {
                   parentDOM.arrLayerIndex.pop();
               }
    });
};
function printMore1()
{
	var sels=$("input[name='selitem']:checked");
	if(sels.length==0)
	{
		alert("请选择要打印的数据!");
		return;
	}	
	var ids="";
	for(var i=0;i<sels.length;i++)
	{
		if(i>0){ids+=",";}
		ids+=sels[i].value;
	}
	if(ids.length==0)
	{
		alert("没有符合条件的数据!");
		return;
	}
	var url=document.location.href;
	url+= url.indexOf("?") > -1 ? "&" : "?";
	url+="act=print&id=" + ids;	
	var table=getobj("eDataTable");
	var ajax = parseBool(table.getAttribute("ajax"));
	if(!ajax)
	{
		//document.location.assign(url);
		//return;
	}
	url=url.addquerystring("ajax","true");
	layer.open({
			  type: 2
			  ,title: "打印"	
			  ,moveOut:true
			  ,shadeClose: true //点击遮罩关闭层
			  //,area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"]
			  //,offset: [rect.top + "px", rect.left + "px"]
			  ,area: ["95%","95%"]
			  ,content: url
			  
			  ,success: function(layero, index)
			  {
				arrLayerIndex.push(index);
			  }
			  ,cancel: function(index, layero)
			  {
				  arrLayerIndex.pop();
			  }				
	});
}
//对比按钮事件
function contrastMore()
{
    var ids = getSelectIDS();
    if (ids.length == 0) {
        layer.msg("请选择要对比的数据!");
        return;
    }
    var url = document.location.href;
    url += url.indexOf("?") > -1 ? "&" : "?";
    url += "act=viewmore&id=" + ids;
    var table = getobj("eDataTable");
    var ajax = parseBool(table.getAttribute("ajax"));
    if (!ajax) {
        document.location.assign(url);
        return;
    }
    url = url.addquerystring("ajax", "true");
    layer.open({
        type: 2
			  , title: "对比"
			  , moveOut: true
			  , shadeClose: true //点击遮罩关闭层
        //,area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"]
        //,offset: [rect.top + "px", rect.left + "px"]
			  , area: ["95%", "95%"]
			  , content: url

			  , success: function (layero, index) {
			      arrLayerIndex.push(index);
			  }
			  , cancel: function (index, layero) {
			      arrLayerIndex.pop();
			  }
    });
};
function contrastMore1()
{
	var sels=$("input[name='selitem']:checked");
	if(sels.length==0)
	{
		alert("请选择要对比的数据!");
		return;
	}	
	var ids="";
	for(var i=0;i<sels.length;i++)
	{
		if(i>0){ids+=",";}
		ids+=sels[i].value;
	}
	if(ids.length==0)
	{
		alert("没有符合条件的数据!");
		return;
	}
	var url=document.location.href;
	url+= url.indexOf("?") > -1 ? "&" : "?";
	url+="act=view&id=" + ids;	
	var table=getobj("eDataTable");
	var ajax = parseBool(table.getAttribute("ajax"));
	if(!ajax)
	{
		document.location.assign(url);
		return;
	}
	url=url.addquerystring("ajax","true");
	layer.open({
			  type: 2
			  ,title: "对比"	
			  ,moveOut:true
			  ,shadeClose: true //点击遮罩关闭层
			  //,area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"]
			  //,offset: [rect.top + "px", rect.left + "px"]
			  ,area: ["95%","95%"]
			  ,content: url
			  
			  ,success: function(layero, index)
			  {
				arrLayerIndex.push(index);
			  }
			  ,cancel: function(index, layero)
			  {
				  arrLayerIndex.pop();
			  }				
	});
}
function delrequest(url)
{
	url=url.addquerystring("ajax","true");
	$.ajax({
			type: 'get',
			async: false,
			url: url,	
			dataType: "html",
			success: function(data)
			{
			}
		});
}
//编辑所选按钮事件
function editMore(obj, width, height)
{
    if (!width) width = "95%";
    if (!height) height = "95%";
    var ids = getSelectIDS("edit");
    if (ids.length == 0) {
        layer.msg("请选择要编辑的数据!");
        return;
    }
    var url = document.location.href;
    if (ids.indexOf(",") > -1 || 3>1)
    {
        url = url.addquerystring("act", "editmore");
        url = url.addquerystring("ids", ids);
    }
    else
    {
        url = url.addquerystring("act", "edit");
        url = url.addquerystring("id", ids);
    }
   
    if (top != self)//Frame打开
    {
        url = url.addquerystring("ajax", "true");
        top.layer.open({
            type: 2
				  , title: "批量修改"
				  , moveOut: true
				  , maxmin: true
				  , shadeClose: true //点击遮罩关闭层
				  , area: [width, height]
				  , content: url
				  , success: function (layero, index) {
				      top.arrLayerIndex.push(index);
				  }
				  , cancel: function (index, layero) {
				      top.arrLayerIndex.pop();
				  }
				  , end: function (index) {
				      top.arrLayerIndex.pop();
				  }
        });
    }
    else {
        document.location.assign(url);
    }
};
function editMore1(obj,width,height)
{
	if(!width) width="95%";
	if(!height) height="95%";
	var sels=$("input[name='selitem']:checked");
	if(sels.length==0)
	{
		layer.msg("请选择要编辑的数据!");
		return;
	}	
	var ids="";
	sels.each(function(i,elem)
	{
		if($(elem).parents("tr:first").find("a[href*='act=del']").length > 0 || $(elem).parents("tr:first").find("a[_href*='act=del']").length > 0  || $(elem).parents("tr:first").find("a[ehref*='act=del']").length > 0 )
		{
			if(ids.length>0){ids+=",";}
			ids+=elem.value;
		}		
	});
	if(ids.length==0)
	{
		layer.msg("没有符合条件的数据!");
		return;
	}
	
	var url=document.location.href;
		//url+= url.indexOf("?") > -1 ? "&" : "?";		
		//url+="act=delmore&ids=" + ids;
	url=url.addquerystring("act","editmore");
	url=url.addquerystring("ids",ids);
	if(top!=self)//Frame打开
	{
		url=url.addquerystring("ajax","true");
		top.layer.open({
				  type: 2
				  ,title: "批量修改"	
				  ,moveOut:true
				  ,maxmin: true
				  ,shadeClose: true //点击遮罩关闭层
				  ,area: [width,height]
				  ,content: url			  
				  ,success: function(layero, index)
				  {
					  top.arrLayerIndex.push(index);
				  }
				  ,cancel: function(index, layero)
				  {
					  top.arrLayerIndex.pop();
				  }
				  ,end : function(index)
				  {
					  top.arrLayerIndex.pop();
				  }
				});	
	}
	else
	{
		document.location.assign(url);
	}
};
//删除所选按钮事件
function deleteMore1()
{
	//var sels=$("input[name='delitem']:checked");
	var sels=$("input[name='selitem']:checked");
	if(sels.length==0)
	{
		layer.msg("请选择要删除的数据!");
		return;
	}	
	var ids="";
	/*
	for(var i=0;i<sels.length;i++)
	{
		if(i>0){ids+=",";}
		ids+=sels[i].value;
	}
	*/
	
	sels.each(function(i,elem)
	{
		if($(elem).parents("tr:first").find("a[href*='act=del']").length > 0 || $(elem).parents("tr:first").find("a[_href*='act=del']").length > 0  || $(elem).parents("tr:first").find("a[ehref*='act=del']").length > 0 )
		{
			if(ids.length>0){ids+=",";}
			ids+=elem.value;
		}		
	});
	if(ids.length==0)
	{
		layer.msg("没有符合条件的数据!");
		return;
	}
	var page=getobj("page");
	//if(page)
	//alert(page.value);
	//return;
	
	//alert(ids);
	//return;
	var allitem=$("input[name='selallitem']:checked").length == 0 ? false : true;
	if(!allitem || 1==1)
	{
		//var _back=confirm('确认要删除所选数据吗？');
		//if(!_back){return;}	
		
		var url=document.location.href;
		//url+= url.indexOf("?") > -1 ? "&" : "?";		
		//url+="act=delmore&ids=" + ids;
		url=url.addquerystring("act","delmore");
		url=url.addquerystring("ids",ids);
		//alert(url);
		//return;
		layer.confirm('确认要删除所选数据吗?', {title: "删除",shadeClose: true, area:['220','160'], btn:['删除', '取消'],
			btn1:function(idx, layero)
			{
				
				if(top!=self)//Frame打开
				{
					delrequest(url);
					Search();
					layer.close(idx);
				}
				else
				{
					document.location.assign(url);
				}	
			}
		});
		
		
		/*
		if(top!=self)//Frame打开
		{
			delrequest(url);
			Search();
		}
		else
		{
			document.location.assign(url);
		}	
		*/
	}
	else
	{
		/*
		layer.confirm('确认要删除吗?', {title: "删除",shadeClose: true, btn: ['删除已选', '删除所有', '取消']},
			function (idx, layero)
			{
				layer.close(idx);
				var url=document.location.href;
				//url+= url.indexOf("?") > -1 ? "&" : "?";
				//url+="act=delmore&ids=" + ids;	
				url=url.addquerystring("act","delmore");
				url=url.addquerystring("ids",ids);
				//alert(url);
		//return;
				if(top!=self)//Frame打开
				{
					delrequest(url);
					Search();
				}
				else
				{
					document.location.assign(url);
				}
				
			},function(idx, layero)
			{
				layer.close(idx);
				var url=document.location.href;
				//url+= url.indexOf("?") > -1 ? "&" : "?";
				//url+="act=delmore";	
				url=url.addquerystring("act","delmore");
				//alert(url);
				if(top!=self)//Frame打开
				{
					delrequest(url);
					Search();
				}
				else
				{
					document.location.assign(url);
				}
			}
		);
		*/
		layer.confirm('确认要删除吗?', {title: "删除",shadeClose: true, btn: ['确认删除',  '取消']},
			function (idx, layero)
			{
				
				var url=document.location.href;
				//url+= url.indexOf("?") > -1 ? "&" : "?";
				//url+="act=delmore&ids=" + ids;	
				url=url.addquerystring("act","delmore");
				url=url.addquerystring("ids",ids);
				//alert(url);
		//return;
				if(top!=self)//Frame打开
				{
					delrequest(url);
					Search();
					layer.close(idx);
				}
				else
				{
					document.location.assign(url);
				}
				
			}
		);
	}
}
//刷新窗口数据
function reloadDoc()
{
	if(top!=self)
	{
		Search();
	}
	else
	{
		document.location.assign(document.location.href);
	}
}
//get请求
function ajaxGet(url)
{
	url=url.addquerystring("ajax","true");
	url=url.addquerystring("t",now());
	$.ajax({
		   type: 'get',
		   async: false,
		   url: url,
		   dataType: "html",
		   success: function(data){
			}
	});
}
//post请求
function ajaxPost(url,obj)
{
	url=url.addquerystring("ajax","true");
	$.ajax({
		   type: 'post',	
		   async: false,
		   url: url,
		   data:obj,
		   dataType: "html",
		   success: function(data){
			   //layer.msg(data);
			}
	});
}
function TableSum(id,name)
{
	var table=$("#" + id);
	var tbody=table.find("tbody");	
	var trs=tbody.find("tr:visible");
	var result=0;
	trs.each(function(i,el){		
		var hj=getHTMLValue($(this).find("[postname='" + name + "']").val());//合计
		result+=hj;
	});
	return result;
}
//去掉多余HTML返回数值类型
function getHTMLValue(html)
{
	var value=0;
	html=html.replace(/ /g,"");
	html=html.replace(/&nbsp;/g,"");
	html=html.replace(/,/g,"");
	if(html.length==0){return value;}
	try 
	{		
		value = html.indexOf(".") > -1 ? parseFloat(html) : parseInt(html);
    }
	catch(e)
	{
        return 0;
    }
	return value;
}
//生成拼音
function MakePinyin(obj,objid)
{	
	var value = obj.value.length==0 ? "" : pinyinUtil.getFirstLetter(obj.value, true).toString();
	$("#" + objid).val(value);
}
function IsMobile() 
{
    var userAgentInfo = navigator.userAgent.toLowerCase();
    var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone","iPad", "iPod", "Windows CE", "Windows Mobile", "UCWeb", "Midp"];
    var flag = false;
    for(var i = 0; i < Agents.length; i++) 
	{
        if (userAgentInfo.indexOf(Agents[i].toLowerCase()) > -1) 
		{
            flag = true;
            break;
        }
    }
    return flag;
}
function getReportHeight(obj)
{
	var rep=obj.parent();
	var height=rep.height();
	if(rep.find("h1").height()){height-=rep.find("h1").height()+14;}
	if(rep.find("p").height()){	height-=rep.find("p").height()+14;}
	return height;
}
function fonticonselect(obj)
{
	 var url = "../Plugins/FontIconSelect.aspx?obj=" + obj;
        layer.open({
            type: 2
          , title: "选择图标"
          , shadeClose: true //点击遮罩关闭层
          , area: ["1000px", "600px"]

          , content: url

          , success: function (layero, index) {
              arrLayerIndex.push(index);
          }
          , cancel: function (index, layero) {
              arrLayerIndex.pop();
          }

        });
}
function fileorpath_clear(obj)
{
	$("#" + obj).val('');
	 if(typeof(fileLibrary_select_finish)=="function"){fileLibrary_select_finish(obj);}
}
var fileLibraryobj=null;
function fileLibrary_select(obj,path,basepath)
{
	fileLibraryobj=getEventObject();
	var url = "../Plugins/FileSelect.aspx?obj=" + obj + (path.length > 0 ? "&path=" + path : "");
	if(basepath && basepath.length > 0){url+="&basepath=" + basepath;}
	url+= "&t=" + now();
    layer.open({
      type: 2,
      title: "选择文件",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['95%','95%'] : ["60%" , "80%"],    
      //area : ["60%" , "80%"],	
	  // content: [url,'no'], 
	  content: url,
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){
		  if(typeof(fileLibrary_select_finish)=="function"){fileLibrary_select_finish(obj);}
		  arrLayerIndex.pop();
	  }
    });	
}
function path_select(obj,path)
{
	var url = "../Plugins/PathSelect.aspx?obj=" + obj + (path.length > 0 ? "&path=" + path : "");
	url+= "&t=" + now();
    layer.open({
      type: 2,
      title: "选择目录",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['95%','95%'] : ["60%" , "40%"],    
	  btn: ['确定','取消'],
      //area : ["60%" , "80%"],	
	  // content: [url,'no'], 
	  content: url,
	  yes: function(index,layero)
	  {
		  var path=$(layero).find('iframe')[0].contentWindow.document.location.href.getquerystring("path");
		  $("#" + obj).val(path);
		  arrLayerIndex.pop();
		  layer.close(index);
	  },
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){arrLayerIndex.pop();}
    });	
}
//Excel导入
var uploadTempFile="";
function excel_import(area)
{
/*
layer.alert('欢迎访问 hangge.com', {
  resizing: function(layero){
    console.log(layero);
  }
});
*/
	var iframeWin;
	var url= "../Customs/base/ExcelImport.aspx?area=" + area;
	if(typeof(AppItem)=="string" && AppItem.length > 0){url+="&AppItem=" + AppItem;}
	if(typeof(ModelID)=="string" && ModelID.length > 0){url+="&ModelID=" + ModelID;}
	url+= "&t=" + now();
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: "Excel导入",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
      area : ['95%' , '90%'],
      content: url,
	  success: function(layero, index){
		  arrLayerIndex.push(index);
		  
		  //var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
		  //iframeWin = layero.find('iframe')[0].contentWindow;
		  // var path=$(layero).find('iframe')[0].contentWindow.document.location.href.getquerystring("path");
		  iframeWin = layero.find('iframe')[0];

		  
	  },
	  cancel: function(index, layero){
		  //arrLayerIndex.pop();

			   //alert( layero.find('iframe')[0].contentWindow.document.location);
	 },
	  end : function(index, layero, iframe){		  
		  //arrLayerIndex.pop();
		  //var _body = layer.getChildFrame('body', index);
    		//var win=$("#layui-layer-iframe" + index);			
		 	//alert(win.contentWindow);
			   //var res = window["layui-layer-iframe" + index].callbackdata(); 
			if(uploadTempFile.length>0)
			{
				removefile(uploadTempFile);
				uploadTempFile="";
			}
			 
		// alert( layero );
		  //var file=iframeWin.document.location.href.getquerystring("file");
		  //alert("end" + file);
		  document.location.assign(document.location.href);
	  }
    });
}
//自动回填
function autoFillN(obj,pid,objIds)
{
	var url=document.location.href;	
	url=url.removequerystring("debug");
	if(obj.tagName=="SELECT")
	{
		if(obj.options[obj.selectedIndex].getAttribute("code"))
		{
			if(obj.options[obj.selectedIndex].getAttribute("code").length>0)
			{
				pid=obj.options[obj.selectedIndex].getAttribute("code");
			}
		}
	}
	else
	{
		if(obj.getAttribute("code"))
		{
			if(obj.getAttribute("code").length>0)
			{
				pid=obj.getAttribute("code");
			}
		}
	}
	autoFill(obj,pid,objIds,url);
}
function autoFill(obj,pid,objIds,url)
{
	var objid=objIds.split(",");
	
	for(var t=0;t<objid.length;t++)
	{
		var file="";
		try
		{
			var arr=document.location.href.split("/");
			file=arr[arr.length-1].split(".")[0] + ".aspx";
		}
		catch(e)
		{
			file="Model.aspx";
		}
		var _pid=pid;
		if(!_pid)
		{
			if(obj.tagName=="SELECT")
			{
				
				if(obj.options[obj.selectedIndex].getAttribute("code"))
				{
					if(obj.options[obj.selectedIndex].getAttribute("code").length>0)
					{
						_pid=obj.options[obj.selectedIndex].getAttribute("code");
					}
				}
			}
			else
			{			
				switch(obj.type)
				{
					case "radio":
						if(obj.getAttribute("code"))
						{
							if(obj.getAttribute("code").length>0)
							{
								_pid=obj.getAttribute("code");
							}
						}
						break;
					case "checkbox":
						if(obj.getAttribute("code"))
						{
							if(obj.getAttribute("code").length>0)
							{
								_pid=obj.getAttribute("code");
							}
						}
						break;
				}
			}
		}
		var _url= file +  (!document.location.href.getquerystring("act") ? "?act=getdata" : "?act=edit");
		if(typeof(AppItem)=="string" && AppItem.length > 0){_url+="&AppItem=" + AppItem;}
		if(typeof(ModelID)=="string" && ModelID.length > 0){_url+="&ModelID=" + ModelID;}
		if(url){_url=url;}
		_url += "&Pid=" + _pid;
		_url += "&obj=" + objid[t];
		var query="";
		if(typeof(autoFill_before)=="function")
		{
			var _back = autoFill_before(objid[t]);
			if(typeof(_back)=="object")
			{
				query=_back.query.replace("?","");				
				if(query.length>0)
				{
					var arr=query.split("&");
					for(var x=0;x<arr.length;x++)
					{
						var arr2=arr[x].split("=");
						if(arr2.length==2)
						{
							_url=_url.addquerystring(arr2[0],arr2[1]);
						}
						//alert(arr[x] + "::" + arr2.length);
					}
					//alert(query + "::" + arr.length);
					//if(query.indexOf("&")!=0){query="&" + query;}	
					//alert(_url);
				}
			}
		}
		//if(query.length>0){_url+=query;}
		_url += "&t=" + now();
		//alert(_url);
		//return;
		$.ajax({
		type: "GET",
		async: false,
		url: _url,
		dataType: "json",
		success: function(data)
		{
			//alert(JSON.stringify(data));
			if(!data){return;}
			var box=$("#" + objid[t] + "_box");
			var controltype=box.attr("etype");
			var html='';
			//alert(controltype + "::" + JSON.stringify(data));
			switch(controltype)
			{
			    case "text":
			    case "textarea":
			        if (data.length > 0)
			        {
			            $("#" + objid[t]).val(data[0]["value"]);
			        }
					else
					{
						var dvalue=$("#" + objid[t]).attr("defaultvalue");
						$("#" + objid[t]).val(dvalue);
					}
			        break;
				case "filterselect":
					 box.find("li").remove();
					 box.find("input[type='hidden']:eq(0)").val('');
					 box.find("input[type='hidden']:eq(1)").val('');
					 box.find("span:eq(0)").find("span:eq(0)").text('请选择');
					 $.each(data, function()
					 {
						box.find("ul").append('<li value="' + this["value"] + '" onclick="set_filterText(this);">' + this["text"] + '</li>'); 
					 });
					break;
				case "autoselect":
					$("#" + objid[t]+"_1").get(0).length=1;
					for(var i=2;i<10;i++)
					{
						var tmp=getobj(objid[t] + "_" + i);
						if(!tmp){break;}
						tmp.parentNode.removeChild(tmp);
					}
					 $.each(data, function()
					 {
						$("#" + objid[t]+"_1").append('<option value="' + this["value"] + '">' + this["text"] + '</option>'); 
					 });
					break;
				case "loopselect":
				case "select":
					 $("#" + objid[t]).get(0).length=1;
					 $.each(data, function()
					 {
						$("#" + objid[t]).append('<option value="' + this["value"] + '">' + this["text"] + '</option>'); 
					 });
					 if(typeof($("#" + objid[t]).get(0).onchange)=="function")
					 {
						$("#" + objid[t]).trigger("change");
					 }
					break;
				case "radio":
					$.each(data, function(i,v)
					 {
						html+='<input etype="checkbox" type="radio" name="' + objid[t] + '" id="' + objid[t] + '_' + (i+1) +  '" value="' + this["value"]+ '" fieldname="'+ (box.attr("fieldname") ? box.attr("fieldname") : "")  +'" notnull="'+ (box.attr("notnull") ? box.attr("notnull") : "")  +'" text="'+this["text"] +'" defaultvalue="">';
						html+='<label for="' + objid[t] + '_' + (i+1) +  '">' +  this["text"]  + '</label>';
					 });
					box.html(html);
					break;
				case "checkbox":
					$.each(data, function(i,v)
					 {
						html+='<input etype="checkbox" type="checkbox" name="' + objid[t] + '" id="' + objid[t] + '_' + (i+1) +  '" value="' + this["value"]+ '" fieldname="'+ (box.attr("fieldname") ? box.attr("fieldname") : "") +'" notnull="'+ (box.attr("notnull") ? box.attr("notnull") : "")  +'" text="'+this["text"] +'" defaultvalue="">';
						html+='<label for="' + objid[t] + '_' + (i+1) +  '">' +  this["text"]  + '</label>';
					 });
					box.html(html);
					break;
			}
			if(typeof(autoFill_finsh)=="function"){autoFill_finsh(pid,objid[t]);}
			if(typeof(autoFill_finish)=="function"){autoFill_finish(pid,objid[t]);}
			
			/*
			
			
			//$("#" + ObjID).empty();
			
			 */
		}
		});
	}
}
//Ajax提交表单
function ajaxSubmit(frm)
{
	//if(Attribute(frmaddoredit,"finsh")=="true"){return;}
	//alert($(frm).serialize());
	//return;
	var _back=eCheckform(frm);
	if(!_back){return;}	
	//alert( $(frm).serialize());
	//document.write($(frm).serialize());
	//return;
	$.ajax({
			type: 'post',
			async: false,
			url: $(frm).attr("action"),			
			data: "ajax=true&" + $(frm).serialize(),
			//data:{ajax:"true",value:"22"},
			dataType: "json",
			success: function(data)
			{
				//alert(data);
				//alert(JSON.stringify(data));
				if(parseBool(data.success))
				{
					$(frm).find("input,select,textarea").each(function(i,el)
					{
						var v=$(el).val();
						if(v.length>0)
						{
							$(el).val(v.decode());
						}
					});
					if(frm["id"] && typeof(data.id) != "undefined")
					{
						frm["id"].value = data.id;						
					}
					if(typeof(data.message)==="undefined")
					{
						layer.msg("保存成功!");
					}
					else
					{
						layer.msg(data.message);
					}
					$(frm).find("input[type='password']").each(function(i,elem){
						var pwdMD5Twice = elem.value;	
						if(pwdMD5Twice.length>100) 
						{
							elem.value="******";
						}
					});
				}
				else
				{
					if(typeof(data.message)!=="undefined")
					{
						layer.msg(data.message);
					}
				}
			}
	});
}

//帮助中心窗口
function showHelp(ID)
{	
	var url="http://frame.eketeam.com/HelpContent/" + ID + ".html";
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: "帮助中心",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
      area : ['1000px' , '65%'],
      content: url,
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){arrLayerIndex.pop();}
    });
}
//生成网址二维码
function getURLCode(title,_url)
{
	//var url= "UrlCode.aspx?url=" + encodeURIComponent(_url);
	var url= virtualPath + "Plugins/UrlCode.aspx?url=" + encodeURIComponent(_url);
	url+= "&t=" + now();
	var html='<div style="text-align:center;line-height:35px;margin:10px;">' + title + '</div>';
	html+='<div style="margin:10px;text-align:center;"><img src="' + url + '" width="185"></div>';
	layer.open({
  	type: 1
	,area:['400px','400px']
	//,shade: 0.2 //透明度
  	,title: "手机扫一扫-预览" //不显示标题
	,closeBtn: 1
	,moveOut:true
	,scrollbar: false
	,shadeClose: true //开启遮罩关闭
	//,content:'<div style="padding:10px;"><img src="' + src + '" width="'+ w +'"></div'
  	,content:html
	,btn: ['关闭']
	,end: function(){}
	,success: function(layero, index){}
	
	});
}
//唯一性验证
function checkSingleN(obj,singleType,modelid)
{

	var url=document.location.href;	
	url=url.addquerystring("obj","checksingle");
	url=url.removequerystring("debug");
	url=url.addquerystring("act","add");	
	if(modelid){url=url.addquerystring("modelid",modelid);}	
	var frm=$(obj).parents("form:first");
	if(frm)
	{
		var id=frm.find("#ID").val();
		if(id&&id.length>0)
		{
			url=url.addquerystring("id",id);
		}
	}
	url+="&t=" + now();
	checkSingle(obj,url,singleType);
}
function checkSingle(obj,url,singleType)
{
	//checkSingle:0,一起验证；1，逐个验证
	var inputs=$(document.body).find("[checkvalue]");
	var frm=$(obj).parents("form:first");
	if(frm)
	{
		inputs=frm.find("[checkvalue]");
	}
	
	//var inputs=$(document.body).find("[checkvalue]");
	/*
	if(inputs.length == 1 && Attribute(obj,"ovalue") == obj.value && obj.value.length > 0)//编辑
	{
		//obj.setAttribute("checkvalue","false");
		return;
	}
	*/
	//document.title=inputs.length;
	var _url=document.location.href;	
	//_url=_url.addquerystring("act","getdata");
	_url=_url.addquerystring("act","checksingle");	
	_url+="&t=" + now();
	if(url){_url=url;}
	//return;
	var cancel_list=",";
	var hasnull=false;
	var haschange=false;
	inputs.each(function(i,el){
		if(cancel_list.indexOf("," + el.name.toLowerCase() + ",")>-1){return true;}	
		var type=Attribute(el,"type").toLowerCase();	
		var value="";
		var ovalue=$(el).attr("ovalue");
		if(ovalue.length==0){haschange=true;}
		switch(type)
		{
			case "checkbox":				
				$("input[name='" + el.name + "']:checked").each(function(i,sel){
					if(i>0){value+=",";}
					var _value=$(sel).val();
					if(ovalue.length>0 && _value!=ovalue ){haschange=true;}
					if(_value.toLowerCase()=="true"){_value="1";}
					if(_value.toLowerCase()=="false"){_value="0";}					
					value+=_value;
				}); 
				break;
			case "radio":
				value= $("input[name='" + el.name + "']:checked").val();
				if(ovalue.length>0 && value!=ovalue){haschange=true;}
				break;
			default:
				value=$(el).val();
				if(ovalue.length>0 && value!=ovalue){haschange=true;}
				break;
		}
		if(value.length==0){hasnull=true;return false;}	
		if(value.toLowerCase()=="true"){value="1";}
		if(value.toLowerCase()=="false"){value="0";}
		_url+= "&" + el.name + "=" + value;
		cancel_list+=el.name.toLowerCase() + ",";
	});

	if(hasnull || !haschange){return;}
	
	$.ajax({
			type: 'get',
			async: false,
			url: _url,
			dataType: "json",
			success: function(data)
			{
				if(parseBool(data.success))
				{					
					//obj.setAttribute("checkvalue",data.value);
					inputs.each(function(i,el){
						//el.setAttribute("checkvalue",data.value);
							$(el).prop("checkvalue",data.value);
							$(el).attr("checkvalue",data.value);
					});
					if(inputs.length==1 && data.value=="true")
					{
						//alert(Attribute(obj,"fieldname") + "已经存在!");

					}

					if(inputs.length==1 && data.value=="true" && typeof(layer)!="undefined")
					{
						layer.msg($(inputs[0]).attr("fieldname") + "已经存在!");
					}
					//alert(singleType + "::" + inputs.length);
				}
			}
		});
}
//颜色选择器
function showColor(id)
{	
	var url=virtualPath + "Plugins/eColor.html?id=" + id + "&t=" + now();
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: "颜色选择",
	  moveOut:true,
      maxmin: false,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['280px' , '246px'] : ['270px' , '236px'],   
      content: url,
	  
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){arrLayerIndex.pop();}
    });
}
//百度地图
function openbdMap(id)
{	
	var url=virtualPath + "Plugins/bdmap.html?id=" + id;
	url+= "&t=" + now();
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: "百度地图位置坐标拾取",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['95%','65%'] : ['640px' , '580px'],   
      content: url,
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){arrLayerIndex.pop();}
	 
    });
}
function viewbdMap(lng,lat,zoom)
{	
	var url=virtualPath + "Plugins/bdmapview.html?lng="+lng+"&lat="+lat+"&zoom="+zoom;
	url+= "&t=" + now();
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: "百度地图位置",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['95%','65%'] : ['630px' , '520px'],   
      //content: url,
	  content: [url,'no'], 
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){arrLayerIndex.pop();}
	 
    });
}
//高德地图
function openaMap(id)
{	
	var url=virtualPath + "Plugins/amap.html?id=" + id;
	url+= "&t=" + now();
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: "高德地图位置坐标拾取",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['95%','65%'] : ['630px' , '520px'],   
      //content: url,
	  content: [url,'no'], 
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){arrLayerIndex.pop();}
	 
    });
}
function viewaMap(lng,lat,zoom)
{	
	var url=virtualPath + "Plugins/amapview.html?lng="+lng+"&lat="+lat+"&zoom="+zoom;
	url+= "&t=" + now();
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: "高德地图位置",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['95%','65%'] : ['630px' , '520px'],   
      //content: url,
	  content: [url,'no'], 
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){arrLayerIndex.pop();}
	 
    });
}
//腾讯地图
function openqqMap(id)
{	
	var url=virtualPath + "Plugins/qqmap.html?id=" + id;
	url+= "&t=" + now();
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: "腾讯地图位置坐标拾取",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['95%','86%'] : ['630px' , '610px'],   
      //content: url,
	  content: [url,'no'], 
	  success: function(layero, index){		  
		  arrLayerIndex.push(index);
		  var _minwidth=400;
		  var _minheight=300;
		  try
		  {
			  //layer.style(index, {minWidth:_minwidth+'px',minHeight:_minheight+'px'});
			  //layero.find('iframe')[0].style.minWidth=_minwidth+'px';
			  //layero.find('iframe')[0].style.minHeight=(_minheight-42)+'px';
		  } catch (e) {}
	  },
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){arrLayerIndex.pop();}
	 
    });
}
function viewqqMap(lng,lat,zoom)
{	
	var url=virtualPath + "Plugins/qqmapview.html?lng="+lng+"&lat="+lat+"&zoom="+zoom;
	url+= "&t=" + now();
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: "腾讯地图位置",
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  area:IsMobile() ? ['95%','76%'] : ['630px' , '610px'],   
      //content: url,
	  content: [url,'no'], 
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){arrLayerIndex.pop();}
	 
    });
}



//返回
function goBack()
{
	//if(top!=window)
	if(top!=self)//Frame打开
	{
		if(top.arrLayerIndex.length>0)
		{
			top.layer.close(top.arrLayerIndex.pop());
		}
		else
		{
			if(parent.arrLayerIndex && parent.arrLayerIndex.length>0)
			{
				parent.layer.close(parent.arrLayerIndex.pop());
			}
			else
			{
				history.back();
			}
		}  
	}
	else
	{
		if(parent.arrLayerIndex && parent.arrLayerIndex.length>0)
		{
			layer.close(arrLayerIndex.pop());
		}
		else
		{
			history.back();	
		}
	}
}

function go_Action(obj,text,frametop)
{
	//var _back=confirm('确认要' + text + '吗？');
	//if(!_back){return;}
	var url=obj.getAttribute("ehref");	
	$.ajax({
		   type: "get",
		   async: false,
		   url:url,
		   dataType: "html",
		   success: function(data)
		   {
			   if(frametop==1)
			   {
				   top.layer.close(top.arrLayerIndex.pop());	
				   
				   
			   }
			   else
			   {
				   parent.layer.close(parent.arrLayerIndex.pop());
			   }
			   var curtab = $(top.document).find(".eFrameTab dt a.cur");
				   var win = $(top.document).find(".eFrameTab dd iframe:eq(" + curtab.index() + ")").get(0).contentWindow;
				   if (win.treefrommode == "tree") {
					   win.TreeModelUpdate();
				   }
				   else {
					   win.Search();
				   }
			   /*
			   layer.close(arrLayerIndex.pop());
			   var curtab = $(document).find(".eFrameTab dt a.cur");
			   var win = $(document).find(".eFrameTab dd iframe:eq(" + curtab.index() + ")").get(0).contentWindow;
			   if (win.treefrommode == "tree") {
			       win.TreeModelUpdate();
			   }
			   else {
			       win.Search();
			   }
			   */
		   }
	});
}
function goAction(obj,text,frametop)
{
	if(typeof(frametop)== "undefined"){frametop=1;}
	 layer.confirm('确认要'+text+'吗?', {
		title: text, shadeClose: true, area: ['200', '300'], btn: [text, '取消'],
        btn1: function (idx, layero) {
            layer.close(idx);
            go_Action(obj,text,frametop);
        }
     });
}
function isSameDomain()
{
	//var parentDOM = top || window;
    try 
	{
       if(top.layer)
	   {
		   return true;
	   }
    }
	catch(e)
	{
	}
	return false;
}
var treefrommode = "";
var treefromact = "";
var treefromid = "";
var treefrompid = "";
function goLink(obj,width,height,frametop,ismax)
{
	if(!width) width="95%";
	if(!height) height="95%";
	ismax=ismax||false;
	var url = obj.getAttribute("ehref");
	if (url.indexOf("?") == 0) { url = "model.aspx" + url;}
	treefrommode = url.getquerystring("mode");
	treefromact = url.getquerystring("act");
	treefromid = url.getquerystring("id");
	treefrompid = url.getquerystring("parid");

	//alert(treefrommode + "::" + treefromid);
	if(typeof(frametop)== "undefined"){frametop=1;}
	if(url.toLowerCase().indexOf("appitem=")==-1)
	{
		if(typeof(AppItem)=="string" && AppItem.length>0){url=url.addquerystring("AppItem",AppItem);}
	}
	var action = url.toLowerCase().getquerystring("act");
	if(obj.getAttribute("etext"))
	{
	    var _text = obj.getAttribute("etext");
	    var _href = url.getquerystring("appitem").length > 0 ? url.getquerystring("appitem") : url;
	    var tab = $(".eFrameTab dt a[_href='" + _href + "']");
	    if (tab.length == 0) {
	        url = url.removequerystring("act");
			var eappid="";
			var app = $(".applists a.cur");
			if(app.length>0)
			{
				eappid=app.attr("eappid");
			}
	        parent.eFrameTab_add(url,_text,eappid);
	        if (action.length > 0) {
	            setTimeout(function () {
	                parent.goLink(obj, width, height, frametop, ismax);
	            }, 500);
	        }
	        return;
	    }
        /*
        parent.eFrameTab_add(url, _text);
        return;
        */
	} 
	if(url.toLowerCase().indexOf("=del")>-1)
	{
		var _back=confirm('确认要删除吗？');
		if(!_back){return;}		
	}
	//展示	
	var eframe=obj.getAttribute("eframe")||"true";		
	if(url.toLowerCase().indexOf("value=")==-1 &&  url.toLowerCase().indexOf("=del")==-1 &&  url.toLowerCase().indexOf("=cancel")==-1  && (eframe=="true" || url.toLowerCase().indexOf("=add")>-1 || url.toLowerCase().indexOf("=edit")>-1 || url.toLowerCase().indexOf("=copy")>-1 || url.toLowerCase().indexOf("=view")>-1 || url.toLowerCase().indexOf("=print")>-1 ))
	{
			//alert(1 + ":" + url);
			//if(url.indexOf(".aspx")== -1){url="ModelInfo.aspx" + url;}
			//else{url=url.replace("Model.aspx","ModelInfo.aspx");}
		 	//if(typeof(AppItem)=="string" && AppItem == url.getquerystring("appitem") )		
			
			if(url.toLowerCase().indexOf("act=")>-1 ){url=url.addquerystring("ajax","true");}
			//alert(url + "::" + url.toLowerCase().indexOf("=print"));

			var title=obj.innerText;
			if(title.indexOf("添加")>-1) {title="添加";}
			if(obj.getAttribute("etext")){title=obj.getAttribute("etext");}
			if(obj.getAttribute("etitle")){title=obj.getAttribute("etitle");}

			//var table=getobj("eDataTable");			
			//var rect = table.getBoundingClientRect();
			//var rc = document.body.getBoundingClientRect();
			
			//parent.layer.open({
			if(isSameDomain() && frametop==1)
			{
				top.layer.open({
				  type: 2
				  ,title: title	
				  ,moveOut:true
				  ,maxmin: true
				  ,shadeClose: true //点击遮罩关闭层
				  //,area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"]
				  //,offset: [rect.top + "px", rect.left + "px"]
				  //,area: ["95%","95%"]
				  ,area: [width,height]
				  ,content: url			  
				  ,success: function(layero, index)
				  {
					  if(ismax){
					  top.layer.full(index);
					  }
				      top.arrLayerIndex.push(index);			     
				      setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
				  }
				  ,cancel: function(index, layero)
				  {
					  top.arrLayerIndex.pop();
				  }
				  ,end : function(index)
				  {
					  top.arrLayerIndex.pop();
				  }
				});	
			}
			else
			{
				layer.open({
				  type: 2
				  ,title: title	
				  ,moveOut:true
				  ,maxmin: true
				  ,shadeClose: true //点击遮罩关闭层
				  //,area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"]
				  //,offset: [rect.top + "px", rect.left + "px"]
				  //,area: ["95%","95%"]
				  ,area: [width,height]
				  ,content: url			  
				  ,success: function(layero, index)
				  {
					  if(ismax){
					  layer.full(index);
					  }
					  arrLayerIndex.push(index);
				  }
				  ,cancel: function(index, layero)
				  {
					  arrLayerIndex.pop();
				  }
				  ,end : function(index)
				  {
					  arrLayerIndex.pop();
				  }
				});	
			}

			/*
			var index = layer.open({
			  type: 2
			  ,title: title			
			  ,content: url
				
			});
			//layer.full(index);
			*/
			
			
			//document.location.assign(url);
			
			return;
		}
		$.ajax({
			   type: "get",
			   async: false,
			   url:url,
			   dataType: "html",
			   success: function(data)
			   {
				   //var curtab = $(parent.document).find(".eFrameTab dt a.cur");
				   //var win= $(parent.document).find(".eFrameTab dd iframe:eq(" + curtab.index() + ")").get(0).contentWindow;
				   //var page=$(win.document).find("#page").val();
				   //win.Search(page);
				   var _count=$(parent.document).find(".eFrameTab dt a.cur").length;
				   if(_count==1)
				   {
					   var curtab = $(parent.document).find(".eFrameTab dt a.cur");
					   var doc = $(parent.document).find(".eFrameTab dd iframe:eq(" + curtab.index() + ")").get(0).contentWindow;
					   if (doc.treefrommode == "tree") {
					       doc.TreeModelUpdate();
					   }
					   else {
					       doc.Search();
					   }
				   }
				   else
				   {
				       if (parent.treefrommode == "tree") {
				           parent.TreeModelUpdate();
				       }
				       else {
				           parent.Search();
				       }
				   }				   
			   }
			});
	
	
}
//首页
function page_First()
{
	var table=getobj("eDataTable");
	var page=getobj("page");
	if(!table || !page){return;}	
	var ajax = parseBool(table.getAttribute("ajax"));
	
	var num=parseInt(page.value);
	if (num <= 1)
	{
	    layer.msg("当前已是首页!");
	    return;
	}

	if(ajax)
	{
		Search(1);
	}
	else
	{
		var url=getPageUrl();

		if(typeof(AppItem)=="string" && AppItem.length > 0){url=url.addquerystring("AppItem",AppItem);}

		url=url.addquerystring("page","1");
		url=url.addquerystring("t",now());
		document.location.assign(url);
	}
}
//上一页
function page_Previous()
{	
	var table=getobj("eDataTable");
	var page=getobj("page");
	if (!table || !page) { return; }
	
	var ajax = parseBool(table.getAttribute("ajax"));
	var num =parseInt(page.value);
	var maxnum = parseInt(page.getAttribute("maxvalue"));
	if (num <= 1)
	{
	    layer.msg("当前已是第一页!");
	    return;
	}
	num-=1;
	if(ajax)
	{
		Search(num);
	}
	else
	{
		var url=getPageUrl();
		if(typeof(AppItem)=="string" && AppItem.length > 0){url=url.addquerystring("AppItem",AppItem);}
		url=url.addquerystring("page",num);
		url=url.addquerystring("t",now());
		document.location.assign(url);
	}
}
//下一页
function page_Next()
{	
	var table=getobj("eDataTable");
	var page=getobj("page");
	if(!table || !page){return;}	
	var ajax = parseBool(table.getAttribute("ajax"));
	var num =parseInt(page.value);
	var maxnum = parseInt(page.getAttribute("maxvalue"));
	if (num >= maxnum)
	{
	    layer.msg("当前已是最后一页!");
	    return;
	}
	num+=1;
	if(ajax)
	{
		Search(num);
	}
	else
	{
		var url=getPageUrl();
		if(typeof(AppItem)=="string" && AppItem.length > 0){url=url.addquerystring("AppItem",AppItem);}
		url=url.addquerystring("page",num);
		url=url.addquerystring("t",now());
		document.location.assign(url);
	}
}
//尾页
function page_Last()
{
	var table=getobj("eDataTable");
	var page=getobj("page");
	if(!table || !page){return;}	
	var ajax = parseBool(table.getAttribute("ajax"));
	
	var num =parseInt(page.value);
	var maxnum = parseInt(page.getAttribute("maxvalue"));
	if (num >= maxnum)
	{
	    layer.msg("当前已是尾页!");
	    return;
	}

	if(ajax)
	{
		Search(maxnum);
	}
	else
	{
		var url=getPageUrl();
		if(typeof(AppItem)=="string" && AppItem.length > 0){url=url.addquerystring("AppItem",AppItem);}
		url=url.addquerystring("page",maxnum);
		url=url.addquerystring("t",now());
		document.location.assign(url);
	}
}
//获取页面URL
function getPageUrl()
{
	var url=$("#frmsearch").attr("action") || document.location.href;	
	if(document.forms["frmsearch"])
	{
		var info=getSearchInfo(frmsearch);
		var hash=info.hash;
		var keys = hash.keys();
		//for(var entry in keys)
		for(var i=0;i<keys.length;i++)
		{
			//var key=keys[entry];
			var key=keys[i];
			var value=hash.get(key);
			url=url.addquerystring(key,value);		
			//alert(key + "=" + value);
		}
	}
	if(typeof(AppItem)=="string" && AppItem.length > 0){url=url.addquerystring("AppItem",AppItem);}
	return url;
}
//ajax搜索、跳转分页
function Search(page,ajax)
{
	if(ajax && typeof(search_before)=="function")
	{
		var _back=search_before(frm);
		if(!_back){return false;}
	}
	page = page || $("#page").val() || 1;	
	var url=$("#frmsearch").attr("action") || document.location.href;		
	//url=url.addquerystring("page",page);
	if(url.toLowerCase().indexOf("page=")>-1){url=url.addquerystring("page",page);}
	else
	{
		if(parseInt(page)>1){url=url.addquerystring("page",page);}
	}
	if(url.toLowerCase().indexOf("ajax=")==-1){url=url.addquerystring("ajax","true");}		
	if(typeof(AppItem)=="string" && AppItem.length > 0){url=url.addquerystring("AppItem",AppItem);}
	
	var btn=$("#btn_Export");
	var exportbtn = btn.length == 0 ? null : btn;
	var replaceexp=false;
	var _exurl="";
	if(exportbtn)
	{
	    _exurl = exportbtn.attr("basehref");
		if(_exurl){replaceexp=true;}
	}

	btn = $("#btn_Print");
	var printbtn = btn.length == 0 ? null : btn;
	var replaceprt = false;
	var _prurl = "";
	if (printbtn) {
	    _prurl = printbtn.attr("basehref");
	    if (_prurl) { replaceprt = true; }
	}

	if(document.forms["frmsearch"])
	{
		var info=getSearchInfo(frmsearch);
		var hash=info.hash;
		var keys = hash.keys();
		//for(var entry in keys)
		for(var i=0;i<keys.length;i++)
		{
			//var key=keys[entry];
			var key=keys[i];
			var value=hash.get(key);
			url=url.addquerystring(key,value);		
			if (replaceexp) { _exurl = _exurl.addquerystring(key, value); }
			if (replaceprt) { _prurl = _prurl.addquerystring(key, value); }
		}
		if(replaceexp)
		{
			exportbtn.attr("href",_exurl);
		}
		if (replaceprt) {
		    printbtn.attr("href", _prurl);
		}
	}
	url=url.removequerystring("debug");
	url=url.addquerystring("t",now());
	
	var groups = $(".esearchgroup");	
	if (groups.length > 0 && document.forms["frmsearch"])
	{
	    var info = getSearchInfo(frmsearch);
	    var hash = info.hash;
	    var keys = hash.keys();
	    for (var i = 0; i < keys.length; i++) {
	        var key = keys[i];
	        var value = hash.get(key);
	        groups.find("a").each(function (index, val) {
	            var _url = $(this).attr("href");
	            if (_url.length > 0)
	            {
	                if (value.length > 0) {
	                    _url = _url.addquerystring(key, value);
	                } else {
	                    _url = _url.removequerystring(key);
	                }
	            }
	            $(this).attr("href",_url);
	        });
	        
	    }
	 
	    //alert(groups.length);
	}
	
	
	var table=getobj("eDataTable");//无数据时没有	
	if(table)
	{
		var orderby=table.getAttribute("orderby");
		url=url.removequerystring("orderby");	
		if(orderby.length>0)
		{
			url=url.addquerystring("orderby",orderby);
		}
	}


	var Loading = getobj("DivLoading");
	if(!Loading)
	{	
		
		//var rect = table.getBoundingClientRect();
		var rect = document.body.getBoundingClientRect();
	
		Loading = document.createElement("div");
		Loading.id="DivLoading";
		Loading.className="eDataTable_Loading";
		Loading.style.zIndex="200";	
		Loading.style.width = (rect.right -  rect.left) + "px";
		Loading.style.height = (rect.bottom -  rect.top) + "px";	
		//Loading.style.top = rect.top + "px";
		//Loading.style.left = rect.left + "px";
		Loading.style.top =  "0px";
		Loading.style.left =  "0px";
		//document.body.appendChild(Loading);
	}
	

	//alert(url);
	//return;

	//$(".page").val(page);
	
	$.ajax({
		   type: "get",
		   async: false,
		   url:url,
		   dataType: "json",
		   success: function(data)
		   {
			 
			   if(typeof(data.table)!="undefined" || typeof(data.bodyhtml)!="undefined")
			   {
				   var dt=getobj("divlist");
				   if(dt)
				   {
						$("#divlist").html(data.table.decode());
				   }
				   else
				   {
					   dt=getobj("containerbody");
					   if(dt)
					   {
						   $("#containerbody").html(data.bodyhtml.decode());
					   }
					   else
					   {
						   $("#eDataTable").prop("outerHTML", data.table.decode());
					   }
				   }
			   }
			   init_dellink();
			   //$("#eDataTable tbody").html(data.tbody.decode());
			   //$("#epage").html(data.epage.decode());
			  
			   if(typeof(data.epage)!="undefined")
			   {
				   var pg=getobj("epage");			   
				   if(pg)
				   {
						pg.innerHTML=data.epage.decode();
				   }
				   else
				   {
					   $(".epager").prop("outerHTML", data.epage.decode());
				   }
			   }
			  // parent.document.title=3;

			   try
			   {
			   deleteObject(Loading);
			   }
			   catch(e)
			   {
			   }
			   //selectMore_check();
			   etable_init();
			   init_quickviewBody();
			    $("span.more").each(function(index, val) {
						var ele = $(this);		
						ele.on("click", function() {
							showOptionMenu(this);			
						});	
					
					});
			   
			   var table=document.getElementById("eDataTable");
			   if(table)
			   {
				   /*
				   if(table.parent)
				   {
				   		Table_Init_Tbody(table.parent);
				   }
				   */
				  
			   }
			   
		   }
	});
	

	
}
//提交搜索
function goSearch(frm,ajax)
{
	if(typeof(search_before)=="function")
	{
		var _back=search_before(frm);
		if(!_back){return false;}
	}
	var info=getSearchInfo(frm);
	document.location=info.url.replace(/\+/g,'%2B');//+号解码会变空格
	return false;
}
function getEasyUISearch(frm)
{
	var obj=new Object();
	var info=getSearchInfo(frm);
	var hash=info.hash;
	var keys = hash.keys();
	//for(var entry in keys)
	for(var i=0;i<keys.length;i++)
	{
		//var key=keys[entry];
		var key=keys[i];
		var value=hash.get(key);
		obj[key] = value;
	}	
	return obj;
}
function showPower(obj)
{
	var div=obj.parentNode;
	div=div.nextSibling;
	while(div.tagName!="DIV")
	{
		div=div.nextSibling;
	}
	//if(div.nodeType==3){div=div.nextSibling;}
	if(obj.className=="close")
	{
		obj.className="open";
		div.style.display="";
	}
	else
	{
		obj.className="close";
		div.style.display="none";
	}
}
//角色选择、取消选择
function selectRoles(obj)
{
	//var url="?act=getrole&roleid=" + obj.value + "&t=" + now();

	$(".powerContent input[type='checkbox']").prop("checked",false);
	var div=$(obj).parent().parent();
	var inputs=div.find("input:checked");
	//if(inputs.length==0){return;} //还有用户权限，
	var values="";
	inputs.each(function(i,elem){
		if(i>0){values+=",";}			 
		values+=elem.value;
    });

	var url=document.location.href;	
	if(typeof(AppItem)=="string" && AppItem.length > 0){url=url.addquerystring("AppItem",AppItem);}
	url=url.addquerystring("act","getrole");
	//url=url.addquerystring("roleid",obj.value);
	url=url.addquerystring("roleid",values);	
	url=url.addquerystring("t", now());
	
	//alert(url);
	//return;
	//if(obj.type=="radio"){$(".powerContent input[type='checkbox']").prop("checked",false);}

	$.ajax({
		   type: "get",
		   async: false,
		   url:url,
		   dataType: "json",
		   success: function(data)
		   {
			   //var json=new eJson(data);
			   //alert(json.toJson());
			   //$("#json").val( now() + "\n" +  json.toJson());
			   if(!data){return;}
			  // alert(JSON.stringify(data));
			   for(var i=0;i<data.length;i++)
			   {
				   for(p in data[i])
				   {
					   
					   if(p.toLowerCase()=="convert"){continue;}
					   if(typeof(data[i][p])=="function"){continue;}
					   if(p.toLowerCase() == "modelid" || p.toLowerCase() == "applicationitemid" || p.toLowerCase() == "applicationid"){continue;}
						//if(inputs.length==1) alert(p + "::" + data[i][p]);
						if(data[i][p].toLowerCase() == "true")
						{
							var sel=(data[i]["ApplicationItemID"] ?  getobj("model_" + p.toLowerCase() + "_" + data[i]["ApplicationItemID"].replace(/-/g,"") + "_" + data[i]["ModelID"].replace(/-/g,"")) : getobj("model_" + p.toLowerCase() + "_" +  data[i]["ModelID"].replace(/-/g,"")) );
							if(sel)
							{
								sel.checked=true;//obj.checked;
							}
							if(p.toLowerCase()=="list")
							{
								sel=(data[i]["ApplicationItemID"] ? getobj("model_" + data[i]["ApplicationItemID"].replace(/-/g,"") + "_" + data[i]["ModelID"].replace(/-/g,"")) : getobj("model_" + data[i]["ModelID"].replace(/-/g,"")));

								if(sel)
								{
									sel.checked=true;//obj.checked;
								}
								
							}
						}
				   }
			   }
		   }
	});
	//alert(url + "::" + obj.checked);	
}
//全选模块权限
function SelectAllItem(obj,type)
{
	$("input[name*='" + type + "']").each(function(i,el){
		//$(this).trigger("click");
		$(this).prop("checked",obj.checked);
		if(type=="model_list_")
		{
			userCanelAll(el);
			if(!obj.checked)
			{
				$("#allmodelbody input").prop("checked",obj.checked);
			}
		}
	});
}
function SelectAllModel(obj)
{
	$(".modelname").each(function(i,el){
		$(this).find("input:eq(0)").prop("checked",obj.checked);
		userSelectAll($(this).find("input:eq(0)").get(0));
		$("#allmodelbody input").prop("checked",obj.checked);
	});
}
//内容区-全选
function SelectContent(obj)
{
	var div=obj.parentNode.parentNode;	
	var inputs=div.getElementsByTagName("input");
	for(i=0;i < inputs.length;i++)
	{
		if(inputs[i]==obj || inputs[i].type.toLowerCase()!="checkbox"){continue;}
		inputs[i].checked=obj.checked;
	}
};
//用户权限-全选
function userSelectAll(obj)
{
	var div=obj.parentNode.parentNode;	
	var inputs=div.getElementsByTagName("input");
	for(i=0;i < inputs.length;i++)
	{
		if(inputs[i]==obj || inputs[i].type.toLowerCase()!="checkbox"){continue;}
		inputs[i].checked=obj.checked;
	}
}
//用户权限-列表权限
function userCanelAll(obj)
{
	var div=obj.parentNode.parentNode;	
	var inputs=div.getElementsByTagName("input");
	if(obj.checked)
	{
		inputs[0].checked=true;
		return;
	}
	for(i=0;i < inputs.length;i++)
	{
		if(inputs[i]==obj || inputs[i].type.toLowerCase()!="checkbox"){continue;}
		inputs[i].checked=false;
	}
}

//$(function (){ });
//$(function (){
	//$(document).keydown(function(e){
//document.title=e.keyCode;
//});
//});

function selectselItems(obj)
{
	//$("input[name='fillselitem']").prop("checked",obj.checked);
	//$("input[name='fillselitem']:not(:checked)").each(function(i,el){
	$("input[name='fillselitem']:not(:checked)").each(function(i,el){
		 $(this).get(0).click();
	});
}
function excel_add(obj,ModelID)
{
	var table=$(obj).parents("table:first");
	var tfoot=table.find("tfoot");
	var tr=tfoot.find("tr")[0].cloneNode(true);	
	var tbody=table.find("tbody");
	var _max=tbody.children().length + 1;
	$(tr).find("input[type='radio']").each(function(i,el){
		$(this).attr("name","row_" + _max + "_" + $(this).attr("name"));	 
	});	
	tbody[0].appendChild(tr);
	
	if(table.find("thead").text().indexOf("序号")>-1)
	{
		tbody.find("tr:visible").each(function(i,el){
			$(this).find("td:eq(1)").html(i+1);		
		});
	}
	//$("#count_" + ModelID).val(tbody.find("tr:visible").length);	
	var count;
	if(form_area)
	{
		count=form_area.find("#count_" + ModelID);
		count=count.length>0 ? count[0] : count=getobj("count_" + ModelID);
	}
	else
	{
		count=getobj("count_" + ModelID);
	}
	if(count)
	{
		count.value=tbody.find("tr:visible").length;
	}
	
	excel_pack(ModelID);
	//alert(table.tagName);
	//var tr=tfoot.getElementsByTagName("tr")[0].cloneNode(true);
	if(typeof(submodel_onChange)=="function")
	{
		var list_trs=tbody.find("tr:visible");
		submodel_onChange(ModelID,list_trs,tbody);//数据为空
	}
	//alert("add line or select more lines!");
	
}
function excel_delete(obj,ModelID,cancelconfirm)
{
	if(!cancelconfirm)
	{
		if(!confirm("确认要删除吗？")){return;}
	}
	var table=$(obj).parents("table:first");
	form_area=table.parent();
	
	var tbody=table.find("tbody");
	var tr=$(obj).parents("tr:first");
	var index=tr.index();
	//var input=getobj("eformdata_" + ModelID);	
	var input;
	if(form_area)
	{
		input=form_area.find("#eformdata_" + ModelID);		
		input=input.length>0 ? input[0] : getobj("eformdata_" + ModelID);
	}
	else
	{
		input=getobj("eformdata_" + ModelID);
	}

	
	
	
	var model=input.value.toJson();
	//model.Convert=true;	
	//alert(index + "::" + model.toJson());
	//return;
	var _model=model.get("eformdata_" + ModelID);
	_model=_model[index];
	
	
	tr.find("input[name='Delete']").val("true");
	
	if(_model["ID"].length==0)
	{
		_model=model.get("eformdata_" + ModelID)
		_model.remove(index);
		tr.remove();
	}
	else
	{
		_model["Delete"]="true";
		tr.hide();
	}
	input.value=model.toJson();	
	//excel_pack(ModelID);
	tbody.find("tr:visible").each(function(i,el){
		var tdnum=$(this).find("td:eq(1)");
		if(tdnum.attr("class")=="num")
		{
			tdnum.html(i+1);
		}
		//$(this).find("td:eq(1)").html(i+1);
	});
	//$("#count_" + ModelID).val(tbody.find("tr:visible").length);
	var count;
	if(form_area)
	{
		count=form_area.find("#count_" + ModelID);
		count=count.length>0 ? count[0] : count=getobj("count_" + ModelID);
	}
	else
	{
		count=getobj("count_" + ModelID);
	}
	if(count)
	{
		count.value=tbody.find("tr:visible").length;
	}
	
	
	
	if(typeof(submodel_onChange)=="function")
	{
		var list_trs=tbody.find("tr:visible");
		submodel_onChange(ModelID,list_trs,tbody[0]);
	}
}
function excel_pack(ModelID)
{
	//var table=$("#eformlist_" + ModelID);
	var table;
	if(form_area)
	{
		table=form_area.find("#eformlist_" + ModelID);
		if(table.length==0)
		{
			table=$("#eformlist_" + ModelID);
		}
	}
	else
	{
		table=$("#eformlist_" + ModelID);
	}

	//clearPack($(table));
	
	var tbody=table.find("tbody");
	var tfoot=table.find("tfoot");
	if(tfoot.length>0){addPack(tfoot);}
	//var input=getobj("eformdata_" + ModelID);
	var input;
	if(form_area)
	{
		input=form_area.find("#eformdata_" + ModelID);		
		input=input.length>0 ? input[0] : getobj("eformdata_" + ModelID);
	}
	else
	{
		input=getobj("eformdata_" + ModelID);
	}
	if(!input){return;}
	
	var model=input.value.toJson();	
	//model.Convert=true;
	//alert(JSON.stringify(model));
	var data="[]".toJson();	
	//data.Convert=true;	
	tbody.find("tr").each(function(i,el){
		var obj=nodeToJson(el);
		data.append(obj);
	});
	model["eformdata_" + ModelID]=data;	
	input.value=model.toJson();
	
	
	//addPack($(table));
}
//兼容自动上传文件
function autoupload_check(obj)
{
	
	var allowexts=obj.getAttribute("allowexts") || "";
	var preventexts=obj.getAttribute("preventexts") || "";
	if(allowexts.length>0){allowexts+=".";}
	if(preventexts.length>0){preventexts+=".";}
	if (obj.files)
	{		
		for(var i=0;i<obj.files.length;i++)
        {
			var ext=obj.files[i].name.fileExtension();
			if(ext.length==0||ext.indexOf(".")!=0)
			{
				 obj.value = "";
                 top.layer.msg("文件类型错误!");
				 return false;
			}
			if(allowexts.length>0)
			{
				if(allowexts.toLowerCase().indexOf(ext + ".") == -1)
                {
					obj.value = "";
                 	//layer.msg("文件类型" +  ext + "被禁止上传!");
					top.layer.msg("只允许上传" + allowexts.substring(0,allowexts.length-1) + "类型的文件!");
				 	return false;
				}
			}
			else
			{
				if(preventexts.toLowerCase().indexOf(ext + ".") > -1)
                {
					obj.value = "";
                 	top.layer.msg("文件类型" +  ext + "被禁止上传!");
				 	return false;
				}
			}
		}
	}
	else
	{
		var ext=obj.value.fileExtension();
		if(ext.length==0||ext.indexOf(".")!=0)
		{
			obj.value = "";
            top.layer.msg("文件类型错误!");
			return false;
		}
		if(allowexts.length>0)
		{
			if(allowexts.toLowerCase().indexOf(ext + ".") == -1)
            {
				obj.value = "";
                //layer.msg("文件类型" +  ext + "被禁止上传!");
				top.layer.msg("只允许上传" + allowexts.substring(0,allowexts.length-1) + "类型的文件!");
				return false;
			}
		}
		else
		{
			if(preventexts.toLowerCase().indexOf(ext + ".") > -1)
            {
				obj.value = "";
                top.layer.msg("文件类型" +  ext + "被禁止上传!");
				return false;
			}
		}
    }
	if(typeof(autoPost)=="function" && obj.name.toLowerCase()=="imgfile")
	{
		Form1.submit();
	}
	//alert(obj.name);
	return true;	
}
function autoupload_change(obj)
{
	var attach=obj.value;
	if(attach == undefined || attach == "")
	{
		//alert("请选择文件");
        return;
    }
	var result=autoupload_check(obj);
	if(!result){return;}
	
	var posturl=obj.getAttribute("posturl");
	var url = posturl == null ? virtualPath + "Plugins/ProUpload.aspx?type=file" : posturl;
	if(url=="auto")
	{
		url=document.location.href.addquerystring("act","upload");
		url=url.addquerystring("ajax","true");
	}
	//if($(obj).parent().attr("MaxWidth") && $(obj).parent().attr("MaxWidth").length>1) {url+="&PictureMaxWidth=" + $(obj).parent().attr("MaxWidth");}
	var maxWidth=$(obj).parent().attr("MaxWidth");
	if(maxWidth && maxWidth.length>1){url+="&PictureMaxWidth=" + maxWidth;}	
	if (obj.files)
	{
		autopostfile(obj,url);
    }
	else
	{
	   	autopostfile_ie(obj,url);
    }
}
function autopostfile(obj,url)
{
	var formData = new FormData();
	for(var i=0;i<obj.files.length;i++)
	{
		formData.append('files', obj.files[i], obj.files[i].name);
	}
	$.ajax({
		type: "post", 
		async: false,
		data:formData,
        url:url,
        dataType: "json",
		contentType: false,
		cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        success: function (data)
		{
			//layer.msg(data.message);
			obj.value="";
			var callback=$(obj).attr("callback");
			if(callback)
			{
				//eval("if(typeof(" + callback + ")=='function'){" + callback + "(" + data.files +  ");}");
				if(data.files)
				{
					eval(callback + "(data.files);");
				}
				else
				{
					eval(callback + "(data);");
				}
			}			
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {}
    });
}
function autopostfile_ie(obj,url)
{
	$.ajaxFileUpload ({
		type: "post",
		async: false,
		url: url, //用于文件上传的服务器端请求地址 
		secureuri: false, //一般设置为false 
		fileElementId: $(obj).attr("id"), //文件上传空间的id属性  <input type="file" id="file" name="file" /> 
		dataType: "json", //返回值类型 一般设置为json 
		success: function (data, status)  //服务器成功响应处理函数
        {
			layer.msg(data.message);
			obj.value="";
			var callback=$(obj).attr("callback");
			if(callback)
			{
				//eval("if(typeof(" + callback + ")=='function'){" + callback + "(" + data.files +  ");}");
				if(data.files)
				{
					eval(callback + "(data.files);");
				}
				else
				{
					eval(callback + "(data);");
				}
			}
		}, 
		error: function (data, status, e)//服务器响应失败处理函数
        {
			//alert("error");
			//alert(e); 
		} 
	});	
	//alert(2);
}
//删除临时文件
function removefile(file)
{
	if(file.toLowerCase().indexOf("upload/")>0){file=file.substring(file.toLowerCase().indexOf("upload/"));}
	var url=virtualPath + "Plugins/ProUpload.aspx?act=del&file=" + file;
	$.get({url:url,async:false});
}
//读取excel文件返回json
function exceltojson(file)
{
	if(file.toLowerCase().indexOf("upload/")>0){file=file.substring(file.toLowerCase().indexOf("upload/"));}
	var url= virtualPath + "Plugins/ExcelToJson.aspx?path=" + file;
	var obj=[];
	$.ajax({
			type: "get",
			async: false,
			url: url,
			dataType: "json",
			success: function(result)
			{
				obj=result.data;
			}
	});
	return obj;
}
function addrow(obj,modelid)
{
	var table=$("#eformlist_" + modelid);
	if(!table){return null;}
	var tbody=table.find("tbody");
	var tfoot=table.find("tfoot");
	if(tfoot.length>0)
	{
		var tr=tfoot[0].getElementsByTagName("tr")[0].cloneNode(true);
		var _max=tbody.children().length + 1;
		$(tr).find("input[type='radio']").each(function(i,el){
			$(this).attr("name","row_" + _max + "_" + $(this).attr("name"));	 
		});	
		tbody[0].appendChild(tr);
		tbody.find("tr:visible").each(function(i,el){
			//$(this).find("td:eq(1)").html(i+1);
			var tdnum=$(this).find("td:eq(1)");
			if(tdnum.attr("class")=="num")
			{
				tdnum.html(i+1);
			}
		});
		var count=getobj("count_" + modelid);
		if(count)
		{
			count.value=tbody.find("tr:visible").length;
		}
		return tr;
	}
	return null;
}
function excel_SelectDataN(ModelID,singleFields)
{
	var fieldstr= singleFields || "";
	var fieldarr= [];
	if(fieldstr.length>0){fieldarr=fieldstr.split(",");}

	
	var src=getEventObject();
	//alert(src.tagName);
	if(src.tagName!="INPUT" && src.tagName!="TD" && src.tagName!="DIV" && src.tagName!="P" && src.tagName!="A" && src.tagName!="LABEL"){return;}
	if(src.tagName=="INPUT" && src.name.toLowerCase()!="fillselitem"){return;}
	
	//return;
	
	
	//var tb=$("#eformlist_" + ModelID,parent.document);
	var tb;
	if (parent.form_area)
    {
		tb=$("#eformlist_" + ModelID,parent.form_area);
	}
	else
	{
		tb=$("#eformlist_" + ModelID,parent.document);
	}
	
	var chk=null;
	if(src.tagName=="A")
	{
		var dl=$(src).parents("dl:first");
		chk=dl.find("input[name='fillselitem']")[0];
		chk.checked=!chk.checked;
	}	
	else if(src.tagName=="INPUT")
	{
		chk=src;
	}
	else
	{		
		chk=$(src).parents("tr:first").find("input[name='fillselitem']")[0];
		chk.checked=!chk.checked;
	}	
	var values="";
	if(src.tagName=="A")
	{
		values = $(src).attr("jsondata");
	}
	else
	{
		var _tr=$(chk).parents("tr:first")[0];
		values = $(_tr).attr("jsondata");
	}

	var json=decode64(values);
	var data=JSON.parse(json);
	//alert(json);
	
	if(chk.checked) //add
	{
		//alert(parent.fillparent);
		var trs = $(parent.document).find(".excelTable > tbody > tr:hidden");
		var hastr = null;
		//alert(trs.length);
		for(var x = 0; x < trs.length; x++)
		{
			var tr = trs[x];
			var allcount = 0;
			var hascount = 0;
			$.each(data, function(idx, item)
			{
				var name = item["id"];
				if(fieldarr.length > 0 && fieldarr.indexOf(name)==-1){return true;}
				var value = item["value"];
				value = value.replace(/'/gi, "\\'");
				//alert(value);
				if ($(tr).find("[postname='" + name + "']").length == 0) { return true; }
				allcount++;				
				var type = $(tr).find("[postname='" + name + "']").attr("type").toLowerCase();
				if (type == "radio")
				{
					if($(tr).find("[postname='" + name + "'][value='" + value + "']:checked").length > 0)
					{
						hascount++;
					}
				}
				else if(type == "checkbox")
				{
					var tvalue = "," + value + ",";
					var checkboxs = $(tr).find("[postname='" + name + "']:checked");
				    checkboxs.each(function () {
				        tvalue = tvalue.replace("," + $(this).val() + ",", ",");
				    });
					tvalue = tvalue.replace(/,/g, "");
					if(tvalue.length==0)
					{
						hascount++;
					}
				}
				else				
				{
					if($(tr).find("[postname='" + name + "'][value='" + value + "']").length > 0)
					{
						hascount++;
					}
				}
			});
			if (allcount == hascount && allcount > 0) {hastr=tr;}
		}
		//alert(hastr);
		if(hastr)
		{			
			$(hastr).find("[name='Delete']").val("false");
			$(hastr).show();
			var tbody=tb.find("tbody");			
			if(tb.find("thead").text().indexOf("序号")>-1)
			{
				tbody.find("tr:visible").each(function(i,el){
					$(this).find("td:eq(1)").html(i+1);		
				});
			}
		}
		else
		{

			var obj=tb.find("thead td a:eq(0)");
			parent.excel_add(obj,ModelID);
			var tr=tb.find("tbody tr:last");
			parent.fillparent=tr[0];
			FillData2(values,true);
			parent.excel_pack(ModelID);
		}
		//回调函数-删除
		if(typeof(parent.submodel_onChange)=="function")
		{
			var table=obj.parents("table:first");
			var tbody=table.find("tbody");
			var list_trs=tbody.find("tr:visible");
			parent.submodel_onChange(ModelID,list_trs,tbody);
		}
	}
	else
	{
		//alert(JSON.stringify(data));
		var trs = $(parent.document).find(".excelTable > tbody > tr:visible");
		for(var x = 0; x < trs.length; x++)
		{
			var tr = trs[x];
			var has = true;
			$.each(data, function(idx, item)
			{
				var name = item["id"];
				if(fieldarr.length > 0 && fieldarr.indexOf(name)==-1){return true;}
				var value = item["value"];
				value = value.replace(/'/gi, "\\'");				
				var type = $(tr).find("[postname='" + name + "']").attr("type").toLowerCase();
				if (type == "radio")
				{
					if($(tr).find("[postname='" + name + "'][value='" + value + "']:checked").length == 0)
					{
						has = false;
					}
				}
				else if(type == "checkbox")
				{
					var tvalue = "," + value + ",";
					var checkboxs = $(tr).find("[postname='" + name + "']:checked");
				    checkboxs.each(function () {
				        tvalue = tvalue.replace("," + $(this).val() + ",", ",");
				    });
					tvalue = tvalue.replace(/,/g, "");
					if(tvalue.length>0)
					{
						has = false;
					}
					//alert(value);
				}
				else				
				{
					if($(tr).find("[postname='" + name + "'][value='" + value + "']").length == 0)
					{
						has = false;
					}
				}
			});
			if(has)
			{
				var obj= $(tr).find(".btndel")[0];
				parent.excel_delete(obj,ModelID,true);
				break;
			}	
		}	
	}
}
function excel_SelectData(ModelID,values)
{
	var src=getEventObject();
	if(src.tagName!="INPUT" && src.tagName!="TD"){return;}
	if(src.tagName=="INPUT" && src.name.toLowerCase()!="fillselitem"){return;}
	//var chk=src.tagName=="INPUT" ? src : $(src).parents("tr:first").find("input[name='fillselitem']")[0];
	var tb=$("#eformlist_" + ModelID,parent.document);
	var chk=null;
	if(src.tagName=="INPUT")
	{
		chk=src;
	}
	else
	{
		chk=$(src).parents("tr:first").find("input[name='fillselitem']")[0];
		chk.checked=!chk.checked;
	}
	if(chk.checked) //add
	{
		//批量添加和单个添加混乱		
		//alert(parent.fillparent);
		var obj=tb.find("thead td a:eq(0)");
		parent.excel_add(obj,ModelID);
		var tr=tb.find("tbody tr:last");
		parent.fillparent=tr[0];
		
		//parent.FillData(values,true);
		FillData(values,true);
		parent.excel_pack(ModelID);
		
	}
	else
	{
		var _tr=$(chk).parents("tr:first")[0];
		var values = $(_tr).attr("fieldarrs");
		var arrs = values.split("~");		
		var trs = $(parent.document).find(".excelTable > tbody > tr:visible");
		var index=-1;
		for(var x = 0; x < trs.length; x++)
		{
			//alert(x);
            var tr = trs[x];
			var has = true;
			for(var i = 0; i < arrs.length; i++)
			{
				var arr = arrs[i].split("=");
                if (arr.length < 2) { continue; }
                var name = arr[0];
				var value = arr[1].decode().replace(/%u003d/gi, "=");
				value = value.replace(/'/gi, "\\'");
				if($(tr).find("[postname='" + name + "'][value='" + value + "']").length == 0)
				{
					has = false;
				}
			}			
			if(has)
			{
				//index=$(tr).index();
				var obj= $(tr).find(".btndel")[0];
				parent.excel_delete(obj,ModelID,true);
				break;
			}			
		}
		//alert("index=" + index);
		if(index>-1)
		{
			//var obj= $(parent.document).find(".excelTable tbody tr:eq(" + index + ") .btndel")[0];
			//parent.excel_delete(obj,ModelID,true);
		}
	}
	//parent.document.title=src.tagName + "::" + ModelID;	
}
//回填到表单
var fillparent=null;
var fillmodelid=null;
function FillData2(values,cancelclose)//values=json+base
{
	var json=decode64(values);
	//alert(json);
	var data=JSON.parse(json);
	$.each(data, function(idx, item)
	{

		//alert(parent.fillparent.tagName);
		var objs= parent.fillparent.tagName == "TR" ||  parent.fillparent.tagName == "DD" ? $(parent.fillparent).find("[postname='" + this["id"] + "']") : $(parent.fillparent).find("[name='" + item["id"] + "']");
		//alert(objs + "::" + item["value"]);
		if(objs)
		{
			//alert(item["id"] + "::" + objs.length);
			if(objs.length==1)
			{
				objs[0].value=item["value"];
				objs.prop("value", item["value"]);
				objs.attr("value", item["value"]);
				//回填后异步加载
				if(typeof(objs[0].onchange)=="function")
				{
					objs.trigger("change");
				}
				var etype=objs[0].getAttribute("etype");
				//alert(etype);
				switch(etype)
				{
					case "date":
						objs[0].value=item["text"];
						break;
					case "departmentselect":
						//alert(item["text"]);
						var box=$(parent.fillparent).find("#" + item["id"] + "_box");
						$(parent.fillparent).find("[postname='" + item["id"] + "']").val(item["value"]);
						$(parent.fillparent).find("[postname='" + item["id"] + "_text']").val(item["text"]);						
						if(box.find(".useritem").length==1)
						{
							box.find(".useritem p").html(item["text"]);
						}
						else
						{
							var html='<a class="useritem" href="javascript:;">';
							//html += '<p>' + item["text"] + '</p><img src="../images/none.gif" onclick="multipleuser_delete(this);"></a>';//回填不给删除
							html += '<p>' + item["text"] + '</p></a>';
							if(box.find(".useritem_open").length>0)
							{
								box.find(".useritem_open").before(html);
							}
							else
							{
								box.append(html);
							}
						}
						break;
					case "singleuser":
						//alert("2" + etype);
						var box=$(parent.fillparent).find("#" + item["id"] + "_box");
						$(parent.fillparent).find("[postname='" + item["id"] + "']").val(item["value"]);
						$(parent.fillparent).find("[postname='" + item["id"] + "_text']").val(item["text"]);						
						if(box.find(".useritem").length==1)
						{
							box.find(".useritem p").html(item["text"]);
						}
						else
						{
							var html='<a class="useritem" href="javascript:;">';
							//html += '<p>' + item["text"] + '</p><img src="../images/none.gif" onclick="multipleuser_delete(this);"></a>';//回填不给删除
							html += '<p>' + item["text"] + '</p></a>';
							if(box.find(".useritem_open").length>0)
							{
								box.find(".useritem_open").before(html);
							}
							else
							{
								box.append(html);
							}
						}
						//alert(item["id"] + "::" + item["text"] + "::" + item["value"]);
						break;
					case "label":
						$(parent.fillparent).find("#" + item["id"] + "_box span:eq(0)").text(item["text"]);
						break;
					case "html":
						try{parent.KE.html(item["id"],objs[0].value);}catch(e){}
						try{parent.KE.setFullHtml(item["id"],objs[0].value);}catch(e){}
						break;
				}
				/*
				if(etype=="label")
				{	
					$(parent.fillparent).find("#" + item["id"] + "_box span:eq(0)").text(item["text"]);
				}
				if(etype == "html")
				{
					try{parent.KE.html(item["id"],objs[0].value);}catch(e){}
					try{parent.KE.setFullHtml(item["id"],objs[0].value);}catch(e){}
				}
				*/
			}
			else
			{
				var _vs="," + item["value"] + ",";
				for(var j=0;j < objs.length;j++)
				{
					if(_vs.indexOf("," + objs[j].value + ",")>-1)
					{
						objs[j].checked=true;
					}
					else
					{
						objs[j].checked=false;
					}
				}
			}
		}
	});
	if(typeof(parent.FillData_finish)=="function"){parent.FillData_finish(parent.fillparent,parent.fillmodelid);}
	if(!cancelclose && parent.arrLayerIndex.length>0)
	{
		parent.layer.close(parent.arrLayerIndex.pop());
	}
}
//获取同级表单元素的共同上级。
function getFillParent(elem)
{
	var obj=$(elem).parents("table:first");
	var cls=obj.attr("class").toLowerCase();
	if(cls=="edataview")
	{
		return obj[0];
	}
	else
	{
		return $(elem).parents("tr:first")[0];
	}
}
function FillData(values,cancelclose)
{
	//.replace("m&#179;","m³")
	//alert(parent.arrLayerIndex.length + "::" + str);
	//alert(window.opener);
	var arr=values.split("~");
	//alert(parent.fillparent.tagName + "::" + arr.length);
	//alert($(parent.fillparent).find("[name='Me2_F16']"));
	//alert(parent.fillparent.getElementsByName);		
	//alert($("[name='Me2_F16']",parent.fillparent).val());	
	//return;
	//alert(parent.fillparent.tagName);
	for(var i=0;i<arr.length;i++)
	{

		var objvalue=arr[i].split("=");
		if(objvalue.length<2){continue;}
		//if(objvalue[1].length==0){continue;}
		//var objs=parent.document.getElementsByName(objvalue[0]);
		//alert(objvalue[0]);
		var objs= parent.fillparent.tagName == "TR" ? $(parent.fillparent).find("[postname='" + objvalue[0] + "']") : $(parent.fillparent).find("[name='" + objvalue[0] + "']");
		//return;
		//alert(objs);
		if(objs)
		{
			//document.title+=":" + objvalue[1].decode();
			 //alert(objvalue[1].decode() + "::" + objs.length);
			if(objs.length==1)
			{
				var tmp=objvalue[1].decode().replace(/%u003d/gi,"=");
				
				objs[0].value=tmp;
				objs.prop("value",tmp);
				objs.attr("value",tmp);
				//回填后异步加载
				if(typeof(objs[0].onchange)=="function")
				{
					objs.trigger("change");
				}
				var etype=objs[0].getAttribute("etype");
				if(etype == "html")
				{
					try{parent.KE.html(objvalue[0],objs[0].value);}catch(e){}
					try{parent.KE.setFullHtml(objvalue[0],objs[0].value);}catch(e){}
				}
				
			}
			else
			{
				var _vs="," + objvalue[1].decode() + ",";
				for(var j=0;j < objs.length;j++)
				{
					if(_vs.indexOf("," + objs[j].value + ",")>-1)
					{
						objs[j].checked=true;
					}
					else
					{
						objs[j].checked=false;
					}
				}
			}
		}
	}
	
	if(!cancelclose && parent.arrLayerIndex.length>0)
	{
		parent.layer.close(parent.arrLayerIndex.pop());
	}
}
//ajax打开其他模块添加数据
function ajaxOpenModel(url,title,width,height)
{
	if(!width){width="80%";}
	if(!height){height="80%";}
	var _reload=true;
	var idx=parent.layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: title,
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	  //area : ['800px' , '520px'],
	  //area: [width,height],
	  area:IsMobile() ? ['95%','95%'] : [width,height],    
      //content: [url,'no'],
	  scrollbar: true, 
	  content: [url],
	  success: function(layero, index){
		  parent.arrLayerIndex.push(index);
		  //alert(index);
		  //alert(layero);
	  	  //window[layero.find('iframe')[0]['name']].focus();
	  	  var iframeWin = window[layero.find('iframe')[0]['name']];
		  //alert(iframeWin.document.location.href);
	  	  var act=iframeWin.document.location.href.getquerystring("act");
		  //alert(act);
		  if(act=="view"){_reload=false;}
	  },
	  cancel: function(index, layero){parent.arrLayerIndex.pop();},
	  end : function(index){
		  	if(uploadTempFile.length>0)
			{
				removefile(uploadTempFile);
				uploadTempFile="";
			}
		  if(_reload)
		  {
			  //document.location.assign(document.location.href);
			  reloadDoc();
		  }
		  parent.arrLayerIndex.pop();		  
	  }
    });
}
function OpenFillSelectDlg(modelID,title,width,height,area,fmodelID,clientMode)
{
	var src=getEventObject();
	form_area=$(src).parents("table:first").parent();	
	var url= virtualPath + "Plugins/FillSelectData.aspx?modelid=" + modelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "");
	//if(query.length>0){url+=query;}
	if(document.location.href.getquerystring("debug")) {url+="&debug=1";}
	if(area){url+="&area=" + area;}
	var query="";
	if(typeof(OpenFillSelectDlg_before)=="function")
	{
		var _back=OpenFillSelectDlg_before(modelID);
		if(typeof(_back)=="object")
		{
			//if(!_back.result){return;}
			query=_back.query.replace("?","");
			if(query.length>0)
			{
				//if(query.indexOf("&")!=0){query="&" + query;}			
			}
			var arr=query.split("&");
			for(var x=0;x<arr.length;x++)
			{
				var arr2=arr[x].split("=");
				if(arr2.length==2)
				{
					url=url.addquerystring(arr2[0],arr2[1]);
				}
			}	
		}
	}
	
	if(fmodelID){url+="&fmodelID=" + fmodelID;}
	if(clientMode){url+="&clientMode=" + clientMode;}
	url+= "&t=" + now();
	//alert(url);
	//return;
	
	var idx=layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: title,
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	    //area : ['800px' , '520px'],
	  //area: [width,height],
	  area:IsMobile() ? ['95%','95%'] : [width,height],    
      content: url,
	  success: function(layero, index){arrLayerIndex.push(index);
	  window[layero.find('iframe')[0]['name']].focus();
	  //var iframeWin = window[layero.find('iframe')[0]['name']];
	  },
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){
		  if(typeof(OpenFillSelectDlg_finsh)=="function"){OpenFillSelectDlg_finsh(modelID);}
		  if(typeof(OpenFillSelectDlg_finish)=="function"){OpenFillSelectDlg_finish(modelID);}
		  arrLayerIndex.pop();
	  }
    });
	//alert(idx);
}
//搜索回填窗口
function OpenSFillDlg(modelID,title,width,height,area,ptagname,fmodelID,clientMode,obj)
{
	var src=getEventObject();
	if(obj){src=obj;}
	fillparent=$(src).parents(ptagname+":first")[0];
	var url= virtualPath + "Plugins/FillDataS.aspx?modelid=" + modelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "");
	var query="";
	if(typeof(OpenSFillDlg_before)=="function")
	{
		var _back=OpenSFillDlg_before(modelID);//function OpenSFillDlg_before(modelid) {return {result:true,query:"s3=3"};};
		if(typeof(_back)=="object")
		{
			//if(!_back.result){return;}
			query=_back.query.replace("?","");
			var arr=query.split("&");
			for(var x=0;x<arr.length;x++)
			{
				var arr2=arr[x].split("=");
				if(arr2.length==2)
				{
					url=url.addquerystring(arr2[0],arr2[1]);
				}
			}
		}
	}
	if(document.location.href.getquerystring("debug")) {url+="&debug=1";}
	if(area){url+="&area=" + area;}
	if(fmodelID){url+="&fmodelID=" + fmodelID;}
	if(clientMode){url+="&clientMode=" + clientMode;}
	url+= "&t=" + now();
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: title,
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	    //area : ['800px' , '520px'],
	  //area: [width,height],
	  area:IsMobile() ? ['95%','95%'] : [width,height],    
      content: url,
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){
		  arrLayerIndex.pop();
	  }
    });
};
//表单回填窗口
function OpenFillDlg(modelID,title,width,height,area,ptagname,fmodelID,clientMode,obj)
{	
	var src=getEventObject();
	if(obj){src=obj;}
	fillparent=$(src).parents(ptagname+":first")[0];
	fillmodelid=modelID;
	//alert($(fillparent).html());
	//return;
	var url= virtualPath + "Plugins/FillData.aspx?modelid=" + modelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "");
	//if(query.length>0){url+=query;}
	var query="";
	if(typeof(OpenFillDlg_before)=="function")
	{
		var _back=OpenFillDlg_before(modelID);//function OpenFillDlg_before(modelid) {return {result:true,query:"s3=3"};};
		//if(_back==null) alert(66);
		//alert(_back);
		if(typeof(_back)=="object")
		{
			//if(!_back.result){return;}
			query=_back.query.replace("?","");
			if(query.length>0)
			{
				//if(query.indexOf("&")!=0){query="&" + query;}
			}
			var arr=query.split("&");
			for(var x=0;x<arr.length;x++)
			{
				var arr2=arr[x].split("=");
				if(arr2.length==2)
				{
					url=url.addquerystring(arr2[0],arr2[1]);
				}
			}
		}
	}
	if(document.location.href.getquerystring("debug")) {url+="&debug=1";}
	if(area){url+="&area=" + area;}
	if(fmodelID){url+="&fmodelID=" + fmodelID;}
	if(clientMode){url+="&clientMode=" + clientMode;}
	url+= "&t=" + now();
	//alert(url);
	layer.open({
      type: 2,
	  skin: 'layui-layer-rim', //加上边框
      title: title,
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
	    //area : ['800px' , '520px'],
	  //area: [width,height],
	  area:IsMobile() ? ['95%','95%'] : [width,height],    
      content: url,
	  success: function(layero, index){arrLayerIndex.push(index);},
	  cancel: function(index, layero){arrLayerIndex.pop();},
	  end : function(index){
		  var frm=$(src).parents("form:first");
		  if(frm)
		  {
			  frm.find('[checkvalue="true"]').each(function(i,el){
				 el.onblur();
				 el.focus();
				 el.blur();				 
			  });
		  }
		  if(typeof(OpenFillDlg_finsh)=="function"){OpenFillDlg_finsh(modelID);}
		  if(typeof(OpenFillDlg_finish)=="function"){OpenFillDlg_finish(modelID);}
		  arrLayerIndex.pop();
	  }
    });

	/*
	$.ajax({
			type: 'get',
			url: url,	
			dataType: "html",
			success: function(data)
			{
				alert(data);
			}
		});
	*/
}
function bindzoomImage(obj)
{
	var img=obj.getElementsByTagName("img")[0];
	var layer = $(img).parent().parent().parent();
	var content = $(img).parent().parent();
	var pdiv= $(img).parent();
	var nwidth=0;
	var nheight=0;
			
	if (typeof obj.onmousewheel == "object")
	{
		
	    obj.onmousewheel = function(e)
		{
			var e=e||event,v=e.wheelDelta||e.detail;
			if(v>0)
			{				
				nwidth=$(img).width()*1.05;
				nheight=$(img).height()*1.05;		
			}
			else
			{				
				nwidth=$(img).width()*0.95;
				nheight=$(img).height()*0.95;	
			}
			layer.width(nwidth+20).height(nheight+20).css("top",parseInt(($(document.body).height()-nheight-20)/2) + "px").css("left",parseInt(($(document.body).width()-nwidth-20)/2) + "px");
			content.width(nwidth+20).height(nheight+20);
			pdiv.width(nwidth).height(nheight);
			$(img).width(nwidth).height(nheight);
		};
	}
	else
	{
		obj.addEventListener("DOMMouseScroll",function(e){
			var e=e||event,v=e.wheelDelta||e.detail; 			
			if(v>0)
			{
				nwidth=$(img).width()*0.95;
				nheight=$(img).height()*0.95;
			}
			else
			{
				nwidth=$(img).width()*1.05;
				nheight=$(img).height()*1.05;
			}
			layer.width(nwidth+20).height(nheight+20).css("top",parseInt(($(document.body).height()-nheight-20)/2) + "px").css("left",parseInt(($(document.body).width()-nwidth-20)/2) + "px");
			content.width(nwidth+20).height(nheight+20);
			pdiv.width(nwidth).height(nheight);
			$(img).width(nwidth).height(nheight);
		},false);
	}
	
	setTimeout(function(){
		//alert($(img).height());
		nwidth=$(img).width();
		nheight=$(img).height();
		layer.width(nwidth+20).height(nheight+20).css("top",parseInt(($(document.body).height()-nheight-20)/2) + "px").css("left",parseInt(($(document.body).width()-nwidth-20)/2) + "px");
			content.height(nheight+20);
			pdiv.height(nheight);
		
	},50);
}

function viewImage2(src,w,h)
{
	
	var ieVer = 0;
	var isIE =  window.navigator.userAgent.indexOf("compatible") > -1 &&  window.navigator.userAgent.indexOf("MSIE") > -1;
	if(isIE)
	{
		var reg = new RegExp("MSIE (\\d+\\.\\d+);");
		reg.test(window.navigator.userAgent);
		ieVer = parseFloat(RegExp["$1"]);
	}
	var maxw= 1000;//screen.width - 200;
	if(w>maxw)
	{
		var bl=w/maxw;
		w=maxw;
		h=parseInt(h/bl);
	}

	var html='<div id="viewImagediv" style="padding:10px;overflow:hidden;position:relative;width:' + w + 'px;height:' + h + 'px;"><img onclick="layer.close(layer.index);" id="viewimage" src="' + src + '" width="'+ w +'"></div>';	
	if(IsMobile())
	{

		html='<div id="viewImagediv" style="padding:10px;ov4erflow:hidden;position:relative;width:90%;height:90%;max-width:90%;max-height:90%;text-align:center;"><img onclick="layer.close(layer.index);" id="viewimage" src="' + src + '" style="min-width:50%;min-height:50%;max-width:95%;max-height:95%;display:inline-block;"></div>';	
	}
	layer.open({
  	type: 1
	,area:IsMobile() ? ['100%','100%'] : [(w+20) + 'px',(h+20) + 'px']
	//,shade: 0.2 //透明度
  	,title: false //不显示标题
	,moveOut:true
	,closeBtn: 0
	,scrollbar: false
	,anim: (isIE && ieVer < 9 ? -1 : 4) //0-6的动画形式，-1不开启 IE9以下不支持动画
	,shadeClose: true //开启遮罩关闭
	//,content:'<div style="padding:10px;"><img src="' + src + '" width="'+ w +'"></div'
  	,content:html
	,success: function(layero, index)
	{
		var obj=getobj("viewImagediv");
		bindzoomImage(obj);
		
		setTimeout(function(){ document.focus();},1000);
		arrLayerIndex.push(index);
  	}
	,cancel: function(index, layero){arrLayerIndex.pop();}
	,end : function(index){arrLayerIndex.pop();}
	
	});
}
//新加
function showimg(url)
    {
        layer.open({
            type: 1,
            area: ['90%','90%'],
            shadeClose: true, //开启遮罩关闭
            title: false, //不显示标题
			moveOut:true,
            content: '<img onclick="layer.close(layer.index);" src="' + url + '" style="max-width:100%;max-height:100%;" />', 
            cancel: function () {
            }
        });
    }
function viewImage(src,w,h)
{
	top.viewFile(src,'90%','90%');
	/*
	 return;
	 var img = new Image(); //图片预加载
	 img.src=src;
	 if(img.complete)
	 {
		 show_Image(img,src);
     }
	 else
	 {
		 img.onload = function()
		 {
			 show_Image(img,src);
		 };
     }	
	 */
}
function show_Image(img,url)
{
	var ieVer = 0;
	var isIE =  window.navigator.userAgent.indexOf("compatible") > -1 &&  window.navigator.userAgent.indexOf("MSIE") > -1;
	if(isIE)
	{
		var reg = new RegExp("MSIE (\\d+\\.\\d+);");
		reg.test(window.navigator.userAgent);
		ieVer = parseFloat(RegExp["$1"]);
	}

         layer.open({
            type: 1,
			title: false, //不显示标题
			closeBtn: 0,
			moveOut:true,
			scrollbar: false,
			shadeClose: true, //开启遮罩关闭
			anim: (isIE && ieVer < 9 ? -1 : 4), //0-6的动画形式，-1不开启 IE9以下不支持动画
            //skin: 'layui-layer-rim', //加上边框
			skin: 'layui-layer-nobg', //没有背景色
           // area: [img.width + 'px', img.height + 'px'], //宽高
		    area: ['auto'],
		 
            //content: '<div style="font-size:0px;text-align: center;overflow:hidden;"><img onclick="layer.close(layer.index);" src='+url+' style="max-width:90%;max-height:90%;" /></div>'
			content: '<div style="font-size:0px;text-align: center;overflow:hidden;"><img onclick="layer.close(layer.index);" src='+url+' style="max-width:100%;max-height:100%;" /></div>'
         });

}
function viewImage1(src,w,h)
{
	
	var ieVer = 0;
	var isIE =  window.navigator.userAgent.indexOf("compatible") > -1 &&  window.navigator.userAgent.indexOf("MSIE") > -1;
	if(isIE)
	{
		var reg = new RegExp("MSIE (\\d+\\.\\d+);");
		reg.test(window.navigator.userAgent);
		ieVer = parseFloat(RegExp["$1"]);
	}
	var maxw= 1000;//screen.width - 200;
	if(w>maxw)
	{
		var bl=w/maxw;
		w=maxw;
		h=parseInt(h/bl);
	}
	layer.open({
  	type: 1
	//,area:[(w+20) + 'px',(h+20) + 'px']
	//,area: ['90%','90%']
	//,shade: 0.2 //透明度
	,area: ['auto']
  	,title: false //不显示标题
	,moveOut:true
	,skin: 'layui-layer-nobg' //没有背景色
	,closeBtn: 0
	,anim: (isIE && ieVer < 9 ? -1 : 4) //0-6的动画形式，-1不开启 IE9以下不支持动画
	,shadeClose: true //开启遮罩关闭
  	//,content:'<div style="padding:10px;font-size:0px;"><img src="' + src + '" style="display:block;max-width:90%;max-height:90%;"></div>'
	,content:'<img onclick="layer.close(layer.index);" src="' + src + '" style="display:block;max-width:90%;max-height:90%;">'
	,success: function(layero, index)
	{
		setTimeout(function(){ document.focus();},1000);
		arrLayerIndex.push(index);
  	}
	,cancel: function(index, layero){arrLayerIndex.pop();}
	,end : function(index){arrLayerIndex.pop();}
	
	});
}

//新增加
function fill_checkbox(viewid,pid,objid)
{
	
	var url= virtualPath + "Plugins/getData.ashx?viewid=" + viewid + "&pid=" + pid;
	var box=$("#"+ objid + "_box");
	box.html("");
	
	$.ajax({
	type: "GET",
	async: false,
	url: url,
	dataType: "json",
	success: function(data)
	{
		//alert(JSON.stringify(data));

		 $.each(data, function(i,v)
		 {
			 //alert(i + "::" + v["value"] + "::" + this["text"]);
			box.append('<input etype="checkbox" type="checkbox" name="' + objid + '" id="' + objid + '_' + (i+1) + '" value="'+ this["value"] +'" text="'+ this["text"] +'"><label for="' + objid + '_' + (i+1) + '">'+ this["text"] +'</label>'); 
		 });

	}
	});
	
}
//加载数据到下拉框
function FillSelect(objId,Prars,Pid)
{	
	var url= virtualPath + "Plugins/getData.ashx?Pid=" + Pid;	
	if(typeof(AppItem)=="string" && AppItem.length > 0)
	{
		url=url.addquerystring("AppItem",AppItem);
	}
	else
	{
		if(typeof(ModelID)=="string" && ModelID.length > 0){url=url.addquerystring("ModelID",ModelID);}	
	}
	if(Prars.indexOf("&")!=0){url += "&";}
	url += Prars;	
	url += "&t=" + now(),

	$.ajax({
	type: "GET",
	async: false,
	url: url,
	dataType: "json",
	success: function(data)
	{
		//alert(JSON.stringify(data));
		$("#" + objId).get(0).length=1;
		if(!data){return;}
		//$("#" + ObjID).empty();
		 $.each(data, function()
		 {
			$("#" + objId).append('<option value="' + this["value"] + '">' + this["text"] + '</option>'); 
		 });
	}
	});
}
function form_view(obj,ModelID,title,width,height,ID) //自动模块
{
	//if(!ID){ID=obj.getAttribute("eRowID");}
	if(width.toLowerCase().indexOf("px")==-1 && width.toLowerCase().indexOf("%")==-1){width+="px";}
	if(height.toLowerCase().indexOf("px")==-1 && height.toLowerCase().indexOf("%")==-1){height+="px";}
	var tr=null;
	if(obj.tagName=="TR" && obj.getAttribute("eRowID")!=null)
	{
		tr=obj;
	}
	else
	{
		tr=getParent(obj.parentNode,"tr");
		if(tr.getAttribute("eRowID")==null){tr=getParent(tr.parentNode,"tr"); }
	}
	if(tr.getAttribute("eRowID")==null){return;}
	if(!ID){ID=tr.getAttribute("eRowID");}
	
	
	//子模块加载数据，不能有AppItem,AppItem是上级的编号
	//var url="?modelid=" + ModelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "") + "&act=viewsub&id=" + ID;
	//var url="?modelid=" + ModelID + "&act=viewsub&id=" + ID;
	var url="model.aspx?modelid=" + ModelID + "&act=viewsub&id=" + ID;
	
	var logid=document.location.href.getquerystring("logid");
	if(logid.length>0) url+= "&logid=" + logid; 
	url+= "&t=" + now();
	var html=PostURL(url);
	layer.open({
  	type: 1 //此处以iframe举例
  	,title: title
	//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
	,shadeClose: true //点击遮罩关闭层
	,area: IsMobile() ? ['98%',height] : [width,height]
	,shade: 0.2 //透明度
	,moveOut:true
	,maxmin: true
	,id: ModelID.replace(/-/gi,"") //设定一个id，防止重复弹出
	,resize: true
	,btnAlign: 'l' //lcr
	,moveType: 0 //拖拽模式，0或者1
	,anim: 0 //0-6的动画形式，-1不开启
	,content: html
	,btn: ['返回']
	,yes: function(index,layero)
	{ 
		arrLayerIndex.pop();
		layer.close(index);
	}	
	,cancel: function(index, layero)
	{
		//document.title="Close";
		arrLayerIndex.pop();
	}
	,success: function(layero, index)
	{
		arrLayerIndex.push(index);
		eDataTable_Init();
		if(typeof(form_view_finsh)=="function"){form_view_finsh(ModelID);}
		if(typeof(form_view_finish)=="function"){form_view_finish(ModelID);}
  	}
	,end : function(index){arrLayerIndex.pop();}
	
	
    });
	
}
function form_ViewN(obj,ModelID,title,width,height,url) //自定义模块
{
	if(width.toLowerCase().indexOf("px")==-1 && width.toLowerCase().indexOf("%")==-1){width+="px";}
	if(height.toLowerCase().indexOf("px")==-1 && height.toLowerCase().indexOf("%")==-1){height+="px";}
	var html=PostURL(url);	
	layer.open({
  	type: 1 //此处以iframe举例
  	,title: title
	//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
	,shadeClose: true //点击遮罩关闭层
	,area: IsMobile() ? ['98%',height] : [width,height]
	,shade: 0.2 //透明度
	,moveOut:true
	,maxmin: true
	,id: ModelID.replace(/-/gi,"") //设定一个id，防止重复弹出
	,resize: true
	,btnAlign: 'l' //lcr
	,moveType: 0 //拖拽模式，0或者1
	,anim: 0 //0-6的动画形式，-1不开启
	,content: html
	,btn: ['返回']
	,yes: function(index,layero)
	{ 
		arrLayerIndex.pop();
		layer.close(index);
	}	
	,cancel: function(index, layero)
	{
		arrLayerIndex.pop();
		//document.title="Close";
	}
	,success: function(layero, index)
	{
		arrLayerIndex.push(index);		
  	}
	 ,end : function(index){arrLayerIndex.pop();}
	
    });
}
function form_View(obj,ModelID,title,width,height,url) //自定义模块
{
	if(width.toLowerCase().indexOf("px")==-1 && width.toLowerCase().indexOf("%")==-1){width+="px";}
	if(height.toLowerCase().indexOf("px")==-1 && height.toLowerCase().indexOf("%")==-1){height+="px";}
	var html=PostURL(url);	
	//alert(html);
	layer.open({
  	type: 1 //此处以iframe举例
  	,title: title
	//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
	,shadeClose: true //点击遮罩关闭层
	,area: IsMobile() ? ['98%',height] : [width,height]
	,shade: 0.2 //透明度
	,moveOut:true
	,maxmin: true
	,id: ModelID.replace(/-/gi,"") //设定一个id，防止重复弹出
	,resize: true
	,btnAlign: 'l' //lcr
	,moveType: 0 //拖拽模式，0或者1
	,anim: 0 //0-6的动画形式，-1不开启
	,content: html
	,btn: ['返回']
	,yes: function(index,layero)
	{ 
		arrLayerIndex.pop();
		layer.close(index);
	}	
	,cancel: function(index, layero)
	{
		arrLayerIndex.pop();
		//document.title="Close";
	}
	,success: function(layero, index)
	{
		arrLayerIndex.push(index);		
  	}
	 ,end : function(index){arrLayerIndex.pop();}
	
    });

	var tr= obj; //getParent(obj,"tr");
	var index=tr.Index();
	//alert(index);
	var form=getobj("form_" + ModelID);
	var input=getobj("eformdata_" + ModelID);
	var model=input.value.toJson();
	model=model.get("eformdata_" + ModelID);
	var data=model.get(index);
	data.foreach(function(e)
	{
		if(typeof(data[e])=="object")
		{			

			var ctrl = form[e];			
			//ctrl.value= "{\"" + p + "\":" + data[e].toJson() + "}";
			var node=data[e];			
			//if(!node.append){node=new eJson(node);}
			//node.Convert=true;
			ctrl.value= "{\"" + e + "\":" + node.toJson() + "}";
			JsonToTable(data[e],e.replace("eformdata_","eformlist_"));
		}
		else
		{
			if(e.toLowerCase()=="id"){return;}
			if(e.toLowerCase()=="delete"){return;}
			if(e.indexOf("_Text")>-1){return;}
			var ctrl=document.getElementById("span_" + e);

			
			if(!ctrl){return;}
			if(data[e+"_Text"])
			{
				ctrl.innerHTML=data[e+"_Text"].decode();
			}
			else
			{				
				ctrl.innerHTML=data[e].decode();
			}
			//alert(e);
		}
	});
	eDataTable_Init();
}
function Check_CheckUpCustom()
{
    var trback = getobj("checkup_trback");
    var trflow = getobj("checkup_trflow");
    var truser = getobj("checkup_truser");
    if (trback) {
        var f1_value = frmCheckUp["f1"].value;
        switch (f1_value)
        {
            case "1":
                trback.style.display = "none";
                frmCheckUp["f3"].setAttribute("notnull", "false");
                if (trflow)
                {
                    trflow.style.display = "";
                    frmCheckUp["flow1"].setAttribute("notnull", "true");
                    frmCheckUp["flow2"].setAttribute("notnull", "true");
                }
                if (truser)
                {
                    var flow_value = frmCheckUp["flow"].value;
                    if (flow_value == "1") {
                        truser.style.display = "";
                        frmCheckUp["userid"].setAttribute("notnull", "true");
                    }
                    else {
                        truser.style.display = "none";
                        frmCheckUp["userid"].setAttribute("notnull", "false");
                    }
                }
                break;
            case "2":
                trback.style.display = "";
                frmCheckUp["f3"].setAttribute("notnull", "true");
                if (trflow)
                {
                    trflow.style.display = "none";
                    frmCheckUp["flow1"].setAttribute("notnull", "false");
                    frmCheckUp["flow2"].setAttribute("notnull", "false");
                }
                if (truser)
                {
                    truser.style.display = "none";
                    frmCheckUp["userid"].setAttribute("notnull", "false");
                }
                break;
            case "3":
                trback.style.display = "none";
                frmCheckUp["f3"].setAttribute("notnull", "false");
                if (trflow)
                {
                    trflow.style.display = "none";
                    frmCheckUp["flow1"].setAttribute("notnull", "false");
                    frmCheckUp["flow2"].setAttribute("notnull", "false");
                }
                if (truser)
                {
                    truser.style.display = "none";
                    frmCheckUp["userid"].setAttribute("notnull", "false");
                }
                break
        }
    }
    else {
        if (truser)
        {
            var flow_value = frmCheckUp["flow"].value;
            if (flow_value == "1") {
                truser.style.display = "";
                frmCheckUp["userid"].setAttribute("notnull", "true");
            }
            else {
                truser.style.display = "none";
                frmCheckUp["userid"].setAttribute("notnull", "false");
            }
        }
    }
}
function Check_CheckUp()
{
	var tr=getobj("checkup_trback");
	if(tr)
	{		
		if(frmCheckUp["f1"].value == "2")
		{
			tr.style.display = "";
			frmCheckUp["f3"].setAttribute("notnull","true");
		}
		else
		{
			tr.style.display = "none";
			frmCheckUp["f3"].setAttribute("notnull","false");
		}
	}	
}
function CheckUpCustom(UserArea)
{
	var vpath=null;
	var evt=window.event||arguments[0];
	var src=evt.srcElement||evt.target;
	if(src)
	{
		if(src.tagName=="I")
		{
			vpath=src.parentNode.parentNode.getAttribute("vpath");
		}
	}
	var dlgid="";
	var url= (vpath == null ? virtualPath : vpath) + "Customs/base/CheckUpCustom.aspx?UserArea=" + UserArea;	
	if(typeof(AppItem)=="string" && AppItem.length > 0){dlgid=AppItem;url+="&AppItem=" + AppItem;}
	if(typeof(ModelID)=="string" && ModelID.length > 0){dlgid=ModelID;url+="&ModelID=" + ModelID;}	
	url+="&id=" + document.location.href.getquerystring("id");	
	url+="&t=" + now();
	//alert(url);
	$.ajax({
			type: 'get',
			async: false,
			url: url,	
			dataType: "json",
			success: function(data)
			{
			    var json = data;
			    if (json.errcode == "0")
			    {
			        var html = json.html.decode();
			        var _width = "600px";
			        if (IsMobile()) { _width = "95%"; }
			        layer.open({
			            type: 1 //此处以iframe举例
					    ,title: json.title // + "窗口"
			            //,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
					    ,shadeClose: false //点击遮罩关闭层
			            //,area: ["500px",json.width + "300px"]
					    ,area: [_width,json.height + "px"]
					    ,shade: 0.2 //透明度
					    ,moveOut:true
					    ,maxmin: true
					    ,id: dlgid.replace(/-/gi,"") //设定一个id，防止重复弹出
					    ,resize: true
					    ,btnAlign: 'l' //lcr
					    ,moveType: 0 //拖拽模式，0或者1
					    ,anim: 0 //0-6的动画形式，-1不开启
					    ,content: html
					    ,btn: [json.text, '返回']
					    ,yes: function(index,layero)
					    {
					        var _back = eCheckform(frmCheckUp);
					        if (!_back) { return; }
					        var _value = "";
            
					        if (frmCheckUp.elements["f1"] || frmCheckUp["f1"]) {
					            _value = frmCheckUp["f1"].value || frmCheckUp.elements["f1"].value;
					        }

					        if (json.title == "审33核" && _value == "1") {
					            var back_tip = confirm('提示：本人已知晓本次操作会将相应信息发布到互联网，我已确认本次发布信息符合相关安全规定，无涉密内容。');
					            if (!back_tip) { return; }
					        }
					        url = frmCheckUp.action || $("#frmCheckUp").attr("action");
					        url = url.addquerystring("act", "checkup");
					        var formdata = {};
					        if (frmCheckUp["f1"])
					        {
					            var chk = "0";
					            if (frmCheckUp["f11"].checked) { chk = "1"; }
					            if (frmCheckUp["f12"].checked) { chk = "2"; }
					            if (frmCheckUp["f13"].checked) { chk = "3"; }
					            formdata["f1"] = chk;
					        }
					        if (frmCheckUp["flow"])
					        {
					            var flow = "0";
					            if (frmCheckUp["flow1"].checked) { flow = "0"; }
					            if (frmCheckUp["flow2"].checked) { flow = "1"; }
					            formdata["flow"] = flow;
					            formdata["userid"] = frmCheckUp["userid"].value;
					        }
					        if (frmCheckUp["f2"]) { formdata["f2"] = frmCheckUp["f2"].value.encode(); }
					        if (frmCheckUp["f3"]) { formdata["f3"] = frmCheckUp["f3"].value.encode(); }

					        if (typeof (AppItem) == "string" && AppItem.length > 0) { url = url.addquerystring("AppItem", AppItem); }
					        if (typeof (eSignIn) === "object")
					        {
					            var _url = virtualPath + "Plugins/SignIn.aspx?act=checkup";
					            if (typeof (AppItem) == "string" && AppItem.length > 0) { _url += "&AppItem=" + AppItem; } else { if (typeof (ModelID) == "string" && ModelID.length > 0) { _url += "&ModelID=" + ModelID; } }
					            var data = eSignIn.getdata();
					            if (data.length > 100) {
					                $.ajax({
					                    type: 'POST',
					                    async: false,
					                    url: _url,
					                    data: { "imageData": data },
					                    dataType: 'json',
					                    success: function (data) {
					                        if (data.errcode == "0")
					                        {
					                            formdata["signfile"] = data.signfile;
					                        }
					                    }
					                });
					            }
					        }
					        $.ajax({
					            type: 'post',
					            async: false,
					            url: url,
					            data: formdata,
					            dataType: "json",
					            success: function (data)
					            {
					                if (data.errcode == "0")
					                {
					                    url = document.location.href;
					                    $.ajax({
					                        type: 'get',
					                        async: false,
					                        url: url,
					                        dataType: "html",
					                        success: function (data) {
					                            //alert(data);
					                            //layer.msg(json.title + "成功!");
					                            //setTimeout(function(){document.location.assign(url);},2000);
					                            var table = data;
					                            var sstr = '<!--body_start-->';//'<div id="content"';// style="margin:10px;">
					                            var estr = '<!--body_end-->';//'</table>\r\n</div>';

					                            var s = table.indexOf(sstr);
					                            if (s > -1) {
					                                s += sstr.length;
					                                var e = table.indexOf(estr, s);
					                                if (e > -1) {
					                                    e += estr.length;
					                                    $("#content").html(table.substring(s, e) + "");
					                                    layer.msg(json.title + "成功!");
					                                }
					                            }
					                            layer.close(index);
					                        }
					                    });
					                }
					            }
					        });
                            
					    },
					    btn2: function (index, layero) {
                            arrLayerIndex.pop();
                        },
                        cancel: function (index, layero) {
                            arrLayerIndex.pop();
                        },
                        success: function (layero, index) {
                            if (typeof (eSignIn) === "object")//签名插件
                            {
                                eSignIn.init();
                            }
                            arrLayerIndex.push(index);
                        },
                        end: function (index) { arrLayerIndex.pop(); }
			        });
			    }
			    else
			    {
			        layer.msg(json.message);
			    }
			}
	});
}
function CheckUp(UserArea)
{
	var vpath=null;
	var evt=window.event||arguments[0];
	var src=evt.srcElement||evt.target;
	if(src)
	{
		if(src.tagName=="I")
		{
			vpath=src.parentNode.parentNode.getAttribute("vpath");
		}
	}
	var dlgid="";
	var url= (vpath == null ? virtualPath : vpath) + "Customs/base/CheckUp.aspx?UserArea=" + UserArea;	
	if(typeof(AppItem)=="string" && AppItem.length > 0){dlgid=AppItem;url+="&AppItem=" + AppItem;}
	if(typeof(ModelID)=="string" && ModelID.length > 0){dlgid=ModelID;url+="&ModelID=" + ModelID;}	
	url+="&id=" + document.location.href.getquerystring("id");	
	url+="&t=" + now();
	//alert(url);
	//return;
	//window.alert(url);
	$.ajax({
			type: 'get',
			async: false,
			url: url,	
			dataType: "html",
			success: function(data)
			{
				
				//alert(data);
				var json=data.toJson();
				//if(parseBool(json.success))
				if(json.errcode=="0")
				{
					var html = json.html.decode();
					
					var _width="600px";
					if(IsMobile()){_width="95%";}
					//alert(json.html.replace(/</gi,"&lt;").replace(/>/gi,"&gt;"));
					layer.open({
					type: 1 //此处以iframe举例
					,title: json.title // + "窗口"
					//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
					,shadeClose: false //点击遮罩关闭层
					//,area: ["500px",json.width + "300px"]
					,area: [_width,json.height + "px"]
					,shade: 0.2 //透明度
					,moveOut:true
					,maxmin: true
					,id: dlgid.replace(/-/gi,"") //设定一个id，防止重复弹出
					,resize: true
					,btnAlign: 'l' //lcr
					,moveType: 0 //拖拽模式，0或者1
					,anim: 0 //0-6的动画形式，-1不开启
					,content: html
					,btn: [json.text, '返回']
					,yes: function(index,layero)
					{
						var _back=eCheckform(frmCheckUp);							
						if(!_back){return;}
						var _value = "";
						if(frmCheckUp.elements["f1"] || frmCheckUp["f1"])
						{						
						 	_value=frmCheckUp["f1"].value || frmCheckUp.elements["f1"].value;
						}
						if( json.title == "审33核" && _value == "1")
						{
							var back_tip=confirm('提示：本人已知晓本次操作会将相应信息发布到互联网，我已确认本次发布信息符合相关安全规定，无涉密内容。');
							if(!back_tip){return;}
						}
						
						//if(_back){arrLayerIndex.pop();layer.close(index);}
						
						//url= $("#frmCheckUp").attr("action");
						url=frmCheckUp.action || $("#frmCheckUp").attr("action");
						url = url.addquerystring("act", "checkup");
						var formdata = {};
						if(frmCheckUp["f1"])
						{
							var chk="0";
							if(frmCheckUp["f11"].checked){chk="1";}
							if(frmCheckUp["f12"].checked){chk="2";}
							if(frmCheckUp["f13"].checked){chk="3";}
							formdata["f1"] = chk;
						}
						if (frmCheckUp["f2"]) { formdata["f2"] = frmCheckUp["f2"].value.encode(); }
						if (frmCheckUp["f3"]) { formdata["f3"] = frmCheckUp["f3"].value.encode(); }

						if(typeof(AppItem)=="string" && AppItem.length>0){url=url.addquerystring("AppItem",AppItem);}
						if(typeof(eSignIn)==="object")
						{
							var _url = virtualPath + "Plugins/SignIn.aspx?act=checkup";
							if(typeof(AppItem)=="string" && AppItem.length > 0){_url+="&AppItem=" + AppItem;}else{if(typeof(ModelID)=="string" && ModelID.length > 0){_url+="&ModelID=" + ModelID;}}
							var data = eSignIn.getdata();
							if(data.length>100)
							{
								$.ajax({
							        type: 'POST',
									async: false,
							        url: _url,
									data: {"imageData" :  data  },
							        dataType: 'json',
							        success: function (data) {
										if(data.errcode=="0")
										{
										    formdata["signfile"] = data.signfile;
										}
							        }
							    });
							}
						}
						//alert(url);
						//return false;
						$.ajax({
						    type: 'post',
						    async: false,
						    url: url,
						    data: formdata,
						    dataType: "json",
						    success: function (data)
						    {
						        //if(parseBool(data.success))
						        if (data.errcode == "0")
						        {
						            url = document.location.href;
						            $.ajax({
						                type: 'get',
						                async: false,
						                url: url,
						                dataType: "html",
						                success: function (data)
						                {
										    //alert(data);
											//layer.msg(json.title + "成功!");
											//setTimeout(function(){document.location.assign(url);},2000);
											var table=data;
											var sstr= '<!--body_start-->';//'<div id="content"';// style="margin:10px;">
											var estr='<!--body_end-->';//'</table>\r\n</div>';
		
											var s=table.indexOf(sstr);
											if(s>-1)
											{
											    s += sstr.length;
											    var e = table.indexOf(estr, s);
											    if (e > -1)
											    {
											        e += estr.length;
											        $("#content").html(table.substring(s, e) + "");
											        layer.msg(json.title + "成功!");
											    }
											}
											layer.close(index);
										}
									});										   
								}
							}								
						});				
					}
					,btn2: function(index, layero)
					{
						//document.title="关闭";
						arrLayerIndex.pop();
					}
					,cancel: function(index, layero)
					{
						//document.title="Close";
						arrLayerIndex.pop();
					}
					,success: function(layero, index) 
					{
						if(typeof(eSignIn)==="object")//签名插件
						{
							eSignIn.init();
						}	
						arrLayerIndex.push(index);
					}
	  				, end: function (index) { arrLayerIndex.pop(); }
					});
				}
				else
				{
					layer.msg(json.message);
				}
			}
	});
}
function form_load(ModelID)
{
	var act=document.location.href.getquerystring("act");
	var input=getobj("eformdata_" + ModelID);	
	var model=input.value.toJson();
	//alert(JSON.stringify(model));
	//outText(act);
	model=model.get("eformdata_" + ModelID);
	if(model.length==0){return;}
	var data=model.get(0);
	var form=getobj("form_" + ModelID);
	data.foreach(function(e)
	{
		
		var ctrl = form[e];
		if(!ctrl)
		{
			//if(e.indexOf("_Text")>-1){return;}
			ctrl=document.getElementById("span_" + e);
			if(!ctrl){return;}
			if(ctrl.innerHTML.length>0) {return;}
			
			if(data[e+"_Text"])
			{
				ctrl.innerHTML=data[e+"_Text"].decode();
			}
			else
			{
				ctrl.innerHTML=data[e].decode();
			}
		}
		if(!ctrl){return;}
		if(typeof(data[e])=="object")
		{			
			var table=getobj(ctrl.name.replace("eformdata_","eformlist_"));
			if(table)
			{
				//outText(e + ":" + table.getAttribute("reinit"));
				
				if(table.getAttribute("reinit")!="false" || act=="add")
				{
					var node=data[e];
					//if(!node.append){node=new eJson(node);}			
					//node.Convert=true;
					//alert(node.tostring());
					ctrl.value="{\"" + e + "\":" + node.toJson() + "}";
					JsonToTable(data[e],e.replace("eformdata_","eformlist_"));
				}
			}
		}
		else
		{
			
			if(typeof(e)=="string")
			{
				if(ctrl.tagName)//一个
				{
					var etype = ctrl.getAttribute("etype");					
					ctrl.value= data[e].decode();
					if(etype=="select")
					{
						if(ctrl.selectedIndex==-1){ctrl.selectedIndex=0;}
					}
					if(etype=="file")
					{
						var frame=getobj("frm" + ctrl.name);
						var url=frame.getAttribute("src");
						if(ctrl.value.length > 0)
						{
							url=url.addquerystring("act","finsh");
							url=url.addquerystring("file",ctrl.value);
						}
						else
						{
							url=url.removequerystring("act");
							url=url.removequerystring("file");
						}
						frame.src=url;
					}
					if(etype=="html")
					{

						KE.html(ctrl.name,data[e].decode());
					}
				}
				else//多个
				{
					var type=Attribute(ctrl[0],"type").toLowerCase();
					var _tmp="," + data[e].decode() + ",";
					for(var i=0;i<ctrl.length;i++)
					{
						if(_tmp.indexOf("," + ctrl[i].value + ",")>-1)
						{
							ctrl[i].checked=true;
						}
					}
				}

			}
		}		
	});	
	eDataTable_Init();
}
function getAddHTMLN(ModelID,_url)
{


	var html="";	
	
	//eval("var modelhtml=window.ModelHTML_" + ModelID + ";");
	var modelhtml=eval("window.ModelHTML_" + ModelID.replace(/-/gi,"") );
	
	if(modelhtml)
	{
		html=modelhtml;
		//document.title="get";
	}
	else
	{
		//var url="?modelid=" + ModelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "")  + "&act=addsub";
		var url=document.location.href;
		url=url.removequerystring("id");
		url=url.removequerystring("act");
		url=url.addquerystring("ModelID",ModelID);
		url=url.addquerystring("act","addsub");
		if(url.toLowerCase().indexOf("model.aspx")==-1)
		{
			url="model.aspx?modelid=" + ModelID + "&act=addsub";
		}
		if(_url){url=_url;}


		if(typeof(getAddHTML_before)=="function")
		{
			
			var _back=getAddHTML_before(ModelID);
			if(typeof(_back)=="object")
			{
				//if(!_back.result){return;}
				if(_back.query.length>0)
				{
					//url+= url.indexOf("?") > -1 ? "&" + _back.query : "?"  + _back.query ;
					var query=_back.query.replace("?","");
					var arr=query.split("&");
					for(var x=0;x<arr.length;x++)
					{
						var arr2=arr[x].split("=");
						if(arr2.length==2)
						{
							url=url.addquerystring(arr2[0],arr2[1]);
						}
					}
				}
				
			}
		}
		if(url.indexOf("pid=")==-1)
		{
			var id=document.location.href.getquerystring("id");
			if(id.length>0)
			{
				url+= url.indexOf("?") > -1 ? "&pid=" + id : "?pid="  + id ;
			}
		}
		
		var debug=document.location.href.getquerystring("debug");
		if(debug.length>0) url+= "&debug=" + debug; 
		url+= "&t=" + now();
		html=PostURL(url);
		eval('window.ModelHTML_'+ ModelID.replace(/-/gi,"") +'=html;');
		//document.title="set";
	}
	return html;
}

function form_viewN(obj,ModelID,title,width,height,ID) //自动模块
{
	if(width.toLowerCase().indexOf("px")==-1 && width.toLowerCase().indexOf("%")==-1){width+="px";}
	if(height.toLowerCase().indexOf("px")==-1 && height.toLowerCase().indexOf("%")==-1){height+="px";}
	//if(!ID){ID=obj.getAttribute("eRowID");}
	//alert(obj instanceof jQuery);
	//alert(obj instanceof Array);   //会返回true
	//alert(obj instanceof Object)  
	//alert(typeof(obj));
	var tr=null;
	if(obj.tagName=="TR" && obj.getAttribute("eRowID")!=null)
	{
		tr=obj;
	}
	else
	{
		tr=getParent(obj.parentNode,"tr");
		if(tr.getAttribute("eRowID")==null){tr=getParent(tr.parentNode,"tr"); }
	}
	
	if(tr.getAttribute("eRowID")==null){return;}
	
	if(!ID){ID=tr.getAttribute("eRowID");}
	
		var url=document.location.href;
		url=url.removequerystring("id");
		url=url.removequerystring("act");
		url=url.addquerystring("ModelID",ModelID);
		url=url.addquerystring("act","viewsub");
		url=url.addquerystring("id",ID);
		


	
	var logid=document.location.href.getquerystring("logid");
	if(logid.length>0) url+= "&logid=" + logid; 
	url+= "&t=" + now();


	var html=PostURL(url);
	layer.open({
  	type: 1 //此处以iframe举例
  	,title: title
	//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
	,shadeClose: true //点击遮罩关闭层
	,area: IsMobile() ? ['98%',height] : [width,height]
	,shade: 0.2 //透明度
	,moveOut:true
	,maxmin: true
	,id: ModelID.replace(/-/gi,"") //设定一个id，防止重复弹出
	,resize: true
	,btnAlign: 'l' //lcr
	,moveType: 0 //拖拽模式，0或者1
	,anim: 0 //0-6的动画形式，-1不开启
	,content: html
	,btn: ['返回']
	,yes: function(index,layero)
	{ 
		arrLayerIndex.pop();
		layer.close(index);
	}	
	,cancel: function(index, layero)
	{
		//document.title="Close";
		arrLayerIndex.pop();
	}
	,success: function(layero, index)
	{
		arrLayerIndex.push(index);
		eDataTable_Init();
		if(typeof(form_view_finsh)=="function"){form_view_finsh(ModelID);}
		if(typeof(form_view_finish)=="function"){form_view_finish(ModelID);}
  	}
	,end : function(index){arrLayerIndex.pop();}
	
	
    });
	
}
function form_quickview(obj,appitem,ModelID,title,width,height) //自动模块
{
	if(width.toLowerCase().indexOf("px")==-1 && width.toLowerCase().indexOf("%")==-1){width+="px";}
	if(height.toLowerCase().indexOf("px")==-1 && height.toLowerCase().indexOf("%")==-1){height+="px";}
	var tr=null;
	if(obj.tagName=="TR" && obj.getAttribute("eRowID")!=null)
	{
		tr=obj;
	}
	else
	{
		tr=getParent(obj.parentNode,"tr");
		if(tr.getAttribute("eRowID")==null){tr=getParent(tr.parentNode,"tr"); }
	}
	
	if(tr.getAttribute("eRowID")==null){return;}
	
	var ID=tr.getAttribute("eRowID");

	
		var url=document.location.href;
		url=url.removequerystring("id");
		url=url.removequerystring("act");
		url=url.addquerystring("ModelID",ModelID);
		url=url.addquerystring("act","quickview");
		url=url.addquerystring("act","viewsub");
		url=url.addquerystring("id",ID);
		url=url.addquerystring("appitem",appitem);
		//url=url.addquerystring("ajax","true");
	
	var logid=document.location.href.getquerystring("logid");
	if(logid.length>0) url+= "&logid=" + logid; 
	url+= "&t=" + now();

	var html=PostURL(url);
	layer.open({
  	type: 1 //此处以iframe举例
  	,title: title
	//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
	,shadeClose: true //点击遮罩关闭层
	,area: IsMobile() ? ['98%',height] : [width,height]
	,shade: 0.2 //透明度
	,moveOut:true
	,maxmin: true
	,id: ModelID.replace(/-/gi,"") //设定一个id，防止重复弹出
	,resize: true
	,btnAlign: 'l' //lcr
	,moveType: 0 //拖拽模式，0或者1
	,anim: 0 //0-6的动画形式，-1不开启
	,content: html
	,btn: ['返回']
	,yes: function(index,layero)
	{ 
		arrLayerIndex.pop();
		layer.close(index);
	}	
	,cancel: function(index, layero)
	{
		//document.title="Close";
		arrLayerIndex.pop();
	}
	,success: function(layero, index)
	{
		arrLayerIndex.push(index);
		eDataTable_Init();
		if(typeof(form_view_finsh)=="function"){form_view_finsh(ModelID);}
		if(typeof(form_view_finish)=="function"){form_view_finish(ModelID);}
  	}
	,end : function(index){arrLayerIndex.pop();}
	
	
    });
	
}

var form_area;//保存区域对象Jquery对象
function form_saveN(ModelID)
{
	
	var frm= document.forms["form_" + ModelID];
	if(!frm){layer.msg("表单form_" + ModelID + "不存在!");return false;}	
	var Prefix="M" + ModelID + "_";
	Prefix="";

	var _back=eCheckform(frm);	
	if(!_back){return false;}

	
	//var input=getobj("eformdata_" + ModelID);
	var input;
	if(form_area)
	{
		input=form_area.find("#eformdata_" + ModelID);		
		input=input.length>0 ? input[0] : getobj("eformdata_" + ModelID);
	}
	else
	{
		input=getobj("eformdata_" + ModelID);
	}
	//alert(input);
	//input.style.borderColor="#ff0000";
	//return true;
	var model=input.value.toJson();	
	//model.Convert=true;
	//alert(model.toJson());
	
	var _data=model.get("eformdata_" + ModelID);
	

	var index=parseInt(frm[Prefix + "Index"].value);
	//document.title="X2:" + index;
	
	//var table=getobj("eformlist_" + ModelID);
	var table;
	if(form_area)
	{
		table=form_area.find("#eformlist_" + ModelID);
		table=table.length>0 ? table[0] : getobj("eformlist_" + ModelID);
	}
	else
	{
		table=getobj("eformlist_" + ModelID);
	}
	
	
	var tbody=table.getElementsByTagName("tbody")[0];
	var obj= formToJson(frm);
//alert("form_SaveN" + obj.toJson());
	//return;
	//alert(new eJson(obj).toJson());
	

	//return;
	
	var tfoot=table.getElementsByTagName("tfoot")[0];
	var otr=tfoot.getElementsByTagName("tr")[0].cloneNode(true);
	var otds=otr.getElementsByTagName("td");
	if(index>-1)//替换
	{
		_data[index]=obj;
		
		//var tr=tbody.getElementsByTagName("tr")[index];
		var tr=tbody.children[index];
		//tr,td 不可以使用getElementsByName  getElementById 所以要从TD 去读JSON数据，而不是从Json数据到TD
		//alert(tr.outerHTML);
		
		//alert("form_SaveN" + obj.toJson());
		 $(tr).find("[name]").each(function(i,elem){			
			var name=elem.getAttribute("name");
			if(name)
			{
				var etype=$(elem).attr("etype");
				var ewidth=$(elem).attr("ewidth");
				var eheight=$(elem).attr("eheight");
				if($(elem).find("label").length>0)
				{
					elem=$(elem).find("label").get(0);
				}
				var _opar= $(otr).find("[name='" + name + "']").get(0);
				name=name.replace("td_","");
				if(obj[name+"_Text"])
				{
				    elem.innerHTML = obj[name + "_Text"].decode().replace(/\\n/g, " ");
				}
				else
				{
					if(obj[name] || typeof(obj[name])== "string")
					{
					    if (etype == "file")
					    {
					        $(elem).html('<a href="' + obj[name] + '" target="_blank">查看</a>');
					        return true;
					    }
						if(etype=="image")
						{
						    //alert("A:" + obj[name]);
						    $(elem).find("img").attr("src", obj[name]);
							//elem.innerHTML='<img src="'+ obj[name] +'" style="width:'+ ewidth +'px;height:'+ eheight +'px;">';
							return true;
						}
						if (etype == "images") {
						    var div = $(elem).find(".efiles-body div");
							/*1
						    div.attr("url", "");
						    div.css("backgroundImage", "");
						    div.attr("onclick", "");
						    var jsonstr = obj[name].decode();
						    if (jsonstr.length > 3) {
						        var json = jsonstr.toJson();
						        if (json.length > 0) {
						            div.attr("url", json[0].url + "");
						            div.css("backgroundImage", "url(" + json[0].url + ")");
						            div.attr("onclick", "viewImage(\'" + json[0].url + "\',800,600);");
						        }
						    }
							*/
						    div.attr("url", "");
						    var jsonstr = obj[name].decode();
						    if (jsonstr.length > 3) {
						        var json = jsonstr.toJson();
						        if (json.length > 0) {
						            div.attr("url", json[0].url + "");
						        }
						    }
						    return true;
						}
						if(_opar.innerHTML.toLowerCase().indexOf("data:")==-1)
						{
						    elem.innerHTML = obj[name].decode().replace(/\\n/g, " ");//
						    //alert(obj[name].decode());
						}
						else
						{
						    elem.innerHTML = _opar.innerHTML.replace(/{data:.*?}/gi, obj[name].decode().replace(/\\n/g, " "));
						}						
					}
					else
					{
						if(name.length>0 && _opar.innerHTML.toLowerCase().indexOf("data:")> -1){elem.innerHTML="";}
					}
				}
			}
	     });
	}
	else //添加
	{
		_data.append(obj);
		//alert(JSON.stringify(obj));
		$(otr).find("[name]").each(function(i,elem){
			var name=elem.getAttribute("name");
			if(name)
			{
				var etype=$(elem).attr("etype");
				var ewidth=$(elem).attr("ewidth");
				var eheight=$(elem).attr("eheight");
				if($(elem).find("label").length>0)
				{
					elem=$(elem).find("label").get(0);
				}				
				name=name.replace("td_","");
				if(obj[name+"_Text"])
				{
				    elem.innerHTML = obj[name + "_Text"].decode().replace(/\\n/g, " ");
				}
				else
				{
					if(obj[name] || typeof(obj[name])== "string")
					{
					    if (etype == "file") {
					        $(elem).html('<a href="' + obj[name] + '" target="_blank">查看</a>');
					        return true;
					    }
						if(etype=="image")
						{
						    //alert("B:" + obj[name]);
						    $(elem).find("img").attr("src", obj[name]);
							//elem.innerHTML='<img src="'+ obj[name] +'" style="width:'+ ewidth +'px;height:'+ eheight +'px;">';
							return true;
						}
						if (etype == "images") {
						    var div = $(elem).find(".efiles-body div");
                            /*2
						    div.attr("url", "");
						    div.css("backgroundImage", "");
						    div.attr("onclick", "");
						    var jsonstr = obj[name].decode();
						    if (jsonstr.length > 3) {
						        var json = jsonstr.toJson();
						        if (json.length > 0) {
						            div.attr("url", json[0].url + "");
						            div.css("backgroundImage", "url(" + json[0].url + ")");
						            div.attr("onclick", "viewImage(\'" + json[0].url + "\',800,600);");
						        }
						    }
                            */
						    div.attr("url", "");
						    var jsonstr = obj[name].decode();
						    if (jsonstr.length > 3) {
						        var json = jsonstr.toJson();
						        if (json.length > 0) {
						            div.attr("url", json[0].url + "");
						        }
						    }
						    return true;
						}
						if(elem.innerHTML.toLowerCase().indexOf("data:")==-1)
						{
						    elem.innerHTML = obj[name].decode().replace(/\\n/g, " ");
						}
						else
						{
						    elem.innerHTML = elem.innerHTML.replace(/{data:.*?}/gi, obj[name].decode().replace(/\\n/g, " "));
						}
						
					}
					else
					{
						//elem.innerHTML="";
						//alert($(tbody).find("tr").length);
						//更新顺序号
						elem.innerHTML=elem.innerHTML.replace(/{row:index}/gi,$(tbody).children("tr").length + 1);
					}
				}
			}
		});		
		tbody.appendChild(otr);
		//alert(table.parent);
		if(table.parent){Table_Init_Tbody(table.parent);}
		
	}
	//alert(model.toJson());
	input.value=model.toJson();
	//form_cancel(ModelID);
	//var count=getobj("count_" + ModelID);
	var count;
	//count计算
	if(form_area)
	{
		count=form_area.find("#count_" + ModelID);
		count=count.length>0 ? count[0] : count=getobj("count_" + ModelID);
	}
	else
	{
		count=getobj("count_" + ModelID);
	}
	//alert(count);
	if(count)
	{
		count.value=$(tbody).find("tr:visible").length;// tbody.children.length;
	}
	//回调函数-添加修改
	if(typeof(submodel_onChange)=="function")
	{
		var list_trs=$("#eformlist_" + ModelID + " > tbody > tr");
		submodel_onChange(ModelID,list_trs,tbody);
	}

	return true;
}
function form_addN(obj,ModelID,title,width,height,url)
{
	form_area=$(obj).parents("table:first").parent();
	//form_area[0].style.borderColor="#ff0000";
	//alert(form_area[0].tagName);
	//alert(url);
	//return;
	var html=getAddHTMLN(ModelID,url);
	//alert(html);
	//return;
	layer.open({
  	type: 1 //此处以iframe举例
  	,title: title
	//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
	,shadeClose: false //点击遮罩关闭层
  	,area: IsMobile() ? ['98%',height] : [width,height]
	,shade: 0.2 //透明度
	,moveOut:true
	,maxmin: true
	,id: ModelID.replace(/-/gi,"") //设定一个id，防止重复弹出
	,resize: true
	,btnAlign: 'l' //lcr
	,moveType: 0 //拖拽模式，0或者1
	,anim: 0 //0-6的动画形式，-1不开启
	,content: html
	,btn: ['确定', '关闭']
	,yes: function(index,layero)
	{ 
		//alert(ModelID);

		var _back=form_saveN(ModelID);
		if(_back){arrLayerIndex.pop();layer.close(index);}
	}
	,btn2: function(index, layero)
	{
		//document.title="关闭";
		arrLayerIndex.pop();
	}
	,cancel: function(index, layero)
	{
		//document.title="Close";
		arrLayerIndex.pop();
	}
	,success: function(layero, index)
	{
		arrLayerIndex.push(index);
		$('.layui-layer-content textarea[etype*="html"]').each(function(i,elem){
			KE.init({
				id : elem,
				width :  elem.getAttribute("width") ,
				height : elem.getAttribute("height")
			});
			KE.create(elem.id);
		});
		initdate($('.layui-layer-content'));//初始化移动端日期选择
        
		var area = $(".layui-layer-content");
		Resize_eControl(area);
		if(typeof(form_add_finsh)=="function"){form_add_finsh(ModelID);}
		if(typeof(form_add_finish)=="function"){form_add_finish(ModelID);}
  	}
	 ,end : function(index){arrLayerIndex.pop();}
    });
	var form=getobj("form_" + ModelID);	
	if(form){form["Index"].value="-1";}
}
function JsonToDD(data,dd)
{
	data.foreach(function(e)
	{
	    var ctrl = dd.find("[postname='" + e + "']");
	    //alert(e + "::" + ctrl.length );
		if(ctrl.length>0)
		{
		    //alert(ctrl.length);
			/*
			var type=ctrl.attr("type").toLowerCase();
			if(type=="checkbox" || type=="radio")//只有一个选项
			{
				var _tmp="," + data[e].decode() + ",";
				if(_tmp.indexOf("," + ctrl.value + ",")>-1)
				{
					ctrl.checked=true;
				}
			}
			else
			{
				ctrl.val(data[e]);
			}
			*/
		    ctrl.each(function (i, el) {
				var type = ctrl.attr("type");
				var etype = ctrl.attr("etype") ? ctrl.attr("etype") : "text";
				if(type=="checkbox" || type=="radio")//只有一个选项
				{
					var _tmp="," + data[e].decode() + ",";
					if(_tmp.indexOf("," + el.value + ",")>-1)
					{
						el.checked=true;
					}
				}
				else
				{					
					$(this).val(data[e]);
					if(etype=="label" && data[e+"_Text"])
					{
						var onext = ctrl.nextElementSibling||ctrl.nextSibling;
						onext.innerHTML=data[e+"_Text"].decode();
						$(this).attr("text",data[e+"_Text"].decode());
					}
				}
			});	
		}
	});
}
function form_editN(obj,ModelID,title,width,height,url)
{
	if(width.toLowerCase().indexOf("px")==-1 && width.toLowerCase().indexOf("%")==-1){width+="px";}
	if(height.toLowerCase().indexOf("px")==-1 && height.toLowerCase().indexOf("%")==-1){height+="px";}
	var src=getEventObject();
	if(src.tagName=="DIV" && typeof(src.onclick)=='function')
	{
		return;
	}
	if(src.tagName.toLowerCase()=="a" && src.className=="btndel"){return;}
	form_area=$(obj).parents("table:first").parent();
	var Prefix="M" + ModelID + "_";
	Prefix="";

	var rect=obj.getBoundingClientRect();	
	var html=getAddHTMLN(ModelID,url);

	
	//var frm=new eDialog("model_form_" + ModelID.replace(/-/gi,""),"修改",rect.left,Scroll().top + rect.bottom,500,300);
	//frm.setHTML(html);
	layer.open({
  	type: 1 //此处以iframe举例
  	,title: title
	//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
	,shadeClose: false //点击遮罩关闭层
	,area: IsMobile() ? ['98%',height] : [width,height]
	,shade: 0.2 //透明度
	,moveOut:true
	,maxmin: true
	,id: ModelID.replace(/-/gi,"") //设定一个id，防止重复弹出
	,resize: true
	,btnAlign: 'l' //lcr
	,moveType: 0 //拖拽模式，0或者1
	,anim: 0 //0-6的动画形式，-1不开启
	,content: html
	,btn: ['确定', '关闭']
	,yes: function(index,layero)
	{ 

		var _back=form_saveN(ModelID);
		if(_back){arrLayerIndex.pop();layer.close(index);}
	}
	,btn2: function(index, layero)
	{
		arrLayerIndex.pop();
		//document.title="关闭";
	}
	,cancel: function(index, layero)
	{
		arrLayerIndex.pop();
		//document.title="Close";
	}
	,success: function(layero, index)
	{
		arrLayerIndex.push(index);
		$('.layui-layer-content textarea[etype*="html"]').each(function(i,elem){
			//弹出层有问题
			KE.init({
				id : elem,
				width :  elem.getAttribute("width") ,
				height : elem.getAttribute("height")
			});
			KE.create(elem.id);
			//KE.html(elem.id, '<h3>Hello KindEditor</h3>');

		});
		initdate($('.layui-layer-content'));
		var area = $(".layui-layer-content");
		Resize_eControl(area);
		if(typeof(form_edit_finsh)=="function"){form_edit_finsh(ModelID);}
		if(typeof(form_edit_finish)=="function"){form_edit_finish(ModelID);}
  	}
	  ,end : function(index){arrLayerIndex.pop();}

    });
	
	

	
	//var tr=obj;//getParent(obj,"tr");
	//var index=0;
	//for(i=0;i<trs.length;i++){if(trs[i]== tr){index= i;}}
	var tr=null;

	if(obj.tagName=="TR" && obj.getAttribute("eRowID")!=null)
	{
		tr=obj;
	}
	else
	{
		tr=getParent(obj.parentNode,"tr");

	}
	

	if(tr.getAttribute("eRowID")==null)
	{
		tr=getParent(tr,"tr");
	}

	var index=tr.Index();
	//alert(index);
	var form=getobj("form_" + ModelID);
	if(form[Prefix + "Index"])
	{
		form[Prefix + "Index"].value=index;
	}
	
	//alert(form.elements.length);
	for(i=0; i < form.elements.length; i++)
	{
		//alert(form.elements[i].name);
	}
	//var input=getobj("eformdata_" + ModelID);
	var input;
	if(form_area)
	{
		input=form_area.find("#eformdata_" + ModelID);		
		input=input.length>0 ? input[0] : getobj("eformdata_" + ModelID);
	}
	else
	{
		input=getobj("eformdata_" + ModelID);
	}
	
	
	//alert(input.value);
	var model=input.value.toJson();
	//alert(model.toJson());
	//model.Convert=true;
	model=model.get("eformdata_" + ModelID)	
	//alert(ModelID + "::" + model.toJson());
	var data=model.get(index);	
	//alert(data.toJson());
	//alert(index);
	//alert(data.foreach);
	data.foreach(function(e)
	{
		//alert(e);
		var ctrl = form[e];		
		//alert(ctrl);
	//alert(e + "::" + ctrl.length);
		
		if(!ctrl)
		{
			//编辑只读
			//alert(e + "::" );
			ctrl=$("#"+e +"_box");
			if(ctrl.length>0)
			{
				if(data[e+"_Text"])
				{
					ctrl.html(data[e+"_Text"]);
				}
				else
				{
					ctrl.html(data[e]);
				}
			}
			return;
		}
		if(ctrl.length && (e.toLowerCase()=="id" || e.toLowerCase()=="delete"))
		{
			ctrl=ctrl[0];//excel会造成ID，delete多个
		}
		if(typeof(data[e])=="object")
		{
			
			var node=data[e];
			//count计算
			//count_89169770-43f8-4ecd-a283-b1a9256a763d //eformdata_89169770-43f8-4ecd-a283-b1a9256a763d
			//alert(e + "::" + node.toJson());
			//if(!node.append){node=new eJson(node);}
			//node.Convert=true;
			ctrl.value= "{\"" + e + "\":" + node.toJson() + "}";
			
			//alert(333);
			var countid=e.replace("eformdata_","count_");			
			var par=$(ctrl).parent();
			var listobj= par.find("#" + e.replace("eformdata_","eformlist_"));
			var count=par.find("#" + countid);
			if(count)
			{
				count.val(node.length);
			}
			if(listobj.length>0 && listobj.attr("class")=="divsubList")
			{
				var _modelid= e.replace("eformdata_","");
				var _html=getAddHTMLN(_modelid);	
				//alert( node.toJson());
				node.foreach(function(x)
				{
					//alert(_html);
					listobj.append(_html);
					var dd=listobj.find("dl:last dd");
					//dd.css("border","1px solid #ff0000");
					JsonToDD(node[x],dd);
				});
			}
			else
			{
				//JsonToTable(data[e],e.replace("eformdata_","eformlist_"));
				JsonToTable(node,e.replace("eformdata_","eformlist_"));
			}
		}
		else
		{
		
			if(typeof(e)=="string")
			{
				
				if(ctrl.tagName)
				{
					//alert(ctrl.tagName + "::" + ctrl.name + "::" +  data[e]);
					
					var type=Attribute(ctrl,"type").toLowerCase();
					if(type=="checkbox" || type=="radio")//只有一个选项
					{
						var _tmp="," + data[e].decode() + ",";
						if(_tmp.indexOf("," + ctrl.value + ",")>-1)
						{
							ctrl.checked=true;
						}
						return;
						//alert(e + "::" + ctrl.tagName + "::" + ctrl.length + "::" + type);
					}				
					var v=data[e].decode();
					ctrl.value= v;
					ctrl.setAttribute("ovalue",v);

					var editreadonly=Attribute(ctrl,"editreadonly");
					if(v.length>0 && editreadonly=="true")
					{
						ctrl.setAttribute("readOnly","true");
					}

					if(ctrl.onchange)
					{
						$(ctrl).trigger("change");
					}
					var etype=Attribute(ctrl,"etype").toLowerCase();
					
					if(etype=="image")
					{
					    $(ctrl).parent().find(".eimage img").attr("src", ctrl.value);
						//$(ctrl).parent().find(".eimage").css("backgroundImage","url('" + ctrl.value + "')");
						//alert(etype);
					}
					if (etype == "images" && ctrl.value.length > 3)
					{
					    var imgs = ctrl.value.toJson();
					    var pbody = $(ctrl).parent();
						for(var i=0;i < imgs.length; i++)
						{
							//alert(imgs[i].url);
						    //$(ctrl).after('<div onclick="viewImage(\'' + imgs[i].url.replace("_thumb", "") + '\',800,600);" url="' + imgs[i].url + '" style="background-image:url(' + imgs[i].url + ');"><img title="删除" class="del" src="' + $(ctrl).parent().attr("vpath") + 'images/none.gif" /></div>');
						    $(ctrl).after('<div url="' + imgs[i].url + '" style="width:' + pbody.find("a:eq(0)").width() + 'px;height:' + pbody.find("a:eq(0)").height() + 'px;"><img src="' + imgs[i].url + '" /><img title="删除" class="del" src="' + $(ctrl).parent().attr("vpath") + 'images/none.gif" /></div>');
						}						
						pbody.find("div").arrangeable();
						//alert(imgs.toJson());
						//alert("DD::"+ctrl.value);
						//$(ctrl).after("DDD");
					}
					if(etype=="singleuser" && ctrl.value.length>0 && ctrl.name.toLowerCase().indexOf("_text")>-1)
					{
						//alert($(ctrl).parent().text() + "::" + ctrl.value + "::" + ctrl.name  );
						$(ctrl).parent().find("p").text(ctrl.value);
					}
					if(etype=="label" && ctrl.value.length>0)
					{							
						var onext = ctrl.nextElementSibling||ctrl.nextSibling;		
						if(data[e+"_Text"])
						{
							onext.innerHTML=data[e+"_Text"].decode();
							ctrl.setAttribute("text",data[e+"_Text"].decode());
						}
						else
						{
							onext.innerHTML=ctrl.value;
						}
					}
					if(etype=="html" && ctrl.value.length>0)
					{
						KE.html(ctrl.id, ctrl.value);
						//alert(etype + "::" + ctrl.value + "::" + ctrl.id);
					}
					//alert(etype + "::" + ctrl.value);
					if(etype=="file" && ctrl.value.length>0)
					{
						var frame=getobj("frm" + ctrl.id );
						if(frame)
						{
							var src=frame.getAttribute("src");
							if(src.toLowerCase().indexOf("act=")==-1)
							{
								src+="&act=finsh";
							}
							src+="&file=" + ctrl.value;
							//alert(src);
							//alert(ctrl.id + "::" + data[e]);
							frame.src=src;
						}
					}
				}
				else
				{
					//checkbox or radio
					var type=Attribute(ctrl[0],"type").toLowerCase();
					var editreadonly=Attribute(ctrl[0],"editreadonly");					
					var _tmp="," + data[e].decode().toLowerCase().replace("true","1").replace("false","0") + ",";
					//alert(type + "::" + _tmp);
					for(var i=0;i<ctrl.length;i++)
					{
						if(editreadonly=="true")
						{
							//ctrl[i].setAttribute("readOnly","true");
							ctrl[i].disabled=true;
						}
						if(_tmp.indexOf("," + ctrl[i].value.toLowerCase().replace("true","1").replace("false","0") + ",")>-1)
						{
							ctrl[i].checked=true;
						}
					}
				}
			}
		}
	});
	
	eDataTable_Init();
}
function form_deleteN(obj,ModelID,delText)
{
	if(!delText){delText="删除";}
	var Prefix="M" + ModelID + "_";
	Prefix="";
	if(!confirm("确认要" + delText + "吗？")){return;}
	
	var tr=getParent(obj,"tr");
	if(tr.getAttribute("eRowID")==null)
	{
		tr=getParent(tr.parentNode,"tr");
	}
	//alert(tr.getAttribute("eRowID"));
	//return;
	var tbody=getParent(tr,"tbody");
	var trs=tbody.getElementsByTagName("tr");
	//var index=0;
	//for(i=0;i<trs.length;i++){if(trs[i]== tr){index= i;}}
	var index=tr.Index();
	
	var input=getobj("eformdata_" + ModelID);
	
	var model=input.value.toJson();
	//model.Convert=true;

	
	var _model=model.get("eformdata_" + ModelID);
	_model=_model[index];

	if(_model[Prefix + "ID"].length==0)
	{
		_model=model.get("eformdata_" + ModelID)
		_model.remove(index);	
		tbody.removeChild(tr);
	}
	else
	{
		_model[Prefix + "Delete"]="true";
		tr.style.display="none";
	}
	//更新顺序号
	var otable=getobj("eformlist_" + ModelID);	
	var otfoot=otable.getElementsByTagName("tfoot")[0];
	var otr=otfoot.getElementsByTagName("tr")[0].cloneNode(true);
	var otds=otr.getElementsByTagName("td");
	var row_index=-1;
	for(var i=0;i<otds.length;i++)
	{
		if(otds[i].innerHTML.toLowerCase().indexOf("row:index")>-1)
		{
			row_index=i;
			break;
		}
	}
	if(row_index>-1)
	{
		$(tbody).find("tr:visible").each(function(i,elem){
			$(this).find("td:eq(" + row_index + ")").html(i + 1); 
		});
	}
		
	//var count=getobj("count_" + ModelID);
	var count;
	if(form_area)
	{
		count=form_area.find("#count_" + ModelID);
		count=count.length>0 ? count[0] : count=getobj("count_" + ModelID);
	}
	else
	{
		count=getobj("count_" + ModelID);
	}
	
	if(count)
	{		
		count.value= $(tbody).find("tr:visible").length;// tbody.children.length;
	}
	input.value=model.toJson();	

	//回调函数-删除
	if(typeof(submodel_onChange)=="function")
	{
		var list_trs=$("#eformlist_" + ModelID + " > tbody > tr");
		submodel_onChange(ModelID,list_trs,tbody);
	}
}
//OK
function form_add(obj,ModelID,title,width,height,url)
{
	var html=getAddHTML(ModelID,url);
	//alert(html);
	layer.open({
  	type: 1 //此处以iframe举例
  	,title: title
	//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
	,shadeClose: false //点击遮罩关闭层
  	,area: IsMobile() ? ['98%',height] : [width,height]
	,shade: 0.2 //透明度
	,moveOut:true
	,maxmin: true
	,id: ModelID.replace(/-/gi,"") //设定一个id，防止重复弹出
	,resize: true
	,btnAlign: 'l' //lcr
	,moveType: 0 //拖拽模式，0或者1
	,anim: 0 //0-6的动画形式，-1不开启
	,content: html
	,btn: ['确定', '关闭']
	,yes: function(index,layero)
	{ 
		var _back=form_save(ModelID);
		if(_back){arrLayerIndex.pop();layer.close(index);}
	}
	,btn2: function(index, layero)
	{
		//document.title="关闭";
		arrLayerIndex.pop();
	}
	,cancel: function(index, layero)
	{
		//document.title="Close";
		arrLayerIndex.pop();
	}
	,success: function(layero, index)
	{
		arrLayerIndex.push(index);
		$('.layui-layer-content textarea[etype*="html"]').each(function(i,elem){
			KE.init({
				id : elem,
				width :  elem.getAttribute("width") ,
				height : elem.getAttribute("height")
			});
			KE.create(elem.id);
		});		
		initdate($('.layui-layer-content'));//初始化移动端日期选择
		var area = $(".layui-layer-content");
		Resize_eControl(area);
		if(typeof(form_add_finsh)=="function"){form_add_finsh(ModelID);}
		if(typeof(form_add_finish)=="function"){form_add_finish(ModelID);}
  	}
	 ,end : function(index){arrLayerIndex.pop();}
    });
	
	var form=getobj("form_" + ModelID);	
	if(form){form["Index"].value="-1";}
}
//OK

function form_edit(obj,ModelID,title,width,height,url)
{
	if(!url)
	{
		//url="model.aspx?modelid=" + ModelID + "&act=add";
	}
	//alert(url);
	
	var src=getEventObject();
	if(src.tagName=="DIV" && typeof(src.onclick)=='function')
	{
		return;
	}
	if(src.tagName.toLowerCase()=="a" && src.className=="btndel"){return;}
	//alert(ModelID);
	var Prefix="M" + ModelID + "_";
	Prefix="";

	var rect=obj.getBoundingClientRect();	
	var html=getAddHTML(ModelID,url);
	//alert(html);

	
	//var frm=new eDialog("model_form_" + ModelID.replace(/-/gi,""),"修改",rect.left,Scroll().top + rect.bottom,500,300);
	//frm.setHTML(html);
	layer.open({
  	type: 1 //此处以iframe举例
  	,title: title
	//,skin: 'layui-layer-molv' //加上边框 layui-layer-rim  layui-layer-lan layui-layer-molv layer-ext-moon
	,shadeClose: false //点击遮罩关闭层
	,area: IsMobile() ? ['98%',height] : [width,height]
	,shade: 0.2 //透明度
	,moveOut:true
	,maxmin: true
	,id: ModelID.replace(/-/gi,"") //设定一个id，防止重复弹出
	,resize: true
	,btnAlign: 'l' //lcr
	,moveType: 0 //拖拽模式，0或者1
	,anim: 0 //0-6的动画形式，-1不开启
	,content: html
	,btn: ['确定', '关闭']
	,yes: function(index,layero)
	{ 
		var _back=form_save(ModelID);
		if(_back){arrLayerIndex.pop();layer.close(index);}
	}
	,btn2: function(index, layero)
	{
		arrLayerIndex.pop();
		//document.title="关闭";
	}
	,cancel: function(index, layero)
	{
		arrLayerIndex.pop();
		//document.title="Close";
	}
	,success: function(layero, index)
	{
		arrLayerIndex.push(index);
		$('.layui-layer-content textarea[etype*="html"]').each(function(i,elem){
			//弹出层有问题
			KE.init({
				id : elem,
				width :  elem.getAttribute("width") ,
				height : elem.getAttribute("height")
			});
			KE.create(elem.id);
			//KE.html(elem.id, '<h3>Hello KindEditor</h3>');

		});
		initdate($('.layui-layer-content'));
		var area = $(".layui-layer-content");
		Resize_eControl(area);
		if(typeof(form_edit_finsh)=="function"){form_edit_finsh(ModelID);}
		if(typeof(form_edit_finish)=="function"){form_edit_finish(ModelID);}
  	}
	  ,end : function(index){arrLayerIndex.pop();}

    });
	
	
	
	//var tr=obj;//getParent(obj,"tr");
	//var index=0;
	//for(i=0;i<trs.length;i++){if(trs[i]== tr){index= i;}}
	var tr=null;

	if(obj.tagName=="TR" && obj.getAttribute("eRowID")!=null)
	{
		tr=obj;
	}
	else
	{
		tr=getParent(obj.parentNode,"tr");

	}	

	if(tr.getAttribute("eRowID")==null)
	{
		tr=getParent(tr,"tr");
	}

	var index=tr.Index();
	//alert(index);
	var form=getobj("form_" + ModelID);
	if(form[Prefix + "Index"])
	{
		form[Prefix + "Index"].value=index;
	}
	
	var input=getobj("eformdata_" + ModelID);
	var model=input.value.toJson();
	//model.Convert=true;	
	model=model.get("eformdata_" + ModelID)	
	var data=model.get(index);	
	//alert(index);
	data.foreach(function(e)
	{
		var ctrl = form[e];		
		if(!ctrl){return;}		
		if(typeof(data[e])=="object")
		{
			var node=data[e];			
			//if(!node.append){node=new eJson(node);}
			//node.Convert=true;
			ctrl.value= "{\"" + e + "\":" + node.toJson() + "}";
			//alert(node.toJson());
			JsonToTable(data[e],e.replace("eformdata_","eformlist_"));
		}		
		else
		{
		
			if(typeof(e)=="string")
			{
				
				if(ctrl.tagName)
				{
					var type=Attribute(ctrl,"type").toLowerCase();
					if(type=="checkbox" || type=="radio")//只有一个选项
					{
						var _tmp="," + data[e].decode() + ",";
						if(_tmp.indexOf("," + ctrl.value + ",")>-1)
						{
							ctrl.checked=true;
						}
						return;
						//alert(e + "::" + ctrl.tagName + "::" + ctrl.length + "::" + type);
					}				
					ctrl.value= data[e].decode();					
					if(ctrl.onchange)
					{
						$(ctrl).trigger("change");
					}
					var etype=Attribute(ctrl,"etype").toLowerCase();
					if(etype=="singleuser" && ctrl.value.length>0 && ctrl.name.toLowerCase().indexOf("_text")>-1)
					{
						//alert($(ctrl).parent().text() + "::" + ctrl.value + "::" + ctrl.name  );
						$(ctrl).parent().find("p").text(ctrl.value);
					}
					if(etype=="label" && ctrl.value.length>0)
					{
						var onext = ctrl.nextElementSibling||ctrl.nextSibling;		
						if(data[e+"_Text"])
						{
							onext.innerHTML=data[e+"_Text"].decode();
							ctrl.setAttribute("text",data[e+"_Text"].decode());
						}
						else
						{
							onext.innerHTML=ctrl.value;
						}
						//onext.innerHTML=ctrl.value;
					}
					if(etype=="html" && ctrl.value.length>0)
					{
						KE.html(ctrl.id, ctrl.value);
						//alert(etype + "::" + ctrl.value + "::" + ctrl.id);
					}
					//alert(etype + "::" + ctrl.value);
					if(etype=="file" && ctrl.value.length>0)
					{
						var frame=getobj("frm" + ctrl.id );
						if(frame)
						{
							var src=frame.getAttribute("src");
							if(src.toLowerCase().indexOf("act=")==-1)
							{
								src+="&act=finsh";
							}
							src+="&file=" + ctrl.value;
							//alert(src);
							//alert(ctrl.id + "::" + data[e]);
							frame.src=src;
						}
					}
				}
				else
				{
					var type=Attribute(ctrl[0],"type").toLowerCase();
					var _tmp="," + data[e].decode() + ",";
					for(var i=0;i<ctrl.length;i++)
					{
						if(_tmp.indexOf("," + ctrl[i].value + ",")>-1)
						{
							ctrl[i].checked=true;
						}
					}
				}
			}
		}
	});
	
	eDataTable_Init();
}
//OK
function form_delete(obj,ModelID,delText)
{
	if(!delText){delText="删除";}
	var Prefix="M" + ModelID + "_";
	Prefix="";
	if(!confirm("确认要" + delText + "吗？")){return;}
	
	var tr=getParent(obj,"tr");
	if(tr.getAttribute("eRowID")==null)
	{
		tr=getParent(tr.parentNode,"tr");
	}
	//alert(tr.getAttribute("eRowID"));
	//return;
	var tbody=getParent(tr,"tbody");
	var trs=tbody.getElementsByTagName("tr");
	//var index=0;
	//for(i=0;i<trs.length;i++){if(trs[i]== tr){index= i;}}
	var index=tr.Index();
	
	var input=getobj("eformdata_" + ModelID);
	
	var model=input.value.toJson();
	//model.Convert=true;

	
	var _model=model.get("eformdata_" + ModelID);
	_model=_model[index];
	

	if(_model[Prefix + "ID"].length==0)
	{
		_model=model.get("eformdata_" + ModelID)
		_model.remove(index);
		tbody.removeChild(tr);
	}
	else
	{
		_model[Prefix + "Delete"]="true";		
	
		tr.style.display="none";
	}
	//更新顺序号
	var otable=getobj("eformlist_" + ModelID);	
	var otfoot=otable.getElementsByTagName("tfoot")[0];
	var otr=otfoot.getElementsByTagName("tr")[0].cloneNode(true);
	var otds=otr.getElementsByTagName("td");
	var row_index=-1;
	for(var i=0;i<otds.length;i++)
	{
		if(otds[i].innerHTML.toLowerCase().indexOf("row:index")>-1)
		{
			row_index=i;
			break;
		}
	}
	if(row_index>-1)
	{
		$(tbody).find("tr:visible").each(function(i,elem){
			$(this).find("td:eq(" + row_index + ")").html(i + 1); 
		});
	}
		
	//var count=getobj("count_" + ModelID);
	var count;
	if(form_area)
	{
		count=form_area.find("#count_" + ModelID);
		count=count.length>0 ? count[0] : count=getobj("count_" + ModelID);
	}
	else
	{
		count=getobj("count_" + ModelID);
	}
	if(count)
	{
		
		count.value= $(tbody).find("tr:visible").length;// tbody.children.length;
	}
	input.value=model.toJson();	

	//回调函数-删除
	if(typeof(submodel_onChange)=="function")
	{
		var list_trs=$("#eformlist_" + ModelID + " > tbody > tr");
		submodel_onChange(ModelID,list_trs,tbody);
	}
}
//OK
function form_save(ModelID)
{
	
	var frm= document.forms["form_" + ModelID];
	if(!frm){layer.msg("表单form_" + ModelID + "不存在!");return false;}	
	var Prefix="M" + ModelID + "_";
	Prefix="";
	var _back=eCheckform(frm);	
	if(!_back){return false;}
	var input=getobj("eformdata_" + ModelID);
	//alert(input.value);
	var model=input.value.toJson();	
	//model.Convert=true;
	
	//alert(model.toJson());
	//return;
	var _data=model.get("eformdata_" + ModelID);

	var index=parseInt(frm[Prefix + "Index"].value);
	var table=getobj("eformlist_" + ModelID);
	var tbody=table.getElementsByTagName("tbody")[0];

	var obj= formToJson(frm);
	//alert(new eJson(obj).toJson());
	
	var tfoot=table.getElementsByTagName("tfoot")[0];
	var otr=tfoot.getElementsByTagName("tr")[0].cloneNode(true);
	var otds=otr.getElementsByTagName("td");
	if(index>-1)//替换
	{
		_data[index]=obj;
		
		//var tr=tbody.getElementsByTagName("tr")[index];
		var tr=tbody.children[index];
		//tr,td 不可以使用getElementsByName  getElementById 所以要从TD 去读JSON数据，而不是从Json数据到TD
		//alert(tr.outerHTML);
		
		
		 $(tr).find("[name]").each(function(i,elem){
			var name=elem.getAttribute("name");
			if(name)
			{
				var _opar= $(otr).find("[name='" + name + "']").get(0);
				name=name.replace("td_","");
				if(obj[name+"_Text"])
				{
				    elem.innerHTML = obj[name + "_Text"].decode().replace(/\\n/g, " ");
				}
				else
				{
					if(obj[name])
					{
						
						if(_opar.innerHTML.toLowerCase().indexOf("data:")==-1)
						{
						    elem.innerHTML = obj[name].decode().replace(/\\n/g, " ");
						}
						else
						{
						    elem.innerHTML = _opar.innerHTML.replace(/{data:.*?}/gi, obj[name].decode().replace(/\\n/g, " "));
						}
						
					}
					else
					{
						if(name.length>0 && _opar.innerHTML.toLowerCase().indexOf("data:")> -1){elem.innerHTML="";}
					}
				}
			}
	     });
		

		/*
		var tds=tr.getElementsByTagName("td");
		for(var i=0;i<tds.length;i++)
		{
			var name=tds[i].getAttribute("name").replace("td_","");//正
			if(name)
			{
				if(obj[name+"_Text"]){tds[i].innerHTML=obj[name+"_Text"].decode();continue;}
				
				if(obj[name])
				{
					if(otds[i].innerHTML.toLowerCase().indexOf("data:")==-1)
					{
						tds[i].innerHTML=obj[name].decode();
					}
					else
					{
						tds[i].innerHTML=otds[i].innerHTML.replace(/{data:.*?}/gi,obj[name].decode());
					}
				}
				else
				{
					tds[i].innerHTML="";
				}
			}
		}
		*/
	}
	else //添加
	{
		_data.append(obj);

		$(otr).find("[name]").each(function(i,elem){
			var name=elem.getAttribute("name");
			if(name)
			{
				name=name.replace("td_","");
				if(obj[name+"_Text"])
				{
				    elem.innerHTML = obj[name + "_Text"].decode().replace(/\\n/g, " ");
				}
				else
				{
					if(obj[name])
					{
						if(elem.innerHTML.toLowerCase().indexOf("data:")==-1)
						{
						    elem.innerHTML = obj[name].decode().replace(/\\n/g, " ");
						}
						else
						{
						    elem.innerHTML = elem.innerHTML.replace(/{data:.*?}/gi, obj[name].decode().replace(/\\n/g, " "));
						}
						
					}
					else
					{
						//elem.innerHTML="";
						//alert($(tbody).find("tr").length);
						//更新顺序号
						elem.innerHTML=elem.innerHTML.replace(/{row:index}/gi,$(tbody).children("tr").length + 1);
					}
				}
			}
		});		
		/*
		for(var i=0;i<otds.length;i++)
		{
			var name=otds[i].getAttribute("name").replace("td_","");
			if(name)
			{
				if(obj[name+"_Text"]){otds[i].innerHTML=obj[name+"_Text"].decode();continue;}
				if(obj[name])
				{
					
					if(otds[i].innerHTML.toLowerCase().indexOf("data:")==-1)
					{
						
						
						otds[i].innerHTML=  obj[name].decode();
					}
					else
					{
						otds[i].innerHTML=otds[i].innerHTML.replace(/{data:.*?}/gi,obj[name].decode());
					}
				}
				else
				{
					otds[i].innerHTML="";
				}
			}
		}
		*/
		tbody.appendChild(otr);
		//alert(table.parent);
		if(table.parent){Table_Init_Tbody(table.parent);}
		
	}
	//alert(model.toJson());
	input.value=model.toJson();
	//form_cancel(ModelID);
	//var count=getobj("count_" + ModelID);
	var count;
	if(form_area)
	{
		count=form_area.find("#count_" + ModelID);
		count=count.length>0 ? count[0] : count=getobj("count_" + ModelID);
	}
	else
	{
		count=getobj("count_" + ModelID);
	}
	if(count)
	{
		count.value=$(tbody).find("tr:visible").length;// tbody.children.length;
	}
	//回调函数-添加修改
	if(typeof(submodel_onChange)=="function")
	{
		var list_trs=$("#eformlist_" + ModelID + " > tbody > tr");
		submodel_onChange(ModelID,list_trs,tbody);
	}


	/*
	
	setTimeout(function(){
	eDataTable_Init();
	if(table.parent){Table_Init_Tbody(table.parent);}
	//alert(table.id);
	},500);
	
	if(!table.parent)
	{
		eDataTable_Init();
	}
	else
	{
		Table_Init_Tbody(table.parent);
	}
	*/
	return true;
}


//OK

/*
var query="";
	if(typeof(OpenFillSelectDlg_before)=="function")
	{
		var _back=OpenFillSelectDlg_before(modelID);
		if(typeof(_back)=="object")
		{
			//if(!_back.result){return;}
			query=_back.query;
			if(query.length>0)
			{
				if(query.indexOf("&")!=0){query="&" + query;}			
			}
		}
	}
	var url="../Plugins/FillSelectData.aspx?modelid=" + modelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "");
	if(query.length>0){url+=query;}
	*/



function getAddHTML(ModelID,_url)
{


	var html="";	
	
	//eval("var modelhtml=window.ModelHTML_" + ModelID + ";");
	var modelhtml=eval("window.ModelHTML_" + ModelID.replace(/-/gi,"") );
	
	if(modelhtml)
	{
		html=modelhtml;
		//document.title="get";
	}
	else
	{
		//var url="?modelid=" + ModelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "")  + "&act=addsub";
		
		var url="model.aspx?modelid=" + ModelID + "&act=addsub";
		if(_url){url=_url;}
		
		if(typeof(getAddHTML_before)=="function")
		{
			
			var _back=getAddHTML_before(ModelID);
			if(typeof(_back)=="object")
			{
				//if(!_back.result){return;}
				if(_back.query.length>0)
				{
					//url+= url.indexOf("?") > -1 ? "&" + _back.query : "?"  + _back.query ;
					var query=_back.query.replace("?","");
					var arr=query.split("&");
					for(var x=0;x<arr.length;x++)
					{
						var arr2=arr[x].split("=");
						if(arr2.length==2)
						{
							url=url.addquerystring(arr2[0],arr2[1]);
						}
					}
				}
			}
		}
		if(url.indexOf("pid=")==-1)
		{
			var id=document.location.href.getquerystring("id");
			if(id.length>0)
			{
				url+= url.indexOf("?") > -1 ? "&pid=" + id : "?pid="  + id ;
			}
		}
		
		var debug=document.location.href.getquerystring("debug");
		if(debug.length>0) url+= "&debug=" + debug; 
		url+= "&t=" + now();
		html=PostURL(url);
		eval('window.ModelHTML_'+ ModelID.replace(/-/gi,"") +'=html;');
		//document.title="set";
	}
	return html;
}

function form_init(ModelID)
{

	var frm= document.forms["form_" + ModelID];
	if(!frm){layer.msg("表单form_" + ModelID + "不存在!");return false;}
	
	var executenames="";
	var elements=frm.elements;
	
	for(var i=0; i < elements.length; i++)
	{
		if(executenames.indexOf(elements[i].name.toLowerCase())>-1){continue;}
		if(elements[i].getAttribute("Exclude")!=null || elements[i].getAttribute("exclude")!=null){continue;}
		if(elements[i].tagName.toLowerCase()=="fieldset"){continue;}
		if(elements[i].name.toLowerCase()=="index"){continue;}
		if(elements[i].name.toLowerCase().indexOf("_index") > -1 ){continue;}
		if(elements[i].name.toLowerCase()=="page"){continue;}
		
		//var fieldname = elements[i].getAttribute("fieldname");
		
		var defaultvalue = elements[i].getAttribute("defaultvalue");
		
		if(defaultvalue==null){defaultvalue="";}
		if(elements[i].name.indexOf("eformdata_")>-1)
		{
			
			var table=getobj(elements[i].name.replace("eformdata_","eformlist_"));
			if(table)
			{
				if(table.getAttribute("reinit")=="false"){continue;}
				var tbody=table.getElementsByTagName("tbody")[0];			
				var trs=tbody.getElementsByTagName("tr");					
				for(var j=trs.length;j > 0;j--)
				{
					trs[0].parentNode.removeChild(trs[0]);
				}
			}
			elements[i].value='{"' + elements[i].name + '":[]}';
		}
		else
		{
			var etype = elements[i].getAttribute("etype");
			if(etype==null){etype="";}
			//alert(etype + defaultvalue);
			if(defaultvalue.length>0 && etype != "checkbox" && etype!="radio")
			{
				elements[i].value = defaultvalue;
			}
			else
			{
				if(etype != "checkbox" && etype!="radio")
				{
					elements[i].value = "";
				}
			}
			if(etype=="autoselect" && elements[i].name.indexOf("all")==-1)
			{
				
				var tmp;
				for(var j=2;j<10;j++)
				{
					tmp=getobj(elements[i].name + "_" + j);
					

					if(!tmp){break;}
					tmp.parentNode.removeChild(tmp);
				}
				tmp=getobj(elements[i].name + "_1");
				tmp.value="";
			}
			if(etype=="file")
			{
				var frame=getobj("frm" + elements[i].name);
				var url=frame.getAttribute("src");
				url=url.removequerystring("act");
				url=url.removequerystring("file");
				
				frame.src=url;
			}
			if(etype=="html"){KE.html(elements[i].name,defaultvalue);}
			if(etype=="checkbox" || etype=="radio")
			{
				executenames+="," + elements[i].name.toLowerCase() + ",";
				var chks=document.getElementsByName(elements[i].name);
				for(var j=0; j < chks.length; j++)
				{
					chks[j].checked=(defaultvalue.length > 0 && defaultvalue.indexOf(chks[j].value) > -1 ? true : false);
				}

			}
			
		}
	}
}
//OK
function submitform(frm)
{	
	if(typeof(frm)=="string"){frm= document.forms[frm];}
	if(!frm){return;}
	if(frm.onsubmit()!=false)
	{
		frm.submit();
		var loading= document.createElement("div");
		loading.className="eform_loading";
		document.body.appendChild(loading);
	}
}
//删除HTML标签
function removeHTMLTag(str){
    return str.replace(/<\/?.+?\/?>/g,'');
}
function saveform(ModelID)
{
	var frm= document.forms["form_" + ModelID];
	if(!frm){layer.msg("表单form_" + ModelID + "不存在!");return;}
	var frmobj= formToJson(frm);
	var obj=new eJson2([]);
	obj.append(frmobj);	
	
	var model=new eJson2();
	model.append("ModelID",ModelID);	
	model.append("eformdata_" + ModelID,obj);
	
	//alert(JSON.stringify(model));
	var url="?act=savedraft";	
	if(typeof(AppItem)=="string" && AppItem.length > 0){url+="&AppItem=" + AppItem;}
	if(typeof(ModelID)=="string" && ModelID.length > 0){url+="&ModelID=" + ModelID;}	
	$.ajax({
		type: "post",
		async: false,
		data:{"data":model.toJson()},
        url:url,
        dataType: "html",
        success: function (html)
		{
			layer.msg("保存成功!");
        }
    });
};
function packform(ModelID,ajax)
{
    //var _value = "1\"23";
    //alert(_value + "::" + _value.trim().encode());
    
    //return;


	if(Attribute(frmaddoredit,"finsh")=="true"){return;}
	
	var frm= document.forms["form_" + ModelID];
	if(!frm){layer.msg("表单form_" + ModelID + "不存在!");return;}
	var _back=eCheckform(frm);
	if(!_back){return;}	

//return;
	//alert($(frm).find(".excelTable").length);
	//return;
	//clearPack($(frm));//清除合并标记

/*
	$(frm).find(".excelTable").each(function(i,el){
		if($(this).attr("exclude")=="undefined" || $(this).attr("exclude")!="true")
		{
			form_area=$(this).parent();
			excel_pack($(this).attr("id").replace("eformlist_",""));
		}
	});	


	//从没有下拉的列表往上汇总
	var ctrls = new Array();
	$(frm).find(".divsubList").each(function(i,el){	
		$(this).attr("pack","false");
		if($(this).find(".divsubList").length==0)
		{
			ctrls.push($(this));
		}
	});
	if(ctrls.length>0){eachItems(ctrls);}
	*/


	

	//return false;
	//alert($(frm).find(".excelTable").length);
	var frmobj= formToJson(frm);	
	
	//alert(frmobj.toJson());//20250224
	//return;
	var obj=new eJson2([]);
	obj.append(frmobj);
	//alert(obj);
	//alert(ModelID);
	//var xx=$(frm).serialize()
	//alert(xx);
	//return;
	
	//var str='{"eformdata_' + ModelID + '":[]}';
	//var model=str.toJson();	
	//model["eformdata_"+ ModelID]=obj;

	//alert(obj.toJson());
	//return;
	

	
	//var model=new eJson();
	//model.Convert=true;
	//model.append("ModelID",ModelID);
	//model.append("eformdata_" + ModelID,obj);	
	//alert("xx:" + model.toJson());
	
	
	var model=new eJson2();
	model.append("ModelID",ModelID);	
	model.append("eformdata_" + ModelID,obj);
	var input=getobj("eformdata_" + ModelID);	
	
	//alert(model.toJson());
	//return;
	input.value= model.toJson();
	
	if (typeof localStorage === 'object') {
	    var act = document.location.href.getquerystring("act");
	    if (act == "add") {
	        var appitem = document.location.href.getquerystring("appitem");
	        localStorage.removeItem(appitem);
	    }
	}
	//$("#eformdata_result").val(model.toJson());
	//alert(model.toJson());
	//alert(obj.toJson());
	//return;
	//alert(ajax);
	//return;
	if(ajax)
	{
	
		//alert("ajax" + $("#frmaddoredit").serialize());
		//if(!frmaddoredit["ajax"]){var input= document.createElement("input");input.type="hidden";input.name="ajax";input.value="true";frmaddoredit.appendChild(input);}
		$.ajax({
			type: 'post',
			async: false,
			url: $("#frmaddoredit").attr("action"),			
			data: "ajax=true&" + $("#frmaddoredit").serialize(),
			dataType: "json",
			success: function(data)
			{
				//alert(JSON.stringify(data));
				//layer.alert(data,{title:"提示" ,area: ['800px', '600px']});
				//alert(data);
				var json=new eJson2(data);
				//alert(typeof(parent.postback) + "::" + _json.toJson());
				//return;
				if(typeof(parent.postback)=="function")
				{
					parent.postback(data);
					return;
				}


				//data=eJson(data);
				if(parseBool(data.success))
				{
					//var json=eJson(data);
					//json.Convert=true;
					if(frmaddoredit["id"] && frmaddoredit["id"].value){frmaddoredit["id"].value = json["id"];}
					if(frmaddoredit["ID"] && frmaddoredit["ID"].value){frmaddoredit["ID"].value = json["id"];}
					if(frm["id"] && frm["id"].value){frm["id"].value = json["id"];}
					if(frm["ID"] && frm["ID"].value){frm["ID"].value = json["id"];}
					//layer.alert( json["id"] + "::" +  json.toJson(),{title:"提示" ,area: ['800px', '600px']});
					//alert(json.toJson());
				
					//var data=json.get("data").get(0);
					//data.Convert=true;		
					
					//alert( json["id"] + "::" +json.id );
					
					//form_init(ModelID);
					//input.value=data.toJson();
					//form_load(ModelID);
					
					//layer.msg("保存成功!");
					//if(frm["id"]){frm["id"].value=json.id;}
					//if(frm["ID"]){frm["ID"].value=json.id;}

					if(top!=self)//Frame打开
					{	
							if(parent.arrLayerIndex.length>0 || 1>-0)
							{
								parent.layer.msg(data.message);
								//$(parent.document).find(".excelTable tbody tr:visible"); //layui-layer1
								var index = parent.layer.getFrameIndex(window.name);	
								
								$(parent.document).find("#layui-layer-shade" + index).hide();								
								$(parent.document).find("#layui-layer" + index).hide();
								//alert(index);
								//var _count=parent.arrLayerIndex.length;
								var _count=$(parent.document).find(".eFrameTab dt a.cur").length;
								//alert(_count + "B");
								//parent.document.title=_count;
								setTimeout(function(){
									parent.layer.close(parent.arrLayerIndex.pop());
									//parent.document.location.assign(parent.document.location.href);
									if(_count==1)//eframe打开再打开判断有误
									{
										var curtab = $(parent.document).find(".eFrameTab dt a.cur");										
										var doc = $(parent.document).find(".eFrameTab dd iframe:eq(" + curtab.index() + ")").get(0).contentWindow;
										if (doc.treefrommode == "tree") {
										    doc.TreeModelUpdate();
										}
										else {
										    doc.Search();
										}
									}
									else
									{
										var win=$(parent.document).find("#layui-layer-iframe" + parent.arrLayerIndex[parent.arrLayerIndex.length-1]);										
										if(win.length>0)
										{
										    if (win.get(0).contentWindow.treefrommode == "tree") {
										        win.get(0).contentWindow.TreeModelUpdate();
										    }
										    else {
										        win.get(0).contentWindow.Search();
										    }
										}
										else
										{
											if(parent.treefrommode=="tree") {
											    parent.TreeModelUpdate();
											}
											else {
												parent.Search();
											}
										}
									}
 									//doc.location.assign(doc.location.href);
									//if(parent.arrLayerIndex.length==0)parent.Search();
								},1000);
								
							}
					}
					else
					{
						//alert(66);
					}
					/*
					layer.msg(data.message, {
					time: 0 //20s后自动关闭
					,shade: 0.2 //透明度
					,shadeClose: false //点击遮罩关闭层
					
					,btn: ["添加新记录","继续修改","返回"]
					,yes:function(index,layero)
					{
						
						//layer.msg("添加" + ModelID);
						input.value="";
						form_init(ModelID);

						if(frm["id"]){frm["id"].value="";}
						if(frm["ID"]){frm["ID"].value="";}
						layer.close(index);
					}
				    ,btn2:function(index,layero)
					{
						if(frm["id"]){frm["id"].value=json.id;}
						if(frm["ID"]){frm["ID"].value=json.id;}
						//layer.msg("修改");
					}
					,btn3:function(index,layero)
					{
						//layer.msg("返回" + frmaddoredit["fromurl"].value);
						//document.location.assign(frmaddoredit["fromurl"].value);
						if(top!=self)//Frame打开
						{	
							if(parent.arrLayerIndex.length>0)
							{

								parent.layer.close(parent.arrLayerIndex.pop());
								if(parent.arrLayerIndex.length==0)parent.Search();
							}
						}						
					}
				  	});
					*/
				}
				else
				{
					
					//alert("失败!");
				}

				
			}
		});
	}
	else
	{
		//var btn=getEventObject();
		
		frmaddoredit.setAttribute("finsh","true");
		frmaddoredit.submit();
		/*
		return;
		var loading= document.createElement("div");
		loading.className="eform_loading";
		document.body.appendChild(loading);
		*/
	}
	//return;
}
function removeAddNew(obj,ModelID)
{	
	var dl=$(obj).parents("dl:first");
	var list=dl.parent();//div
	var inputid=dl.find("input[postname='ID']");
	var id=inputid.val();
	if(id.length==0)
	{
		dl.remove();
	}
	else
	{
		var _back=confirm('确认要删除吗？');
		if(!_back){return;}	
		dl.find("input[postname='Delete']").val("true");
		dl.find("input[id*='count_']").remove();
		dl.hide();
		//addPack(dl);
	}
	ItemToJson(list);	
}

function addNew(obj,ModelID)
{
	form_area=$(obj).parents("dd:first");
	var html=getAddHTMLN(ModelID);	
	//$(obj).before(html);	
	var list=$(obj).parent().find("#eformlist_" + ModelID + ":first");
	list.append(html);
	Resize_eControl(list);
	//alert(list.find(">dl").length + "::" + list.find(">dl:last").index());
	var _row=list.find(">dl").length;	
	list.find(">dl:last").find("input[type='radio']").each(function(i,el)
	{
		//alert(el.value + "::" + el.name);
		var _name=$(this).attr("name");
		if(_name.indexOf("{row}")>-1 )
		{
			_name=_name.replace("{row}","row_" + _row + "_");
			$(this).attr("name",_name);
		}
	});
	
	ItemToJson(list);
	//alert(html);
	/*
	var url=document.location.href;
	url=url.removequerystring("id");
	url=url.removequerystring("act");
	url=url.addquerystring("ModelID",ModelID);
	url=url.addquerystring("act","addsub");	
	if(typeof(getAddHTML_before)=="function")
	{			
		var _back=getAddHTML_before(ModelID);
		if(typeof(_back)=="object")
		{
			//if(!_back.result){return;}
			if(_back.query.length>0)
			{
				url+= url.indexOf("?") > -1 ? "&" + _back.query : "?"  + _back.query ;
			}
		}
	}
	if(url.indexOf("pid=")==-1)
	{
		var id=document.location.href.getquerystring("id");
		if(id.length>0)
		{
			url+= url.indexOf("?") > -1 ? "&pid=" + id : "?pid="  + id ;
		}
	}
		
	var debug=document.location.href.getquerystring("debug");
	if(debug.length>0) url+= "&debug=" + debug; 
	url+= "&t=" + now();
	*/
	//alert(ModelID + "::" + url);
}
function eachItems(arr)
{
	var ctrls = new Array();
	//for(p in arr)
	for(var i=0;i<arr.length;i++)
	{
		var div=arr[i];//arr[p];
		eachItem(div);
		var pdiv=div.parents(".divsubList:first");
		if(pdiv.length>0){ctrls.push(pdiv);}
	}
	if(ctrls.length>0){eachItems(ctrls);}
}
function eachItem(div)//div
{
	//alert(div.html());
	var pack=div.attr("pack");
	if(pack=="true"){return;}
	form_area=div;
	
	ItemToJson(div);
	div.attr("pack","true");
	//alert(div.parents(".divsubList:first").length);
	//if(div.parents(".divsubList:first").length>0)
	//{
		//var pdiv=div.parents(".divsubList:first");
		//eachItem(pdiv);
		//alert(pdiv.length);
		//alert(pdiv.attr("id") + "::" + pdiv.find("input:not([pack])").length + "::" +  pdiv.find("input").not("[pack]").length);
	//}
}

function ItemToJson(div) //div
{
	var _modelid=div.attr("id").replace("eformlist_","");
	var txtid=div.attr("id").replace("eformlist_","eformdata_");
	var _data="[]".toJson();	
	//_data.Convert=true;
	//alert(div.find(">dl>dd").length + "X");
	//div.find(">dl>dd").each(function(j,elem){
	if(div.parent().find("#count_" + _modelid).length>0)
	{
		div.parent().find("#count_" + _modelid).val(div.children("dl").children("dd").length);
	}
	div.children("dl").children("dd").each(function(j,elem){
		var _item= nodeToJson(elem);	
		if(_item.toJson().length>2)
		{
			_data.append(_item);
		}
	});
	//alert(_data.toJson());
	
	var _model=new eJson2();
	
	//_model[txtid]=_data;
	_model.append(txtid,_data);
	//$("#" + txtid).val(_model.toJson());
	//alert(_model.toJson());
	div.prevAll("#" + txtid).val(_model.toJson() );
}

//OK
function clearPack(node)
{
	var inputs=$(node).find("input[pack]");
	for(var i=0;i < inputs.length;i++)
 	{
		 $(inputs[i]).removeAttr("pack");
	}
	var selects=$(node).find("select[pack]");
	for(var i=0;i < selects.length;i++)
 	{
		 $(selects[i]).removeAttr("pack");
	}
	var textareas=$(node).find("textarea[pack]");
	for(var i=0;i < textareas.length;i++)
 	{
		 $(textareas[i]).removeAttr("pack");
	}
}
function addPack(node)
{
	var inputs=$(node).find("input");
	for(var i=0;i < inputs.length;i++)
 	{
		 $(inputs[i]).attr("pack","true");
	}
	var selects=$(node).find("select");
	for(var i=0;i < selects.length;i++)
 	{
		 $(selects[i]).attr("pack","true");
	}
	var textareas=$(node).find("textarea");
	for(var i=0;i < textareas.length;i++)
 	{
		 $(textareas[i]).attr("pack","true");
	}
}

function nodeToJson(node)
{
	var el=$(node)[0];	
	if(el.tagName!="DD"){clearPack(node);} //不能清除整个子模块内容
	var tfoot=$(node).find("tfoot");
	if(tfoot.length>0){addPack(tfoot);}
	var json=new eJson2();
	

	
	//var inputs=node.getElementsByTagName("input");
	var inputs=$(node).find("input:not([pack])");
	//alert(inputs.length);
 	for(var i=0;i < inputs.length;i++)
 	{
		var type= inputs[i].getAttribute("type").toString().toLowerCase();
		//if(inputs[i].getAttribute("Exclude")!=null || inputs[i].getAttribute("exclude")!=null){continue;}
		if(type == "submit" || type == "button" || type == "reset"){continue;}
		var postname=inputs[i].name;
		//alert(postname);
		if(inputs[i].getAttribute("postname")){postname=inputs[i].getAttribute("postname");}
		if(postname.length==0){continue;}	
		if(postname.toLowerCase().indexOf("eformdata_")==-1)
		{
			
		 	$(inputs[i]).attr("pack","true");
			//inputs[i].style.borderColor="#ff0000";
		}
		//if(postname.toLowerCase().indexOf("eformdata_")==-1){ $(inputs[i]).attr("pack","true");}
		//json["name"]=postname;
		var trimtype=inputs[i].getAttribute("trimtype") || "0";
		var value = postname.toLowerCase().indexOf("eformdata_") > -1 ? inputs[i].value.autotrim(trimtype) : inputs[i].value.autotrim(trimtype).encode();
		if (type == "checkbox" && $(elements[i]).attr("etype") == "switcher") { continue; }
		if((type == "radio" || type=="checkbox") && inputs[i].checked==false){value="";}
		
		if(postname.toLowerCase().indexOf("eformdata_")>-1) //子模块对象 
		{

			var _json=value.toJson();
			_json=_json.get(postname);
			
			//_json.Convert=true;
			//json[postname]=_json;
			json.append(_json);
			
		}
		else
		{
			
			if(!json[postname])
			{
				json[postname] = value;
			}
			else
			{
				if(value.length>0){json[postname] += "," + value;}
			}
			if(inputs[i].getAttribute("type")=="hidden" && inputs[i].getAttribute("text"))
			{
				json[postname + "_Text"] = inputs[i].getAttribute("text");
			}
		}		
		//inputs[i].name="";
 	}

 	//var selects=node.getElementsByTagName("select");
	var selects=$(node).find("select:not([pack])");
	for(var i=0;i < selects.length;i++)
	{
		$(selects[i]).attr("pack","true");
		var postname=selects[i].name;
		if(selects[i].getAttribute("postname")){postname=selects[i].getAttribute("postname");}
		if(postname.length==0){continue;}
		var value=selects[i].value.trim().encode();
		json[postname] = value;
		//selects[i].name="";
	}
	//var textareas=node.getElementsByTagName("textarea");
	var textareas=$(node).find("textarea:not([pack])");
	for(var i=0;i < textareas.length;i++)
	{
		//$(textareas[i]).attr("pack","true");
		var postname=textareas[i].name;
		if(textareas[i].getAttribute("postname")){postname=textareas[i].getAttribute("postname");}
		if(postname.length==0){continue;}
		if(postname.toLowerCase().indexOf("eformdata_")==-1)
		{
			$(textareas[i]).attr("pack","true");
			//textareas[i].style.borderColor="#ff0000";			
		}
		//json["name"]=postname;
		//if(postname.toLowerCase().indexOf("eformdata_")==-1){ $(textareas[i]).attr("pack","true");}
		var trimtype=textareas[i].getAttribute("trimtype") || "0";
		var value=  postname.toLowerCase().indexOf("eformdata_") > -1 ?  textareas[i].value.autotrim(trimtype) : textareas[i].value.autotrim(trimtype).encode();
		if(postname.toLowerCase().indexOf("eformdata_")>-1) //子模块对象 
		{
			var _json=value.toJson();
			_json=_json.get(postname);
			//_json.Convert=true;
			//json[postname]=_json;
			json.append(_json);
		}
		else
		{
			json[postname] = value;
		}
		//textareas[i].name="";
	}
	$(node).find("[name^='eformdata_']").each(function(j,elem){
			var _json=$(this).val().toJson();
			_json=_json.get($(this).attr("name"));
			json.append($(this).attr("name"),_json)										
			//alert($(this).val());	   
		//excel_pack($(this).attr("id").replace("eformlist_",""));
	});
	addPack(node);
	return json;
}
//OK
function TableToJson(ModelID)
{
	var model=new eJson2([]);
	//model.Convert=true;
	//var table=getobj("eformlist_" + ModelID);
	var table;
	if(form_area)
	{
		table=form_area.find("#eformlist_" + ModelID);
		table=table.length>0 ? table[0] : getobj("eformlist_" + ModelID);
	}
	else
	{
		table=getobj("eformlist_" + ModelID);
	}
	
	
	var tbody=table.getElementsByTagName("tbody")[0];
	var trs=tbody.getElementsByTagName("tr");
	
	for(var j=0;j < trs.length;j++)
 	{
  		model.append("eformdata_" + ModelID,nodeToJson(trs[j]));
	}
	//var input=getobj("eformdata_" + ModelID);
	var input;
	if(form_area)
	{
		input=form_area.find("#eformdata_" + ModelID);		
		input=input.length>0 ? input[0] : getobj("eformdata_" + ModelID);
	}
	else
	{
		input=getobj("eformdata_" + ModelID);
	}
	
	input.value=model.toJson();
}
function formToJson(frm)//eJson2
{
	
	if(typeof(frm)=="string"){frm= document.forms[frm];}
	var elements=frm.elements;
	//alert(elements.length);
	//var json=new Object();
	clearPack($(frm));
	$(frm).find(".excelTable").each(function(i,el){
		if($(this).attr("exclude")=="undefined" || $(this).attr("exclude")!="true")
		{
			//alert($(this).attr("id"));
			form_area=$(this).parent();			
			excel_pack($(this).attr("id").replace("eformlist_",""));
		}
	});	

	//alert(2);

	
	var ctrls = new Array();
	$(frm).find(".divsubList").each(function(i,el){	
		$(this).attr("pack","false");
		if($(this).find(".divsubList").length==0)
		{
			ctrls.push($(this));
		}
	});
	
	if(ctrls.length>0){eachItems(ctrls);}
	

	//alert(elements.length);
	var json=new eJson2();
	for(var i=0; i < elements.length; i++)
	{
		
		var pack=$(elements[i]).attr("pack");
	
		if(pack=="true"){continue;}
		//alert(elements[i].name + "::" + pack);
		//continue;
		if(elements[i].getAttribute("Exclude")!=null || elements[i].getAttribute("exclude")!=null){continue;}		
		if(elements[i].tagName.toLowerCase()=="fieldset"){continue;}
		if(elements[i].name.toLowerCase()=="index"){continue;}
		if(elements[i].name.toLowerCase().indexOf("_index") > -1 ){continue;}
		if(elements[i].name.toLowerCase()=="page"){continue;}
		if(elements[i].name.toLowerCase().indexOf("_result") > -1 ){continue;}
		if(elements[i].name.length==0){continue;}
		//$(document.body).append(elements[i].name + "<br>");
		
		
		var type= "";
		if(elements[i].getAttribute("type")){type=elements[i].getAttribute("type").toString().toLowerCase();}
		
		if(type.length==0)
		{
			if(elements[i].tagName.toLowerCase()!="select" && elements[i].tagName.toLowerCase()!="textarea")
			{
				continue;
			}
		}		
		if(type == "submit" || type == "button" || type == "reset"){continue;}
		if (type == "checkbox" && $(elements[i]).attr("etype") == "switcher") { continue; }
		if((type == "radio" || type=="checkbox") && elements[i].checked==false){continue;}
	
		var value=elements[i].value;
		var trimtype=elements[i].getAttribute("trimtype") || "0";
		if(elements[i].tagName.toLowerCase()=="select" &&  elements[i].getAttribute("multiple")!=null)
		{

			var _tmp="";
			for(var j=0;j< elements[i].options.length;j++)
			{
				if( elements[i].options[j].selected)
				{
					if(_tmp.length>0){_tmp+=",";}
					_tmp+=elements[i].options[j].value;
				}
			}
			value=_tmp;
		}		
		
		if(type=="text" ||  elements[i].tagName.toLowerCase()=="textarea")
		{
			//if(elements[i].name.toLowerCase().indexOf("eformdata_") == -1) value = value.encode64();
		}
		
		if(elements[i].name.toLowerCase().indexOf("eformdata_")>-1) //子模块对象 
		{
			
			var _json=value.toJson();
			//alert("a:" + _json.tostring());
			_json=_json.get(elements[i].name);
			
			//_json.Convert=true;
			//alert("B:" + _json.toJson());
			json.append(elements[i].name,_json);
			json[elements[i].name]=_json;
			//alert(_json.tostring());
			//alert();
			//json.append(elements[i].name,_json);
		}
		else
		{
			
		
			//alert(value + "::" + value.trim().encode());
			value=value.autotrim(trimtype).encode()||"";		
			
			if(!json[elements[i].name])
			{
				//json[elements[i].name] = value;
				if((value.startsWith("[") && value.endsWith("]")) || (value.startsWith("{") && value.endsWith("}")))
				{
					var _json=value.toJson();
					json.append(elements[i].name,_json);
					//alert(value);
				}
				else
				{
					json.append(elements[i].name,value);
				}
			}
			else
			{
				//json.append(elements[i].name,text + "," + value);
				json[elements[i].name] += "," + value;
			}
			//continue;
			//if(elements[i].getAttribute("etype")=="singleuser" && elements[i].name.toLowerCase().indexOf("_text")>-1 )
			//{
				//json[elements[i].name.replace("_t","_T")] = elements[i].value.encode();
			//}
			if(elements[i].getAttribute("etype")=="autoselect" && type=="hidden" && elements[i].name.toLowerCase().indexOf("_all")==-1 )
			{
				var txt="";
				for(var x=1;x<100;x++)
				{
					var tmp=getobj(elements[i].name + "_" + x);
					if(!tmp || tmp.value.length==0){break;}
					if(txt.length>0){txt+=",";}
					txt+=tmp.options[tmp.selectedIndex].text;					
				}
				json[elements[i].name + "_Text"] = removeHTMLTag(txt).encode();
			}
			if(elements[i].tagName.toLowerCase()=="select" && elements[i].selectedIndex > -1)
			{
				if(elements[i].getAttribute("multiple")==null)
				{
					json[elements[i].name + "_Text"] = removeHTMLTag(elements[i].options[elements[i].selectedIndex].text.replace("请选择","")).encode();
				}
				else
				{
					var _tmp="";
					for(var j=0;j< elements[i].options.length;j++)
					{
						if( elements[i].options[j].selected)
						{
							if(elements[i].options[j].value.length>0)
							{
								if(_tmp.length>0){_tmp+=",";}
								_tmp+=removeHTMLTag(elements[i].options[j].text).encode();
							}
						}
					}
					json[elements[i].name + "_Text"] =_tmp;
				}
			}
			//alert(type);
			if(type=="hidden" && elements[i].getAttribute("text"))
			{
				var etype=elements[i].getAttribute("etype");
				if(etype=="label")
				{
					json[elements[i].name + "_Text"] = elements[i].getAttribute("text").encode();
				}
			}
			if(type == "radio" || type=="checkbox")
			{
				if(elements[i].getAttribute("text"))
				{
					if(!json[elements[i].name + "_Text"])
					{
						
						json[elements[i].name + "_Text"] = removeHTMLTag(elements[i].getAttribute("text")).encode();
					}
					else
					{
						json[elements[i].name + "_Text"] += "," + removeHTMLTag(elements[i].getAttribute("text")).encode();
					}
				}
			}
			if(elements[i].name.toLowerCase().indexOf("_text")>-1 && (elements[i].getAttribute("etype")=="singleuser" || elements[i].getAttribute("etype")=="multipleuser"))
			{
				if(!json[elements[i].name.replace("_text","") + "_Text"])
				{
					json[elements[i].name.replace("_text","") + "_Text"] = removeHTMLTag(elements[i].value).encode();
				}
				else
				{
					json[elements[i].name.replace("_text","") + "_Text"] += "," + removeHTMLTag(elements[i].value).encode();
				}
			}
		}		
	}
	//addPack(frm);
	return json;
}
function JsonToTable(data,tableID)
{
    //alert(tableID + "::" + JSON.stringify(data));
	var table=getobj(tableID);	
	var tbody=table.getElementsByTagName("tbody")[0];
	var tfoot=table.getElementsByTagName("tfoot")[0];
	var clsname=table.className;
	data.foreach(function(e)
	{

		if(data[e]["Delete"]=="true") {return;}
		var tr=tfoot.getElementsByTagName("tr")[0].cloneNode(true);	
		if(data[e]["ID"] && tr.getAttribute("eRowID")!=null)
		{
			tr.setAttribute("eRowID",data[e]["ID"]);
		}
		//alert($(tr).find("[name]").length);		
		$(tr).find("[name]").each(function(i,elem){
		    var name = elem.getAttribute("name");		    
			if(name)
			{
			    var els = $(tr).find("[name='" + name + "']");
			    name = name.replace("td_", "");
			    //var _opar= $(tr).find("[name='" + name + "']").get(0);//移动端时有div 和 td两项
			    els.each(function(j,_opar){
				if (_opar.tagName == "TD" || _opar.tagName == "DIV")
				{
					if(data[e][name+"_Text"])
					{
					    _opar.innerHTML = data[e][name + "_Text"].decode();
					}
					else
					{
						if(data[e][name])
						{							
						    _opar.innerHTML = data[e][name].decode();
						}
					}
				}
				else
				{
					_opar.value=data[e][name];
					var etype = Attribute(_opar, "etype").toLowerCase();
					if(etype=="label" && data[e][name+"_Text"])
					{
						var onext = _opar.nextElementSibling||_opar.nextSibling;		
						onext.innerHTML=data[e][name+"_Text"].decode();
						_opar.setAttribute("text",data[e][name+"_Text"].decode());
					}
				}
			    });
			}
		});
		/*
		var tds=tr.getElementsByTagName("td");
		for(var j=0;j<tds.length;j++)
		{
			var name=tds[j].getAttribute("name");
			if(name)
			{
				if(data[e][name+"_Text"])
				{
					tds[j].innerHTML=data[e][name+"_Text"].decode();
					continue;
				}
				if(data[e][name])
				{
					tds[j].innerHTML=data[e][name].decode();
				}
			}
		}
		*/
		tbody.appendChild(tr);
		//alert(tr.outerHTML);
	});	
	if(clsname=="excelTable")
	{
		
		var tr=$(table).find("thead td:contains('序号')");
		if(tr.length>0)
		{
			var _index=tr.index();
			$(tbody).find("tr:visible").each(function(i,elem){
				$(this).find("td:eq(" + _index + ")").html(i + 1); 
			});
		}
			//
		//clsname 	$("a:") //jQuery内容查找
		//alert(50);
	}
	//for(var i=0;i<otds.length;i++)
}
//OK
function form_cancel(ModelID)
{
	var form=getobj("form_" + ModelID);
	if(form){form["Index"].value="-1";}
	var frm=getobj("model_form_" + ModelID.replace(/-/gi,""));	
	if(frm){frm.parentNode.removeChild(frm);}
}
//$(document).ready(function() { }); 
//$("#id").unbind("click").click(function(e){  });
var quick_input;
var quick_show=false;
var quick_clip=null;
var quick_keys="";
function quick_search()
{
	quick_keys = quick_input.value;
	document.onkeydown=function(e)
	{
		e=window.event||e;
		var src=e.srcElement||e.target;
		var _show=$("#eSearchBox dd").is(':visible');
		if(e.keyCode==13 && _show)
		{
			//alert("##");
			return true; 
		}
		
		if(src.tagName != "BODY"){return true;}
		if(e.keyCode == 116 ){return true;}
		//document.title=e.keyCode;
		if(e.keyCode == 8 && quick_show )
		{
			if(quick_keys.length>0)
			{
				quick_keys=quick_keys.substring(0,quick_keys.length-1);
				quick_clip.innerHTML = quick_keys;
			}			
			if (e.stopPropagation){e.stopPropagation();}else{event.cancelBubble = true;}
			if (e.preventDefault){e.preventDefault();}else{e.cancelBubble = true;}
			return false;
		}
		if(e.keyCode<65 || e.keyCode>90){return false;}
		
		return true;
	};

	quick_clip = document.createElement("span");
	quick_clip.id = "quick_clip";
	quick_clip.className="quick_clip";
	quick_clip.style.display = "none";
	
	quick_clip.innerHTML = quick_keys;// 'ABC';
	document.body.appendChild(quick_clip);

	
	
	$("body").bind("keydown",function(e){  
		e=window.event||e;
		var src=e.srcElement||e.target;
		var _show=$("#eSearchBox dd").is(':visible');
		if(e.keyCode==13 && _show)
		{
			//alert(5);
			e.keyCode = 0;
			return true; 
		}
		/*
		if(e.keyCode==13 && _show)
		{
			goSearch(frmsearch);
			//goSearch(document.forms["frmsearch"]);
			return true;  
		}
		*/
		
		if(src.tagName != "BODY"){return true;}
		//document.title+=e.keyCode;// String.fromCharCode(e.keyCode);
		if(e.keyCode==27)//ESC
		{
			quick_keys="";
			quick_show=false;
			quick_clip.style.display = "none";
			quick_clip.innerHTML = quick_keys;
			return false;  
		}
		if(e.keyCode==13)//回车
		{
			//alert(66);
			if(quick_show)
			{
				
				quick_show=false;
				quick_clip.style.display = "none";
				if(quick_keys.length>0 || quick_keys.length == 0)
				{
					quick_input.value=quick_keys;
					var tb=getobj("eDataTable");
					var ajax=false;
					if(tb)
					{
						ajax = parseBool(tb.getAttribute("ajax"));
					}
					if(ajax)
					{
						Search(1);
					}
					else
					{
						goSearch(document.forms["frmsearch"]);
					}
				}
			}
			else
			{
				quick_show=true;
				quick_clip.style.display = "";
			}
			e.keyCode = 0;
			return false;  
		}
		//if(quick_show && e.keyCode>= 65&& e.keyCode<=90)
		if(quick_show && e.keyCode>= 65 )
		{
			
			quick_keys+=String.fromCharCode(e.keyCode);
			quick_clip.innerHTML = quick_keys;
		}
		
	});
}
//星级评分初始
function raty_init()
{
	 $('.raty').each(function(i,elem){ 
		
		var dataid=$(this).attr('data-id');
		var staroff = $(this).attr('data-staroff');	
		var starhalf = $(this).attr('data-starhalf');
		var staron = $(this).attr('data-staron');
		var _readonly = $(this).attr('data-readonly');
		var readonly=false;
		if(_readonly=="true"){readonly=true;}
		var _half = $(this).attr('data-half');
		var half=false;
		if(_half=="true"){half=true;}
		
		if(dataid)
		{
			$(this).raty({ 
				  width:'100%',
				  hints: ['','','','',''],
				  readOnly: readonly, 
				  targetType: 'number',
				  targetKeep: true,
				  half: half,
				  halfShow: half,
				  target    : '#' + dataid,
				  score: function() { return $(this).attr('data-score');},
				  number: function() {return $(this).attr('data-number'); },  
				  starOff : staroff,
				  starHalf  : starhalf,
				  starOn  : staron			  
			  });
		}
		else
		{
			$(this).raty({ 
				  width:'100%',
				  hints: ['','','','',''],
				  readOnly: readonly, 
				  targetType: 'number',
				  targetKeep: true,
				  half: half,
				  halfShow: half,
				  score: function() { return $(this).attr('data-score');},
				  number: function() {return $(this).attr('data-number'); },  
				  starOff : staroff,
				  starHalf  : starhalf,
				  starOn  : staron			  
			  });
		}
	});
	
}
function init_dellink()
{
	//$(document).find("a:contains('删')[onclick]").each(function(i,elem){
		$(document).find("a:contains('删')[onclick*='confirm']").each(function(i,elem){		
			
			$(this).attr("_href",$(this).attr("href"));
			$(this).attr("href","javascript:;");
			var title=$(this).attr("onclick");
			title=title.substring(title.indexOf("(")+1);
			title=title.substring(0,title.indexOf(")"));
			title=title.replace(/'/g,"").replace(/"/g,"");
			elem.onclick=function()
			{				
				//var aa=confirm('确认要删除吗？');
				//var aa=confirm(title);
				//if(aa){document.location.href=$(elem).attr("_href");}
				 layer.confirm('确认要删除吗?', {
					title: "删除", shadeClose: true, area: ['200', '300'], btn: ['删除', '取消'],
					btn1: function (idx, layero) {
						layer.close(idx);
						//document.location.href=$(elem).attr("_href");
						ajaxGet($(elem).attr("_href"));
						var _url=document.location.href;
						var _act=_url.getquerystring("act");
						if(top==self && _act=="view") //查看时删除
						{
							_url=_url.removequerystring("act");
							_url=_url.removequerystring("id");
							document.location.assign(_url);
						}
						else
						{
							reloadDoc();
						}
					}
				});	
			};
		});
};
function init_quickviewBody()
{
    if ($("#quickviewbody").length > 0) {
        //$("#eDataTable tbody tr:eq(0)").trigger("click");
        var trs = $("#eDataTable > tbody > tr")
        if (trs.length > 0)
        {
            $(trs[0]).attr("class", "select");
            window.selectIndex = trs[0].rowIndex;
          
            var chk = $(trs[0]).find("input[name='selitem']");
            if (chk.length > 0) {
                chk.prop("checked", true);
                chk.attr("checked", true);
            }
            trs[0].click();
        }
        selectItems_check();
    }
};
function init()
{	
	//if(document.all)
    init_quickviewBody();
	if(!window.addEventListener)
	{
		//display: flex;align-items: center; IE文字消失问题 https://blog.csdn.net/weixin_34247032/article/details/94585514
		//$(".eDataTable tbody td div").css("float","left");
	}
	$(document).find("input[onblur*='MakePinyin']").each(function(index, elem) {		
	$(this).trigger("blur");
	});
	 // 初始化
    $('.circle').each(function(idx, el) {
        $(this).Circle();
    })
	$(".progress .bar").css("left",0);
	
	if(jQuery)
	{
		init_dellink();
		function buildParams( prefix, obj, traditional, add )
		{
			var name;
		
			if ( jQuery.isArray( obj ) ) {
		
				// Serialize array item.
				jQuery.each( obj, function( i, v ) {
					if ( traditional || rbracket.test( prefix ) ) {
		
						// Treat each array item as a scalar.
						add( prefix, v );
		
					} else {
		
						// Item is non-scalar (array or object), encode its numeric index.
						buildParams(
							prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
							v,
							traditional,
							add
						);
					}
				} );
		
			} else if ( !traditional && jQuery.type( obj ) === "object" ) {
		
				// Serialize object item.
				for(name in obj ) {
					if(typeof(obj[name])=="function"){continue;} 
					buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
				}
		
			} else {
		
				// Serialize scalar item.
				add( prefix, obj );
			}
		};
	
		jQuery.param = function( a, traditional ) {

			var prefix,
				s = [],
				add = function( key, value ) {
		
					// If value is a function, invoke it and return its value
					value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
					if(value.length>0)
					{
					    //var _str = value.KeyWordEncode();
                        /*
						var _str=value.replace(/#/g,"0x23");
						_str = _str.replace(/(?:\+|%26nbsp%3B)from(?:\+|%26nbsp%3B)/gi, function (word) {																					  
						var newword=word;
						newword = newword.replace(/from/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
						return newword;
						});
						
						_str = _str.replace(/(?:\+|%26nbsp%3B)and(?:\+|%26nbsp%3B)/gi, function (word) {																					  
							var newword=word;
							newword = newword.replace(/and/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
							return newword;
						});
						_str = _str.replace(/(?:\+|%26nbsp%3B)or(?:\+|%26nbsp%3B)/gi, function (word) {																					  
							var newword=word;
							newword = newword.replace(/or/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
							return newword;
						});
						_str = _str.replace(/(?:\+|%26nbsp%3B)in(?:\+|%26nbsp%3B)/gi, function (word) {																					  
							var newword=word;
							newword = newword.replace(/in/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
							return newword;
						});
						_str = _str.replace(/(?:\+|%26nbsp%3B)else(?:\+|%26nbsp%3B)/gi, function (word) {																					  
							var newword=word;
							newword = newword.replace(/else/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
							return newword;
						});
						_str = _str.replace(/(?:\+|%26nbsp%3B)set(?:\+|%26nbsp%3B)/gi, function (word) {																					  
							var newword=word;
							newword = newword.replace(/set/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
							return newword;
						});	
						var _keys="where,script,object,function,window,database,update,exec,execute,backup,onclick,convert,href,video,ping";//from,or,and,in,else,set
						var arr=_keys.split(",");
						for(var i=0;i<arr.length;i++)
						{
							var re=new RegExp(arr[i],"gi");
							_str = _str.replace(re, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
						}
                        */
					    value = value.KeyWordEncode();//关键词统一编码
					}
					//alert(key + "::" + value);
					s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
				};
		
			// Set traditional to true for jQuery <= 1.3.2 behavior.
			if ( traditional === undefined ) {
				traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
			}
		
			// If an array was passed in, assume that it is an array of form elements.
			if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
		
				// Serialize the form elements
				jQuery.each( a, function() {
					//alert(this.name + "::" + this.value + "A");
					add( this.name, this.value );
				} );
		
			} else {
		
				// If traditional, encode the "old" way (the way 1.3.2 or older
				// did it), otherwise encode params recursively.
				for(prefix in a ) {
					if(typeof(a[prefix])=="function"){continue;} 
					buildParams( prefix, a[ prefix ], traditional, add );
				}
			}

			//alert(s);
			// Return the resulting serialization
			var r20 = /%20/g;			
			var str= s.join( "&" ).replace(r20, "+" );
			return str;
			
		    /*
            str= str.replace(/#/g,"0x23");
			str = str.replace(/\+from\+/gi, function (word) {return word.replace("f", "\\u0066").replace("F", "\\u0046");});
			str = str.replace(/\+where\+/gi, function (word) {return word.replace("w", "\\u0077").replace("W", "\\u0057");});
			str = str.replace(/\+and\+/gi, function (word) {return word.replace("a", "\\u0061").replace("A", "\\u0041");});
			str = str.replace(/\+set\+/gi, function (word) {return word.replace("s", "\\u0073").replace("S", "\\u0053");});
			str = str.replace(/\+or\+/gi, function (word) {return word.replace("o", "\\u006f").replace("O", "\\u004f");});
			*/
			//str = str.replace(/\+from\+/gi, function (word) {return "0x_from_";});
			//str = str.replace(/\+where\+/gi, function (word) {return "0x_where_";});
			//str = str.replace(/\+and\+/gi, function (word) {return "0x_and_";});
			//str = str.replace(/\+set\+/gi, function (word) {return "0x_set_";});
			//str = str.replace(/\+or\+/gi, function (word) {return "0x_or_";});
			//str = str.replace(/select\+/gi, function (word) {return "0xselect_";});
			//str = str.replace(/\+in\+/gi, function (word){return "0x_in_";});	
			//str = str.replace(/\+else\+/gi, function (word) {return "0x_else_";});//科工防火墙,其他方式替换不行
			/*
			str = str.replace(/(?:\+|%26nbsp%3B)from(?:\+|%26nbsp%3B)/gi, function (word) {return "0x_from_";});			
			str = str.replace(/(?:\+|%26nbsp%3B)where(?:\+|%26nbsp%3B)/gi, function (word) {return "0x_where_";});			
			str = str.replace(/(?:\+|%26nbsp%3B)and(?:\+|%26nbsp%3B)/gi, function (word) {return "0x_and_";});			
			str = str.replace(/(?:\+|%26nbsp%3B)set(?:\+|%26nbsp%3B)/gi, function (word) {return "0x_set_";});			
			str = str.replace(/(?:\+|%26nbsp%3B)or(?:\+|%26nbsp%3B)/gi, function (word) {return "0x_or_";});			
			str = str.replace(/select(?:\+|%26nbsp%3B)/gi, function (word) {return "0xsel_";});			
			str = str.replace(/(?:\+|%26nbsp%3B)in(?:\+|%26nbsp%3B)/gi, function (word){return "0x_in_";});				
			str = str.replace(/(?:\+|%26nbsp%3B)else(?:\+|%26nbsp%3B)/gi, function (word) {return "0x_else_";});//科工防火墙,其他方式替换不行			
			str = str.replace(/script/gi, function (word) {return "0xjstag";});//科工防火墙,其他方式替换不行
			str = str.replace(/object/gi, function (word) {return "0xobjtag";});//科工防火墙,其他方式替换不行
			str = str.replace(/function/gi, function (word) {return "0xfun";});//科工防火墙,其他方式替换不行
			str = str.replace(/window/gi, function (word) {return "0xwin";});//科工防火墙,其他方式替换不行
			str = str.replace(/database/gi, function (word) {return "0xdb";});//科工防火墙,其他方式替换不行
			*/
			/*
			str = str.replace(/(?:\+|%26nbsp%3B)from(?:\+|%26nbsp%3B)/gi, function (word) {																					  
				var newword=word;
				newword = newword.replace(/from/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
				return newword;
			});
			
			str = str.replace(/(?:\+|%26nbsp%3B)and(?:\+|%26nbsp%3B)/gi, function (word) {																					  
				var newword=word;
				newword = newword.replace(/and/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
				return newword;
			});
			str = str.replace(/(?:\+|%26nbsp%3B)or(?:\+|%26nbsp%3B)/gi, function (word) {																					  
				var newword=word;
				newword = newword.replace(/or/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
				return newword;
			});
			str = str.replace(/(?:\+|%26nbsp%3B)in(?:\+|%26nbsp%3B)/gi, function (word) {																					  
				var newword=word;
				newword = newword.replace(/in/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
				return newword;
			});
			str = str.replace(/(?:\+|%26nbsp%3B)else(?:\+|%26nbsp%3B)/gi, function (word) {																					  
				var newword=word;
				newword = newword.replace(/else/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
				return newword;
			});
			str = str.replace(/(?:\+|%26nbsp%3B)set(?:\+|%26nbsp%3B)/gi, function (word) {																					  
				var newword=word;
				newword = newword.replace(/set/gi, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
				return newword;
			});	
			var _keys="where,script,object,function,window,database,update,exec,execute,backup,onclick,convert";//from,or,and,in,else,set
			var arr=_keys.split(",");
			for(var i=0;i<arr.length;i++)
			{
				var re=new RegExp(arr[i],"gi");
				str = str.replace(re, function (word) {var idx=parseInt(word.length/2); return "0x" + word.substring(0,idx) + "--" + word.substring(idx) + "__";});
			}
			//alert(str);
			return str;
			*/
		};

	}
	if(layer)
	{
		//window.alert=function(str){};
	}
	
	$("span.more").each(function(index, val) {
		var ele = $(this);		
		ele.on("click", function() {
			showOptionMenu(this);			
		});	
	
	});
	raty_init();
	//document.title=":";
	if(getobj("eSearchBox"))
	{
		var sbox=getobj("eSearchBox");
		var inputs=sbox.getElementsByTagName("input");		
		for(var i=0;i<inputs.length;i++)
		{
			if(inputs[i].getAttribute("etype")=="quick")
			{
				quick_input=inputs[i];
				quick_search();
				break;
			}
		}
	}
					  
	//$("body").bind("contextmenu", function(event) {return false; }); 
	$("body").bind("keyup",function(e){
		e=window.event||e; 
		if(e.keyCode==16)
		{
			window.shift=false;
		}
		if(e.keyCode==17)
		{
			window.ctrl=false;
		}
		//document.title=e.keyCode+"up";
	});
	$("body").bind("keydown", function (e) {
	  
  		e=window.event||e; 
		if(e.keyCode==16)
		{
			window.shift=true;
		}
		if(e.keyCode==17)
		{
			window.ctrl=true;
		}
		var src = e.srcElement || e.target;
		
		var _show=$("#eSearchBox dd").is(':visible');
		if(e.keyCode==13 && _show && src.tagName!="TEXTAREA")
		{
			//alert(3);
			goSearch(document.forms["frmsearch"]);
			return false;
		}
		if(src.tagName!="BODY"){return;}
		
		//document.title = e.keyCode + "down";
		if (e.keyCode == 38)//上一条数据
		{
		    _parent().prevRecord();
		    return false;
		}
		if (e.keyCode == 40)//下一条数据
		{
		    _parent().nextRecord();
		    return false;
		}
		if(e.keyCode==37 || e.keyCode==33)//上一页
		{
			page_Previous();
			return false;
		}
		if(e.keyCode==36)//首页
		{
			page_First();
			return false;
		}
		if(e.keyCode==39 || e.keyCode==34)//下一页
		{
			page_Next();
			return false; 
		}
		if(e.keyCode==35)//尾页
		{
			page_Last();
			return false;
		}
		if(e.keyCode==45) //Insert
		{
			if($("#btn_add").length==1){document.location.assign($("#btn_add").attr("href"));}
			return false;
		}
		if(e.keyCode==46) //Delete
		{
			//document.title+=src.tagName;$("body :visible")
			if($("#btn_delMore:visible").length==1){$("#btn_delMore:visible").trigger("click");}
			if($("#btn_Delete").length==1){$("#btn_Delete").trigger("click");}
			return false;
		}
		if(e.ctrlKey && e.keyCode==65) //Ctrl + A
		{
		    //$(".eDataTable thead td:eq(0)").find("input[name='selallitem']").trigger("click");
		    selectAll();
			return false;
			
		}
		if(e.ctrlKey && e.keyCode==67) //Ctrl + C
		{
			var selectedText = window.getSelection().toString();
			if(selectedText.length>0){return true;}			
		    //if($("input[name='delitem']:checked").length==1)
            /*
			if($("input[name='selitem']:checked").length==1)
			{
				var url=document.location.href;
				url+= url.indexOf("?") > -1 ? "&" : "?";
				//url+="&act=copy&id=" + $("input[name='delitem']:checked").val();	
				url+="act=copy&id=" + $("input[name='selitem']:checked").val();	
				document.location.assign(url);
				//document.title=$("input[name='delitem']:checked").val();
				//alert(url);
			}
            */
			var tbody = getSelectBody();
			var sels = tbody.find("tr[class='select']");
			if (sels.length == 1)// && arrLayerIndex.length==0
			{
			    if (top != self)//Frame打开
			    {
			        //sels.find("a[ehref*='act=edit']").trigger("click");
			        sels.find("a[ehref*='act=edit']")[0].click();
			    }
			    else
			    {
			        if (sels.find("a[href*='act=edit']").length == 1) {
			            if (arrLayerIndex.length > 0) {
			                layer.close(arrLayerIndex.pop());
			            }
			            //sels.find("a[href*='act=edit']").trigger("click");
			            var url = sels.find("a[href*='act=edit']").attr("href");
			            url = url.addquerystring("act", "copy");
			            document.location.assign(url);
			            //layer.msg("1:" + arrLayerIndex.length);
			        }
			    }
			}
			return false;
		}
		if(e.ctrlKey && e.keyCode==69) //Ctrl + E
		{
			//if($("#btn_Edit").length==1){$("#btn_Edit").trigger("click");}
		    if ($("#btn_Edit").length == 1)
		    {
		        document.location.assign($("#btn_Edit").attr("href"));
		        return false;
		    }
			
			
		    //if($("input[name='delitem']:checked").length==1)
            /*
			if($("input[name='selitem']:checked").length==1)
			{
				//var tr=$("input[name='delitem']:checked").parents("tr:first");
				var tr=$("input[name='selitem']:checked").parents("tr:first");
				if(tr.find("a[href*='act=edit']").length==1)
				{
					//document.title=tr.find("a[href*='act=edit']").length;
					document.location.assign(tr.find("a[href*='act=edit']").attr("href"));
				}
			}
            */
		    var tbody = getSelectBody();
		    var sels = tbody.find("tr[class='select']");
		    if (sels.length == 1)// && arrLayerIndex.length==0
		    {
		        if (top != self)//Frame打开
		        {
		            //sels.find("a[ehref*='act=edit']").trigger("click");
		            sels.find("a[ehref*='act=edit']")[0].click();
		        }
		        else {
		            if (sels.find("a[href*='act=edit']").length == 1) {
		                if (arrLayerIndex.length > 0) {
		                    layer.close(arrLayerIndex.pop());
		                }
		                //sels.find("a[href*='act=edit']").trigger("click");
		                var url = sels.find("a[href*='act=edit']").attr("href");
		                document.location.assign(url);
		                //layer.msg("1:" + arrLayerIndex.length);
		            }
		        }
		    }
			return false;
		}
		if(e.ctrlKey && e.keyCode==70) //Ctrl + F
		{ 
			//document.title="ctrl + f";
    		e.keyCode = 0;  
			var sbox=getobj("eSearchBox");
			if(sbox)
			{
				var h1=sbox.children[0];
				showPanel(h1);
			}
    		return false;
 		} 
	    //document.title=e.keyCode;
		
		//屏蔽F5刷新键  
		/*
		var tb = getobj("eDataTable");
		if (tb) {
		    var ajax = parseBool(tb.getAttribute("ajax"));
		    if (e.keyCode == 116 && ajax) {

		        e.keyCode = 0; //IE下需要设置为keyCode为false
		        Search();
		        return false;
		    }
		}
		*/
		if (e.keyCode == 116)
		{
			if(_top() != self)
			{
				if(document.forms["frmsearch"])
				{
					Search();
				}
				else
				{
					document.location.assign(document.location.href);
				}
				return false;
			}
		}
	   //layer.msg(e.keyCode + "B");
	   //Esc
	   if(e.keyCode==27)
	   {
	       if (_top() != self)//Frame打开
	       {
	           if (_top().arrLayerIndex.length > 0) {
	               _top().layer.close(top.arrLayerIndex.pop());
	           }
	       }
	       else
	       {
	           _parent().unselectAll();
	           if (arrLayerIndex.length > 0) {
	               layer.close(arrLayerIndex.pop());
	           }
	           else {
	               if (parent.arrLayerIndex.length > 0) {
	                   parent.layer.close(parent.arrLayerIndex.pop());
	               }
	           }
	       }
		}	
   
   
    });
	/*
	$(document).keydown(function(e){	
	if(e.keyCode==27)
	{
		if(arrLayerIndex.length>0)
		{
			layer.close(arrLayerIndex.pop());
		}
		if(parent.arrLayerIndex.length>0)
		{
			parent.layer.close(parent.arrLayerIndex.pop());
		}		
	}
	});	
	*/
	/*
	var keyevent=new eKeyEvent();
	keyevent.onkeydown=function()
	{
		if(this.keyCode==2700)
		{
			if(arrLayerIndex.length>0)
			{
				layer.close(arrLayerIndex.pop());
			}
			else
			{
				if(parent.arrLayerIndex.length>0)
				{
					parent.layer.close(parent.arrLayerIndex.pop());
				}	
			}
		}		
		if(this.keyCode==116000)
		{
			if(1==13)
			{
				keyevent.clearEvent=true;
				Search();
			}
			
			//document.location.assign(url);
		}
		if(this.keyCode==7000000 && this.ctrlKey)//F 70
		{
			keyevent.clearEvent=true;
			var sbox=getobj("eSearchBox");
			if(sbox)
			{
				var h1=sbox.children[0];
				showPanel(h1);
			}
			//if(this.Node.tagName=="INPUT"){return;}
			//if(this.ctrlKey && this.keyCode ==65 && this.Node.tagName!="INPUT")
			//if(this.keyCode==46)//DELETE
			//if(this.keyCode==69 && this.ctrlKey)//E
			//if(this.keyCode==86 && this.ctrlKey)//V
			//if(this.keyCode==67 && this.ctrlKey)//C
			//if(this.keyCode==27)//ESC
		}
	};
	*/
	//alert("init_init");
	etable_init();
	if(typeof(eSignIn)==="object")//签名插件
	{
		eSignIn.init();
	}
	$("[etype='sign'][name$='_data']").each(function (i, elem) {
			var par=$(this).parent();
			var canvas=par.find("canvas").get(0);
			//alert(canvas.clientWidth + "::" + canvas.clientHeight);
			canvas.width=canvas.clientWidth;
			canvas.height=canvas.clientHeight;
			var edata=canvas.getAttribute("edata");
			if(edata && edata.length>100)
			{
				var img = new Image;
				img.onload = function(){
					var tow = 0, toh = 0;
					if (img.width / canvas.clientWidth < img.height / canvas.clientHeight) {
						toh = canvas.clientHeight;
						tow = parseInt(img.width * toh / img.height);
					}
					else {
						tow = canvas.clientWidth;
						toh = parseInt(img.height * tow / img.width);
					}
					canvas.getContext("2d").clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);
					//canvas.getContext("2d").drawImage(img,0,0);
					canvas.getContext("2d").drawImage(img,0,0, tow, toh);
					//canvas.width=canvas.clientWidth;
					//canvas.height=canvas.clientHeight;
				};
				img.src = "data:image/png;base64," + edata;
			}
			
		});
}
function etable_init()
{
    var fixedwidth = 1;//固定100%
    var tb = getobj("eDataTable");
    if (!tb) { return; }
    if (tb.getAttribute("fixedwidth")) { fixedwidth = parseInt(tb.getAttribute("fixedwidth")); }
	//document.title+="A";
    var eTable = new eDataTable("eDataTable", fixedwidth);
	eTable.onclick=function(tr)
	{
	    //document.title = "OK";
	    var tbody = $(tr).parents("tbody:first");	   
	    window.selectBody = tbody;
	    var etype = $(tr).attr("etype");
	    if (etype == "sum") //汇总
	    {
	        return;
	    }
		var erowid = $(tr).attr("erowid");

		if(erowid==undefined)
		{
			return;
		}
		var src = getEventObject();
		//document.title = src.tagName;
		if (src.tagName != "INPUT" && (src.tagName != "TD" && src.tagName != "DIV" && src.tagName != "P" && src.tagName != "LABEL")) { return; }		
	    if (src.tagName == "INPUT" && src.name.toLowerCase() != "selitem") { return; }
	    //document.title = src.name.toLowerCase();
	    if (src.tagName == "INPUT" && src.name.toLowerCase() == "selitem")
	    {
	        tr.className = src.checked ? "" : "select";
	        setTimeout(function () { selectItems_check(tbody); }, 100);
	        return;
	    }
	    var chkall = $("input[name='selallitem']");
	    if (chkall.length == 0)
	    {
	        if (!window.ctrl && !window.shift) {
	            tbody.find("tr[class='select']").each(function (i, el) {
	                el.className = "";
	            });
	            tr.className = (tr.className == "select" ? "cur" : "select");
	            selectItems_check(tbody);
	            return;
	        }
	    }
	    if (tbody.find("tr[class='select']").length == 1 && tr.className == "select" && $("#quickviewbody").length > 0) {
	        //selectItems_check(tbody);
	        //return;
	    }
		if(!window.ctrl && !window.shift)
		{
            /*
		    tbody.find("tr[class='select']").each(function (i, el)
			{
		        //el.className = "";			   
		    });
		    tr.className = (tr.className == "select" ? "cur" : "select");
            */

		    window.selectIndex = tr.rowIndex;
		    var chk = $(tr).find("input[name='selitem']");
		    if (tr.className == "select") {
		        tr.className = "";
		    }
		    else		    
		    {
		        tr.className = "select";
		    }
		    if (chk.length > 0)
		    {
		        chk.prop("checked", (tr.className == "select" ? true : false));
		        chk.attr("checked", (tr.className == "select" ? true : false));
		    }			
			selectItems_check(tbody);
		}
		else
		{
			var headct=$(tr).parents("table:first").find("thead tr").length;
			if(window.ctrl)
			{
				if(tbody.find("tr[class='select']").length==1 && tr.className=="select")
				{
				    selectItems_check(tbody);
					return;
				}
			    //tr.className=(tr.className=="select" ? "" : "select");
				if (tr.className == "select")
				{
				    tr.className = ""
				}
				else
				{
				    tr.className = "select"
				}
				var chk = $(tr).find("input[name='selitem']");
				if (chk.length > 0) {
				    chk.prop("checked", (tr.className == "select" ? true : false));
				    chk.attr("checked", (tr.className == "select" ? true : false));
				}
				if(tr.className=="select")
				{
					window.selectIndex=tr.rowIndex;
				}
				if(tbody.find("tr[class='select']").length==0)
				{
					window.selectIndex=null;
				}
				selectItems_check(tbody);
				return;
			}
			if(window.shift)
			{
				//document.title=window.selectIndex + "::" + tr.rowIndex;
				if(window.selectIndex=="undefined" || window.selectIndex==tr.rowIndex)
				{
					return;
				}
				var _min = tr.rowIndex < window.selectIndex ? tr.rowIndex : window.selectIndex;
				_min-=headct;
				var _max = window.selectIndex < tr.rowIndex ? tr.rowIndex : window.selectIndex;
				_max-=headct;
				
				//document.title=_min + "::" + _max;
				$(tr).parents("table:first").find("tbody tr").each(function(i,elem)
				{
				    var chk = $(elem).find("input[name='selitem']");
					if(elem.rowIndex-headct >= _min && elem.rowIndex-headct <= _max)
					{
						elem.className="select";
					}
					else
					{
						elem.className="";
					}
					if (chk.length > 0) {
					    chk.prop("checked", (elem.className == "select" ? true : false));
					    chk.attr("checked", (elem.className == "select" ? true : false));
					}
				});	
				selectItems_check(tbody);
			}
		}
	};
	if($("input[name='selitem']").length>0 && 1==2)
	{
		eTable.onclick=function(tr){
			
			
			if($(tr).find("input[name='selitem']").length==0){return;}			
			//document.title = $(tr).find("a[href*='act=del']").length + "B";			
			var src = getEventObject();
			var evt = getEvent(); 
			if(evt.button!=0 && evt.button!=1){return;}
			if(src.tagName!="INPUT" && (src.tagName!="TD"&&src.tagName!="DIV"&&src.tagName!="P")){return;}
			if(src.tagName=="INPUT" && src.name.toLowerCase()!="selitem"){return;}
			if(src.tagName=="TD"||src.tagName=="DIV"||src.tagName=="P")
			{
				var _value=!$(tr).find("input[name='selitem']")[0].checked;
				$(tr).find("input[name='selitem']").prop("checked",_value);
				selectMore_check();
			}
			else
			{			
				setTimeout(function(){selectMore_check();},100);			
			}
		};
	}
	
	if($("input[name='delitem']").length>0 && 1==2)//
	{
		eTable.onclick=function(tr){
			if($(tr).find("input[name='delitem']").length==0){return;}
			

			//document.title = $(tr).find("a[href*='act=del']").length + "B";
			
			var src=getEventObject();
			if(src.tagName!="INPUT" && src.tagName!="TD"){return;}
			if(src.tagName=="INPUT" && src.name.toLowerCase()!="delitem"){return;}
			if(src.tagName=="TD")
			{
				var _value=!$(tr).find("input[name='delitem']")[0].checked;
				$(tr).find("input[name='delitem']").prop("checked",_value);
				deleteMore_check();
			}
			else
			{			
				setTimeout(function(){deleteMore_check();},100);			
			}
		};
	}
	if($("input[name='fillseli4tem']").length>0)
	{
		eTable.onclick=function(tr){
			if($(tr).find("input[name='fillselitem']").length==0){return;}
			var src=getEventObject();
			if(src.tagName!="INPUT" && src.tagName!="TD"){return;}
			if(src.tagName=="INPUT" && src.name.toLowerCase()!="fillselitem"){return;}
			if(src.tagName=="TD")
			{
				var _value=!$(tr).find("input[name='fillselitem']")[0].checked;
				$(tr).find("input[name='fillselitem']").prop("checked",_value);
				//deleteMore_check();
			}
			else
			{			
				//setTimeout(function(){deleteMore_check();},100);			
			}
			
			//alert(5);
		};	
	}
	eTable.rowover=function(tr){};
	eTable.rowout=function(tr){};
	eTable.setWidth=function(td,widtharr)
	{
		if(typeof(eDataTable_setWidth)=="function")
		{
			eDataTable_setWidth(tr,widtharr);
			return;
		}
	   // alert(widtharr);
		var url="?act=setwidths";	
		if(typeof(AppItem)=="string" && AppItem.length > 0){url+="&AppItem=" + AppItem;}
		if(typeof(ModelID)=="string" && ModelID.length > 0){url+="&ModelID=" + ModelID;}
		var sessionid=document.location.href.getquerystring("sessionid");
		if(sessionid.length>0){url+="&sessionid="+sessionid;}
		url+="&value=" + widtharr + "&t=" + now();		
		//alert(url);
		//return;
		//var url="?act=setwidths&modelid="+ ModelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "") + "&value=" + widtharr + "&t=" + now();

		//$.ajax({type:"GET",async:false,url:_url,dataType:"html"});	
		$.ajax({type: "GET",async: false,url:url,dataType: "html",success: function(data)
		{

		},
	    error: function (XMLHttpRequest, textStatus, errorThrown) 
		{
	        //alert("error:" + XMLHttpRequest.responseText + "::" + XMLHttpRequest.status + "::" + XMLHttpRequest.readyState + "::" + XMLHttpRequest.statusText);
	    }
		});	
	};
	eTable.setHeight=function(td,height)
	{
		if(typeof(eDataTable_setHeight)=="function")
		{
			eDataTable_setHeight(tr,height);
			return;
		}
		var url="?act=setlineheight";	
		if(typeof(AppItem)=="string" && AppItem.length > 0){url+="&AppItem=" + AppItem;}
		if(typeof(ModelID)=="string" && ModelID.length > 0){url+="&ModelID=" + ModelID;}
		var sessionid=document.location.href.getquerystring("sessionid");
		if(sessionid.length>0){url+="&sessionid="+sessionid;}
		url+="&value=" + height + "&t=" + now();
		
		//var url="?act=setlineheight&modelid="+ ModelID +  (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "") + "&value=" + height + "&t=" + now();
		$.ajax({type:"GET",async:false,url:url,dataType:"html",success:function(data)
		{
		},
	    error: function (XMLHttpRequest, textStatus, errorThrown) 
		{
	        //alert("error:" + XMLHttpRequest.responseText + "::" + XMLHttpRequest.status + "::" + XMLHttpRequest.readyState + "::" + XMLHttpRequest.statusText);
	    }
		});
	};
	eTable.sort5=function(td,value)
	{
		//document.title= "::" + value + "_";
		//return false;
		var cancelAutoUrl = true;
		return cancelAutoUrl;
	};
	eTable.ColumnMoved=function(tr)
	{
		if(typeof(eDataTable_ColumnMoved)=="function")
		{
			eDataTable_ColumnMoved(tr);
			return;
		}
		/*
		var value="";
		for(var i=0;i<tr.children.length;i++)
		{
			if(Attribute(tr.children[i],"eCellID").length==0){continue;}
			value+= (value.length == 0 ? "" : "|") + Attribute(tr.children[i],"eCellID") + "_" + (parseInt(tr.children[i].cellIndex) + 1);
		}
		if(value.length==0){return;}
		var _url="?act=setsortall&modelid="+ ModelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "") + "&value=" + value + "&t=" + now();
		*/
		//$.ajax({type:"GET",async:false,url:_url,dataType:"html"});	
	};
	eTable.moveColumn=function(tr,td,index,new_index)
	{
		if(typeof(eDataTable_moveColumn)=="function")
		{
			eDataTable_moveColumn(tr,td,index,new_index);
			return;
		}
		//alert(setCelIndex);
		//var td=tr.children[new_index];
		//alert(td.innerText);
		//alert(index + "::" + new_index);
		//return;
		//alert($(tr).find("input[name='selallitem']").length);
		var value=new_index+1+($(tr).find("input[name='selallitem']").length==0?1:0);
		//var value=new_index+1 + $(tr).find("input[name='selallitem']").length;
		//var url="?act=setsort&modelid="+ ModelID + (typeof(AppItem)=="string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "") + "&ModelItemID=" + Attribute(td,"eCellID") + "&value=" + value + "&t=" + now();
		//	alert(index + "::" + new_index + "::" + value);
		//return;
		
		var url="?act=setsort";	
		if(typeof(AppItem)=="string" && AppItem.length > 0){url+="&AppItem=" + AppItem;}
		if(typeof(ModelID)=="string" && ModelID.length > 0){url+="&ModelID=" + ModelID;}
		var sessionid=document.location.href.getquerystring("sessionid");
		if(sessionid.length>0){url+="&sessionid="+sessionid;}
		url+="&ModelItemID=" + Attribute(td,"eCellID") + "&value=" + value + "&t=" + now();
		//alert(index + "::" + new_index + "::" + url);
		//return;
		//document.title=Attribute(td,"eCellID") + ":::" + value;
		$.ajax({type:"GET",async:false,url:url,dataType:"html"});	
		//alert(tr.children.length + ":::" + index + "::::" + new_index);
		//outText("moveColumn:" +  index + "::" + new_index);
		//document.title= index + "::" + new_index;
		//setCelIndex():
		
		//alert(eTable.thead);
		//setCelIndex(eTable.thead);
	};
	//eTable.sort=function(td){document.title=td.innerText;};
	eTable.moveRow=function(index,new_index,tr)
	{
		if(typeof(eDataTable_moveRow)=="function")
		{
			eDataTable_moveRow(index,new_index,tr);
		}
		//document.title= index + "::" + new_index;
	};
}

var OptionMenuObject=null;
function getEventObject()
{
	var evt,src;
	if(window.event)
	{
		evt=window.event;
		src = evt.srcElement;
	}
	else
	{
		var o = arguments.callee;
		var e;
		while(o != null)
		{
			e = o.arguments[0];
			if(e && (e.constructor == Event || e.constructor == MouseEvent))
			{
				evt=e;src=evt.target; 
				break;
			}
			o = o.caller;
		}
	}
	return src;
}
function cancelOptionMenu()
{
	//alert(getEventObject() + "::" + OptionMenuObject)
	if(getEventObject()==OptionMenuObject)
	{
		return;
	}
	if(OptionMenuObject==null){return;}
	var ul=$(OptionMenuObject).find("ul");
	ul.hide();
	
	if (document.addEventListener)
	{
		document.removeEventListener('mouseup', cancelOptionMenu, false);
	}
	else
	{
		document.detachEvent("onmouseup",cancelOptionMenu);
	}
	OptionMenuObject=null;
}
function showOptionMenu(obj)
{	

	var ul=$(obj).find("ul");	
	if(ul.length==0)
	{
		ul=$(obj).parents("td:first").find("ul");
	}
	if(obj==OptionMenuObject || getEventObject().tagName=="A")
	{
		if (document.addEventListener)
		{
			document.removeEventListener('mouseup', cancelOptionMenu, false);
		}
		else
		{
			document.detachEvent("onmouseup",cancelOptionMenu);
		}
		OptionMenuObject=null;
		ul.hide();
		//cancelOptionMenu();
		return;
	}
	//if(OptionMenuObject!=null){}//cancelOptionMenu会处理	
	var Rect = obj.getBoundingClientRect();
	ul.css("position","absolute");
	ul.css("left","-2000px");
	ul.css("top","-2000px");
	ul.show();


	//document.title=Rect.top + "::" + Rect.bottom + ":::" + $(obj).position().top;
	
	ul.css("left",($(obj).position().left - ul.width()) + "px");	
	ul.css("top",$(obj).position().top + "px");	
		//ul.css("left","0px");	
		//	ul.css("top","0px");	
	//ul.css("left",(Rect.left - ul.width()) + "px");	
	
	//ul.css("top",parseInt(Rect.bottom) + "px");
	/*
	ul.css("left",(new eScroll().left +　Rect.left - ul.width()) + "px");	
	if( (new eScroll().top  +　Rect.bottom + ul.height() + 21) < $(document.body).height() )
	{
		//ul.css("top",(new eScroll().top +　Rect.bottom - 21) + "px");
	}
	else
	{
		//ul.css("top",(new eScroll().top +　Rect.bottom - 21 -  ul.height()) + "px");
	}
	ul.css("top",(new eScroll().top +　Rect.bottom - 21) + "px");
	*/
	
	if (window.addEventListener)
	{
		document.addEventListener('mouseup',cancelOptionMenu, false);
	}
	else
	{
		document.attachEvent("onmouseup",cancelOptionMenu);
	}	
	OptionMenuObject=obj;
}
if (window.addEventListener) { window.addEventListener("load", init, false); } else { window.attachEvent("onload", init); }
function removeLocal(obj, appitem) {
    //清除 按钮，清除本地
    //localStorage.removeItem('key');// 删除数据
    //localStorage.clear();// 清除所有数据
    localStorage.removeItem(appitem);
    
    var url = $("#fromurl").val();
    if (url.length > 0)
    {
        var act = url.getquerystring("act");
        if (act.length == 0)
        {
            localStorage.setItem("href_" + appitem, url);
        }
    }
    document.location.assign(document.location.href);
}
function autoSave()
{
    //document.title += "1";
	var frm= document.forms["form_" + window.smodelid];
	if(!frm){return;}
	var frmobj = formToJson(frm);
	var fcount = 0;
	frmobj.foreach(function (e) {
	    if (typeof (frmobj[e]) == "object") {
	        fcount+=frmobj[e].length;
	    }
	    else {
	        var val = frmobj[e];
	        if (val.length > 0) {
	            fcount++;
	        }
	    }
	});
	if (fcount<2) { return; }
	var obj=new eJson2([]);
	obj.append(frmobj);		
	var model=new eJson2();
	model.append("ModelID", window.smodelid);	
	model.append("eformdata_" + window.smodelid, obj);
	localStorage.setItem(window.appitem, model.toJson());	
};
function lsTest(obj, appitem)
{
    var frm = document.forms["form_" + window.smodelid];
    if (!frm) { return; }
    var frmobj = formToJson(frm);
    var obj = new eJson2([]);
    obj.append(frmobj);

    //alert(frmobj.toJson());
    frmobj.foreach(function(e)
    {
        if (typeof (frmobj[e]) == "object") {
            alert("obj" + frmobj[e].length);
        }
        else
        {
            var val = frmobj[e];
            alert(e + "::" + val.length); 
        }
       
    });
    
};
function init_autoSave()
{
	if (typeof localStorage === 'object')
	{	  
	    var act = document.location.href.getquerystring("act");	   
		if(act=="add")
		{
			var appitem=document.location.href.getquerystring("appitem");
			var ipt = $("#frmaddoredit input[name*='eformdata_']");		
			if(ipt.length>0)
			{
			    var val = ipt.val();
				if(val.length < 10)//未加载草稿
				{
					var modelid=ipt.attr("name").replace("eformdata_","");
					window.appitem=appitem;
					window.smodelid=modelid;
					var value = localStorage.getItem(appitem);
					if(value==null)//定时保存
					{
					    var url = $("#fromurl").val();
					    if (url.length > 0)
					    {
					        var act = url.getquerystring("act");
					        if (act == "add")
					        {
					            var fromurl = localStorage.getItem("href_" + appitem);
					            $("#fromurl").val(fromurl);
					            localStorage.removeItem("href_" + appitem);
					        }
					    }
					}
					else
					{
					    ipt.val(value);
					    form_load(modelid);
					    $(document).find("a:contains('返回')").after('<a href="javascript:;" class="button" onclick="removeLocal(this,appitem);" style="margin-left:10px;"><span><i class="reset">清除</i></span></a>');
					}
					setInterval(autoSave, 3000);
				}
			}
			//$(document).find("a:contains('返回')").after('<a href="javascript:;" class="button" onclick="lsTest(this,appitem);" style="margin-left:10px;"><span><i class="reset">测试2</i></span></a>');
		}
	}
};
if (window.addEventListener) { window.addEventListener("load", init_autoSave, false); } else { window.attachEvent("onload", init_autoSave); }
function initdate(_body)
{
	//alert( pinyinUtil.getHanzi("lv").toString());
	if(!IsMobile()){ return;}
	if(!_body){_body=$(document.body);}
	
	if (_body instanceof jQuery)
	{
	}
	else
	{
		_body=$(_body);
	}

	//$(".date").each(function(i,elem){	
	//$("[roll_format]").each(function(i,elem){
	_body.find("input[roll_format]").each(function(i,elem){
		elem.onclick=function(){};
			new Rolldate({
				el: '#' + elem.id,
				beginYear: 1930,
				format: $(elem).attr("roll_format"),
				value: $(elem).val().length > 4 ?  $(elem).val() : '',
				cancel: function() {$(elem).val('');}
				//trigger: 'click'
			})
	});
	
}
if(window.addEventListener){window.addEventListener("load",function(){initdate();}, false);}else{window.attachEvent("onload",function(){initdate();});}
/*
*/