//回填类型数据{id:"id",value:"value",text:"text" }
function fillfield(area, item)
{
    //与FillData2,表单回填一至
    var objs = $(area).find("[postname='" + item["id"] + "']");
    if (objs.length == 1) {
        /*
        objs[0].value = item["value"];
        objs.prop("value", item["value"]);
        objs.attr("value", item["value"]);
        $(objs[0]).attr("ovalue", item["value"]);
        */
        try {
            objs[0].value = item["value"];
            objs.prop("value", item["value"]);//异步
            objs.attr("value", item["value"]);
            $(objs[0]).attr("ovalue", item["value"]);
            //回填后异步加载
            if (typeof (objs[0].onchange) == "function") {

                objs.trigger("change");
            }
        }
        catch (e) {
        }

        var etype = objs.attr("etype");
        if (typeof (etype) != "string") { return; }
        //选择回填到表单
        switch (etype) {
            case "date":
                objs[0].value = item["text"];
                break;
            case "departmentselect":
                //alert(item["text"]);
                var box = $(area).find("#" + item["id"] + "_box");
                $(area).find("[postname='" + item["id"] + "']").val(item["value"]);
                $(area).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 = $(area).find("#" + item["id"] + "_box");
                $(area).find("[postname='" + item["id"] + "']").val(item["value"]);
                $(area).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":
                $(area).find("#" + item["id"] + "_box span:eq(0)").text(item["text"]);
                break;
            case "html":
                try { KE.html(item["id"], objs[0].value); } catch (e) { }
                try { KE.setFullHtml(item["id"], objs[0].value); } catch (e) { }
                break;
        }
    }
    else {
        var _vs = "," + item["value"] + ",";
        for (var j = 0; j < objs.length; j++) {
            $(objs[j]).attr("ovalue", item["value"]);
            if (_vs.indexOf("," + objs[j].value + ",") > -1) {
                objs[j].checked = true;
            }
            else {
                objs[j].checked = false;
            }
        }
    }
};
//回填类型数据{id:"id",value:"value",text:"text" }
function fill(area, data)
{
    $.each(data, function (idx, item) {
        var objs = $(area).find("[postname='" + this["id"] + "']");
        if (objs.length > 0) {
            fillfield(area, item);
        }
    });
};

var subModel = function (modelid)
{
    var pmodel = this;
    this.modelid = modelid;
    this.table = $("#eformlist_" + modelid);
    this.tbody = this.table.find(">tbody");
    this.tfoot = this.table.find(">tfoot");
    this.input = $("#eformdata_" + modelid);
    this.model = this.input.val().toJson();
    this.addmode = parseInt(this.table.attr("addmode"));//0逐个添加,1原选择添加,2 Excel式添加,3原叠加添加,4新叠加添加
    this.data = this.model.get("eformdata_" + modelid);
    this.resetValue = function ()
    {
        this.input.val(this.model.toJson());
    };
    //显示隐藏的行
    this.showItem = function (index)
    {
        var item = this.data[index];
        item["Delete"] = "false";
        var tr = this.tbody.find(">tr:eq(" + index + ")");//有隐藏的，不能加visible
        tr.show();
        this.resetNumber();//更新顺序号
        this.resetCount();//更新子表数量
        this.resetValue();//更新值
        tr.find("input[postname='Delete']").val("false");        
    };
    //添加行
    this.addItem = function (callback) {
        var tr = this.tfoot.find("tr")[0].cloneNode(true);
        if (typeof (callback) == "function") {
            callback(tr);
        }
        this.tbody[0].appendChild(tr);
        return tr;
    };
    //根据json内容重新输出

    //清除数据和tbody内容
    this.clear = function ()
    {
    };
    //复制行
    this.copyItem = function (index)
    {
    };
    //删除行
    this.delItem = function (index) {
        var item = this.data[index];
        var tr = this.tbody.find(">tr:eq(" + index + ")");//有隐藏的，不能加visible
        if (item["ID"].length == 0) {
            this.data.remove(index);
            tr.remove();
        }
        else {
            item["Delete"] = "true";
            tr.find("input[postname='Delete']").val("true");
            tr.hide();
        }
        this.resetNumber();//更新顺序号
        this.resetCount();//更新子表数量
        this.resetValue();//更新值
        
    };
    //更新顺序号
    this.resetNumber = function (init)//更新顺序号
    {
        if (this.table.find(">thead").text().indexOf("序号") > -1)
        {
            if (!init) {
                this.tbody.find(">tr:visible").each(function (i, el) {
                    $(this).find(">td:eq(1)").text(i + 1);
                });
            }
            else {
                this.tbody.find(">tr").each(function (i, el) {
                    $(this).find(">td:eq(1)").text(i + 1);
                });
            }
        }
    };
    //初始，不可见时更新顺序号

    //更新子表数量
    this.resetCount = function ()//更新子表数量
    {
        var count = this.tbody.find(">tr:visible").length;
        $("input[id='count_"+ modelid +"']").val(count);
    };
    this.nextRowIndex = function ()
    {
        return this.tbody.children().length + 1;
    };
    this.curRowIndex = function () {
        return this.tbody.children().length;
    };
    //移动位置
    this.move = function (s, e)
    {
        if (e<0 ||  e > this.tbody.find(">tr").length-1){ return;}
        var se=this.data[s];//源位置
        var _data = "[]".toJson();
        for (var i = 0; i < this.data.length; i++)
        {
            if (i == s) { continue; }
            if (i == e) {
                if (s < e) { _data.append(this.data[i]); }
                _data.append(se);
                if (s > e) { _data.append(this.data[i]); }
            }
            else {
                _data.append(this.data[i]);
            }
        }
        this.model["eformdata_" + modelid] = _data;
        this.resetValue();
        var trs = this.tbody.find(">tr");
        if (s > e) { //向上            
            this.tbody[0].insertBefore(trs[s], trs[e]);
        }
        else {
            this.tbody[0].insertBefore(trs[s], trs[e].nextSibling);//下
        }
    };
    //列表合并到JSON
    this.pack = function ()
    {
        var data = "[]".toJson();
        this.tbody.find(">tr").each(function (i, el) {
            var drow = areaToJson(el);
            data.append(drow);
            addPack(el);
        });
        this.data = data;
        this.resetValue();       
    };
    return this;
};


//回填窗口 原：OpenFillDlg model_openfill
function model_openfill(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/FillData.aspx?modelid=" + modelid + (typeof (AppItem) == "string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "");
    var query = "";
    if (typeof (OpenFillDlg_before) == "function") {
        var _back = OpenFillDlg_before(modelid);//function OpenFillDlg_before(modelid) {return {result:true,query:"s3=3"};};
        if (typeof (_back) == "object") {
            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();
    //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);
			}
		});
	*/
}
//选择添加窗口 原：OpenFillSelectDlg
function model_openselect(modelid, title, width, height, area, fmodelid, clientMode)
{
    var url = virtualPath + "Plugins/FillSelectData.aspx?modelid=" + modelid + (typeof (AppItem) == "string" && AppItem.length > 0 ? "&AppItem=" + AppItem : "");
    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);
            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();
        }
    });
};
//选择添加 原：excel_SelectDataN
function model_selectadd(model, chk, data, fieldarr)
{
    if (chk.checked) //add
    {
        for (var j = 0; j < model.data.length; j++)
        {
            var _data = model.data[j];
            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, "\\'");
                if (typeof (_data[name]) != "string") { return true; }   
                allcount++;
                if (_data[name] == value) { hascount++; }
            });
            if (allcount == hascount && allcount > 0)
            {
                model.showItem(j);
                return;
            }
        }

   
        var html = getModelAddHTML(model.modelid);
        var div = document.createElement("div");
        div.innerHTML = html;
        div.style.display = "none";
        document.body.appendChild(div);
        fill(div, data);
        //var _back = eCheckform(div);

        var obj = areaToJson(div);
        var tr = model.addItem();
        model_bind(obj, tr);
        model.data.append(obj);
        model.resetNumber();//更新顺序号
        model.resetCount();//更新子表数量
        model.resetValue();//更新值
        $(div).remove();

    }
    else //remove
    {
        for (var j = 0; j < model.data.length; j++) {
            var _data = model.data[j];
            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, "\\'");
                if (typeof (_data[name]) != "string") { return true; }
                allcount++;
                if (_data[name] == value) { hascount++; }
            });
            if (allcount == hascount && allcount > 0) {
                model.delItem(j);
                return;
            }
        }
    }

};
function model_selectrow(modelid, singleFields) {
    var fieldstr = singleFields || "";
    var fieldarr = [];
    if (fieldstr.length > 0) { fieldarr = fieldstr.split(","); }
    var src = getEventObject();
    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; }
    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;
        if (src.parentNode.tagName == "A" && src.parentNode.getAttribute("jsondata") != null) {
            src = src.parentNode;
        }
    }
    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");
    }
    values = decode64(values);
    var json = JSON.parse(values);
    var data = new eJson();
    $.each(json, function (idx, item) {
        data.append(item["id"], item["value"]);
        data.append(item["id"] + "_Text", item["text"]);
    });
    //alert(modelid);
    var model = new parent.subModel(modelid);
    //alert(data.toJson());

    if (chk.checked) //add
    {
        for (var j = 0; j < model.data.length; j++) {
            var _data = model.data[j];
            var allcount = 0;
            var hascount = 0;
            $.each(json, 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, "\\'");
                if (typeof (_data[name]) != "string") { return true; }
                allcount++;
                if (_data[name] == value) { hascount++; }
            });
            if (allcount == hascount && allcount > 0) {
                model.showItem(j);
                return;
            }
        }
      
        if (model.addmode == 0) //逐个添加
        {
            var html = parent.getModelAddHTML(model.modelid);
            var div = document.createElement("div");
            div.innerHTML = html;
            div.style.display = "none";
            parent.document.body.appendChild(div);
            parent.fill(div, json);
            //var _back = eCheckform(div);

            var obj = parent.areaToJson(div);
            var tr = model.addItem();
            model_bind(obj, tr);
            model.data.append(obj);
            model.resetNumber();//更新顺序号
            model.resetCount();//更新子表数量
            model.resetValue();//更新值
            $(div).remove();
        }
        else
        {
            var tr = model.addItem();
            parent.fill(tr, json);
            data = areaToJson(tr);
            model.data.append(data);

            var idx = model.curRowIndex();
            renameControls(tr, idx); //重命名控件
            model.resetNumber();//更新顺序号
            model.resetCount();//更新子表数量
            model.pack();
        }
    }
    else //remove
    {
        //alert("remove" + model.data.length);
        for (var j = 0; j < model.data.length; j++) {
            var _data = model.data[j];
            var allcount = 0;
            var hascount = 0;
            $.each(json, function (idx, item) {
                var name = item["id"];
                //alert(fieldarr + ":" + name);
                if (fieldarr.length > 0 && fieldarr.indexOf(name) == -1) { return true; }
                var value = item["value"];
                value = value.replace(/'/gi, "\\'");
                if (typeof (_data[name]) != "string") { return true; }
                allcount++;
                if (_data[name] == value) { hascount++; }
            });
            if (allcount == hascount && allcount > 0) {
                model.delItem(j);
                return;
            }
        }
    }
};

function upItem(obj)
{
    var tr = $(obj).parents("[eitemrow]:first");
    var index=tr.index();
    if (index == 0) return;
    var tb = $(obj).parents("table:first");
    var modelid = tb.attr("modelid");
    var model = new subModel(modelid);
    model.move(index, index - 1);
};
function downItem(obj) {
    var tr = $(obj).parents("[eitemrow]:first");
    var index = tr.index();  
    var tb = $(obj).parents("table:first");
    var modelid = tb.attr("modelid");
    var model = new subModel(modelid);
    if (index > model.tbody.find(">tr").length - 1) { return; }
    model.move(index, index + 1);
};

//回填数据：原：FillData2
function model_fill(values, cancelclose)
{
    //return FillData2(values, cancelclose);
    var json = decode64(values);
    alert(json);
    var data = JSON.parse(json);
    parent.fill(parent.fillparent, data);
    if (!cancelclose && parent.arrLayerIndex.length > 0) {
        parent.layer.close(parent.arrLayerIndex.pop());
    }
};
//JSON绑定到区域内控件
function model_bindarea(area, data)
{   
    //来源form_editN
    data.foreach(function (e)
    {
        if (e.toLowerCase() == "pkid") { return; }
        /*行处理*/
        if (typeof (e) == "string")
        {
            var td = $(area).find("[name='td_" + e + "']");
            if (td.length > 0)
            {
                //alert(e);
            }
        }

        var ctrl = $(area).find("[postname='" + e + "']");
        if (e.toLowerCase() == "id")
        {
            ctrl = $(area).find("[postname='" + e + "']:first");
        }
        if (!ctrl)
        {
            //编辑只读
            ctrl = $("#" + e + "_box");
            if (ctrl.length > 0) {
                if (data[e + "_Text"])
                {
                    ctrl.html(data[e + "_Text"]);
                }
                else
                {
                    ctrl.html(data[e]);
                }
            }
            return;
        }
       // alert(e + "::" + ctrl.length);
        if (ctrl.length == 0) { return; }
        if (ctrl.length == 1) { ctrl = ctrl[0]; }
        if (typeof (data[e]) == "object")
        {
           
            var node = data[e];
            ctrl.value = "{\"" + e + "\":" + node.toJson() + "}";
            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);
            }

            //alert(listobj.length + "::" + listobj.attr("class"));
            if (listobj.length > 0 && listobj.attr("class") == "divsubList") {
                var _modelid = e.replace("eformdata_", "");
                var _html = getModelAddHTML(_modelid);
                node.foreach(function (x) {
                    listobj.append(_html);
                    var dd = listobj.find("dl:last dd");
                    JsonToDD(node[x], dd);
                });
            }
            else
            {
                var modelid = e.replace("eformdata_", "");
                var model = new subModel(modelid);
                model.tbody.html('');//先清空
                node.foreach(function (x) {
                    var tr = model.addItem();
                    model_bindarea(tr, node[x]);//绑定控件
                    model_bind(node[x],tr);//绑定HTML                  
                });
                model.resetNumber(true);//更新顺序号，不显示，没用

                //JsonToTable(node, e.replace("eformdata_", "eformlist_"));
            }
        }
        else
        {
            if (typeof (e) == "string")
            {
                
                if (ctrl.tagName)
                {

                     //alert(ctrl.tagName + "::" + ctrl.value + "::" + data[e]);
                   
                    //var type = Attribute(ctrl, "type").toLowerCase();
                    var type = "text";
                    if (ctrl.tagName != "INPUT") {
                        type = ctrl.tagName.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();
                    //alert(v);
                    //return;
                    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++) {
                            //$(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();
                    }
                    if (etype == "singleuser" && ctrl.value.length > 0 && ctrl.name.toLowerCase().indexOf("_text") > -1)
                    {
                        $(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);
                    }
                    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;
                            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;
                        }
                    }
                }
            }
        }
    });
};
//绑定到表单
function model_bindform(modelid,index)
{
    var model = new subModel(modelid);
    var data = model.data[index];
    var frm = document.forms["form_" + modelid];
    var form = $("#form_" + modelid);
    model_bindarea(form,data);
};
//绑定行HTML数据
function model_bind(obj, tr)
{
    //form_save
    $(tr).find("[name]").each(function (i, elem) {
        var name = elem.getAttribute("name");
        if (name)
        {
            var etype = $(elem).attr("etype");
            if (etype == "label") { return true; } //label退出当次
            var ewidth = $(elem).attr("ewidth");
            var eheight = $(elem).attr("eheight");
            if ($(elem).find("label").length > 0)
            {
                elem = $(elem).find("label").get(0);
            }
            var _opar = $(tr).parents("table:first").find(">tfoot tr [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")
                    {
                        if (obj[name].length > 0)
                        {
                            $(elem).html('<a href="' + obj[name] + '" target="_blank">查看</a>');
                        }
                        return true;
                    }
                    if (etype == "image")
                    {
                        $(elem).find("img").attr("src", obj[name]);
                        return true;
                    }
                    if (etype == "images")
                    {
                        var div = $(elem).find(".efiles-body div");
                        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, " ");//
                    }
                    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 = ""; }
                }
            }
        }
    });
};

//逐个添加-查看:原form_viewN
function model_viewItem(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"; }
    var tr = null;
    if (obj.tagName == "TR" && obj.getAttribute("eRowID") != null)
    {
        tr = obj;
    }
    else
    {
        tr = $(obj).parents("tr[eRowID]:first");
        if (tr.length == 0) { return; }
        tr = tr[0];
    }  
    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) 
	    {
	        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(); }
    });
};
//逐个添加-保存:原form_saveN
function model_saveItem(modelid) {
    var frm = document.forms["form_" + modelid];
    if (!frm) { layer.msg("表单form_" + modelid + "不存在!"); return false; }
    var _back = eCheckform(frm);
    if (!_back) { return false; }
    //var index = parseInt(frm["Index"].value);
    var index = -1;
    if ($("#form_" + modelid + " input[postname='Index']").length > 0) {
        index = parseInt($("#form_" + modelid + " input[postname='Index']").val());
    }
    var obj = areaToJson(frm);
    var model = new subModel(modelid);
    if (index == -1)//添加
    {
        model.data.append(obj); 
        var tr = model.addItem();
        model.resetNumber();//更新顺序号
        model.resetCount();//更新子表数量
        model_bind(obj, tr);
    }
    else
    {
        model.data[index] = obj;
        var tr = model.tbody.find(">tr:eq(" + index + ")");//有隐藏的，不能加visible
        model_bind(obj, tr);
    }
    model.resetValue();//更新值

    return true;

};
//逐个添加-删除：原form_deleteN
function model_delItem(obj, modelid, delText)
{
    if (!delText) { delText = "删除"; }
    if (!confirm("确认要" + delText + "吗？")) { return; }
    //var tr = $(obj).parents("tr[eRowID]:first");//
    var tr = $(obj).parents("tr[eitemrow]:first");
    if (tr.length == 0) { return; }
    tr = tr[0];
    var model = new subModel(modelid);
    var index = $(tr).index();
    model.delItem(index);
};
//逐个添加-编辑：原form_editN
function model_editItem(obj, 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 src = getEventObject();
    if (src.tagName == "A" && src.className.toLowerCase().indexOf("btn") == -1)//复制行
    {
        return;
    }
    if (src.tagName == "DIV" && typeof (src.onclick) == 'function')
    {
        return;
    }
    if (src.tagName.toLowerCase() == "a" && src.className == "btndel") { return; }


    var tr = null;
    if (obj.tagName == "TR" && (obj.getAttribute("eitemrow") != null || obj.getAttribute("eRowID") != null)) {
        tr = obj;
    }
    else
    {
        tr = $(obj).parents("tr[eRowID]:first");
        if(tr.length==0){return;}
        tr=tr[0];
    }
    if (tr.getAttribute("eRowID") == null) {
        tr = getParent(tr, "tr");
    }
    var html = getModelAddHTML(modelid);
    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 = model_saveItem(modelid);
	        if (_back) { arrLayerIndex.pop(); layer.close(index); }
	    },
	    btn2: function (index, layero)
	    {
	        arrLayerIndex.pop();
	    },
	    cancel: function (index, layero) 
	    {
	        arrLayerIndex.pop();
	    },
	    success: function (layero, index) 
	    {
	        arrLayerIndex.push(index);
	        model_bindform(modelid, $(tr).index());
	        //alert($(tr).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);
	        });
	        $("#form_" + modelid + " input[postname='Index']").val($(tr).index());
	        initdate($('.layui-layer-content'));
	        var area = $(".layui-layer-content");
	        Resize_eControl(area);
	        if (typeof (form_edit_finsh) == "function") { form_edit_finsh(modelid, area); }
	        if (typeof (form_edit_finish) == "function") { form_edit_finish(modelid, area); }
	    },
	    end: function (index) { arrLayerIndex.pop(); }
    });

};
//逐个添加-添加:原form_addN
function model_addItem(obj, modelid, title, width, height)
{
    var html = getModelAddHTML(modelid);
    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 = model_saveItem(modelid);
            if (_back) { arrLayerIndex.pop(); layer.close(index); }
	    },
        btn2: function (index, layero) {
	        arrLayerIndex.pop();
        },
        cancel: function (index, layero) {
	        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);
	        });
	        $("#form_" + modelid + " input[postname='Index']").val("-1");
	        initdate($('.layui-layer-content'));//初始化移动端日期选择
	        var area = $(".layui-layer-content");
	        Resize_eControl(area);
	        if (typeof (form_add_finsh) == "function") { form_add_finsh(modelid, area); }
	        if (typeof (form_add_finish) == "function") { form_add_finish(modelid, area); }
	    },
        end: function (index) { arrLayerIndex.pop(); }
    });
};

//加载草稿箱:来源form_load
function model_loadDraft(modelid)
{
    var input = getobj("eformdata_" + modelid);
    var model = input.value.toJson();
    model = model.get("eformdata_" + modelid);
    if (model.length == 0) { return; }
    var data = model.get(0);
    var form = $("#form_" + modelid);
    model_bindarea(form, data);
};
//加载缓存结果
function model_autocache(modelid)
{
    return model_loadDraft(modelid);
};

//获取模块添加HTML：原getAddHTMLN
function getModelAddHTML(modelid)
{
    var html = "";
    var modelhtml = eval("window.ModelHTML_" + modelid.replace(/-/gi, ""));
    if (modelhtml)
    {
        return modelhtml;
    }
    else {
        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 (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;');
    }
    return html;
}
function overlay_add(obj, modelid) {
    var model = new subModel(modelid);
    var tr = model.addItem();
    var obj = areaToJson(tr);
    //alert(obj.toJson());
    model.data.append(obj);
    var idx = model.curRowIndex();
    //alert(idx);
    renameControls(tr, idx); //重命名控件
    model.resetCount();//更新子表数量
    model.resetValue();//
}
function overlay_delete(obj, modelid) {
    return model_delItem(obj, modelid);
    var _back = confirm('确认要删除吗？');
    if (!_back) { return; }
    var tr = $(obj).parents("tr[eitemrow]:first");
    var model = new subModel(modelid);
    var index = tr.index();
    model.delItem(index);
}
function excel_add(obj, modelid) {
  
    var model = new subModel(modelid);
    var tr = model.addItem();
    var obj = areaToJson(tr);
    //alert(obj.toJson());
    model.data.append(obj);
    var idx = model.curRowIndex();
    //alert(idx);
    renameControls(tr, idx); //重命名控件
    model.resetNumber();//更新顺序号
    model.resetCount();//更新子表数量
    model.resetValue();//
};
function excel_delete(obj, modelid, cancelconfirm)
{
    return model_delItem(obj, modelid);
    if (!cancelconfirm) {
        if (!confirm("确认要删除吗？")) { return; }
    }
    var tr = $(obj).parents("tr[eitemrow]:first");
    var model = new subModel(modelid);
    var index = tr.index();
    model.delItem(index);
};


function tbody_pack(modelid)
{
    var table = $("#eformlist_" + modelid);
    var tbody = table.find(">tbody");
    var tfoot = table.find(">tfoot");
    if (tfoot.length > 0) { addPack(tfoot); }
    var input = $("#eformdata_" + modelid);


    var model = input.val().toJson();
    var data = "[]".toJson();

    tbody.find(">tr").each(function (i, el) {
        var drow = areaToJson(el);
        data.append(drow);
    });
    model["eformdata_" + modelid] = data;
    input.val(model.toJson());
    addPack(table);
}

//区域到JSON：来源formToJson
function areaToJson(area)//eJson2
{    
    var elements = $(area).find("input,select,textarea");
    if (elements.length == 0) return new eJson2();
    clearPack($(area));

    $(area).find(".excelTable,.overlaytable").each(function (i, el) {
        if ($(this).attr("exclude") == "undefined" || $(this).attr("exclude") != "true") {
            var modelid = $(this).attr("id").replace("eformlist_", "");
            tbody_pack(modelid);
            //alert($(this).attr("id"));
            //var model = new subModel(modelid);
            //model.pack();
            //alert("A" + model.input.val());
        }
    });
    var ctrls = new Array();
    $(area).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); }

    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) {
            var postname = elements[i].getAttribute("postname");
            if (!postname) { continue; }
            var chks = $(area).find("[postname='" + postname + "']:checked");
            if (chks.length == 0 && typeof (json[postname]) == "undefined") {
                json.append(postname, "");
                json.append(postname + "_Text", "");
            }
            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 (elements[i].name.toLowerCase().indexOf("eformdata_") > -1) //子模块对象 
        {
            var _json = value.toJson();
            _json = _json.get(elements[i].name);
            json.append(elements[i].name, _json);
            json[elements[i].name] = _json;
        }
        else {
            value = value.autotrim(trimtype).encode() || "";
            var postname = elements[i].name;
            if (elements[i].getAttribute("postname")) {
                postname = elements[i].getAttribute("postname");
            }

            //if (!json[postname])
            if (typeof (json[postname]) == "undefined") {
                //json[elements[i].name] = value;
                if ((value.startsWith("[") && value.endsWith("]")) || (value.startsWith("{") && value.endsWith("}"))) {
                    var _json = value.toJson();
                    json.append(postname, _json);
                }
                else {
                    json.append(postname, value);
                    if (postname.toLowerCase() == "id") {
                        json.append("PKID", value);
                        //alert(postname + ":" + value);
                    }
                }
            }
            else {
                json[postname] += "," + value;
            }

            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(postname + "_" + x);
                    if (!tmp || tmp.value.length == 0) { break; }
                    if (txt.length > 0) { txt += ","; }
                    txt += tmp.options[tmp.selectedIndex].text;
                }
                json[postname + "_Text"] = removeHTMLTag(txt).encode();
            }

            if (elements[i].tagName.toLowerCase() == "select" && elements[i].selectedIndex > -1) {
                if (elements[i].getAttribute("multiple") == null) {
                    json[postname + "_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[postname + "_Text"] = _tmp;
                }
            }

            if (type == "hidden" && elements[i].getAttribute("text")) {
                var etype = elements[i].getAttribute("etype");
                if (etype == "label") {
                    json[postname + "_Text"] = elements[i].getAttribute("text").encode();
                }
            }
            if (type == "radio" || type == "checkbox") {
                if (elements[i].getAttribute("text")) {
                    //if (!json[postname + "_Text"])
                    if (typeof (json[postname + "_Text"]) == "undefined") {

                        json[postname + "_Text"] = removeHTMLTag(elements[i].getAttribute("text")).encode();
                    }
                    else {
                        json[postname + "_Text"] += "," + removeHTMLTag(elements[i].getAttribute("text")).encode();
                    }
                }
            }
            //alert(value + "::" + postname);
            if (elements[i].name.toLowerCase().indexOf("_text") > -1 && (elements[i].getAttribute("etype") == "singleuser" || elements[i].getAttribute("etype") == "multipleuser")) {
                //if (!json[postname.replace("_text", "") + "_Text"])
                if (typeof (json[postname.replace("_text", "") + "_Text"]) == "undefined") {
                    json[postname.replace("_text", "") + "_Text"] = removeHTMLTag(elements[i].value).encode();
                }
                else {
                    json[postname.replace("_text", "") + "_Text"] += "," + removeHTMLTag(elements[i].value).encode();
                }
            }
        }
    }
    //addPack(frm);
    return json;
}


//单个添加：表单更新到JSON
function formToJson(frm)//eJson2
{  
    if (typeof (frm) == "string") { frm = document.forms[frm]; }
    return areaToJson(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")
		{
			form_area=$(this).parent();			
			excel_pack($(this).attr("id").replace("eformlist_",""));
		}
	});
    */


    $(frm).find(".excelTable,.overlaytable").each(function (i, el) {
        if ($(this).attr("exclude") == "undefined" || $(this).attr("exclude") != "true") {
            //tbody_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));
        }
    });
    //alert(ctrls.length);
    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) {
            var postname = elements[i].getAttribute("postname");
            if (!postname) { continue; }
            var chks = $(frm).find("[postname='" + postname + "']:checked");
            if (chks.length == 0 && typeof (json[postname]) == "undefined") {
                json.append(postname, "");
                json.append(postname + "_Text", "");
            }
            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 (elements[i].name.toLowerCase().indexOf("eformdata_") > -1) //子模块对象 
        {
            var _json = value.toJson();
            _json = _json.get(elements[i].name);
            json.append(elements[i].name, _json);
            json[elements[i].name] = _json;
        }
        else {
            value = value.autotrim(trimtype).encode() || "";
            var postname = elements[i].name;
            if (elements[i].getAttribute("postname")) {
                postname = elements[i].getAttribute("postname");
            }

            //if (!json[postname])
            if (typeof (json[postname]) == "undefined") {
                //json[elements[i].name] = value;
                if ((value.startsWith("[") && value.endsWith("]")) || (value.startsWith("{") && value.endsWith("}"))) {
                    var _json = value.toJson();
                    json.append(postname, _json);
                }
                else {
                    json.append(postname, value);
                }
            }
            else {
                json[postname] += "," + value;
            }

            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(postname + "_" + x);
                    if (!tmp || tmp.value.length == 0) { break; }
                    if (txt.length > 0) { txt += ","; }
                    txt += tmp.options[tmp.selectedIndex].text;
                }
                json[postname + "_Text"] = removeHTMLTag(txt).encode();
            }

            if (elements[i].tagName.toLowerCase() == "select" && elements[i].selectedIndex > -1) {
                if (elements[i].getAttribute("multiple") == null) {
                    json[postname + "_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[postname + "_Text"] = _tmp;
                }
            }

            if (type == "hidden" && elements[i].getAttribute("text")) {
                var etype = elements[i].getAttribute("etype");
                if (etype == "label") {
                    json[postname + "_Text"] = elements[i].getAttribute("text").encode();
                }
            }
            if (type == "radio" || type == "checkbox") {
                if (elements[i].getAttribute("text")) {
                    //if (!json[postname + "_Text"])
                    if (typeof (json[postname + "_Text"]) == "undefined") {

                        json[postname + "_Text"] = removeHTMLTag(elements[i].getAttribute("text")).encode();
                    }
                    else {
                        json[postname + "_Text"] += "," + removeHTMLTag(elements[i].getAttribute("text")).encode();
                    }
                }
            }
            //alert(value + "::" + postname);
            if (elements[i].name.toLowerCase().indexOf("_text") > -1 && (elements[i].getAttribute("etype") == "singleuser" || elements[i].getAttribute("etype") == "multipleuser")) {
                //if (!json[postname.replace("_text", "") + "_Text"])
                if (typeof (json[postname.replace("_text", "") + "_Text"]) == "undefined") {
                    json[postname.replace("_text", "") + "_Text"] = removeHTMLTag(elements[i].value).encode();
                }
                else {
                    json[postname.replace("_text", "") + "_Text"] += "," + removeHTMLTag(elements[i].value).encode();
                }
            }
        }
    }
    //addPack(frm);
    return json;
}
//JSON回填到卡片
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());
                    }
                }
            });
        }
    });
}
//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];
    $(tbody).html('');//先清空
    //return;
    var clsname = table.className;
    var idx = 1;
    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 + "']");
                var type = $(els).attr("etype").toLowerCase() || "";
                name = name.replace("td_", "");
                //var _opar= $(tr).find("[name='" + name + "']").get(0);//移动端时有div 和 td两项
                els.each(function (j, _opar) {
                    // alert(name + ":" + _opar.tagName + ":" + type);
                    if (_opar.tagName == "TD" || _opar.tagName == "DIV") {
                        if (_opar.innerHTML == "{row:index}") {
                            _opar.innerHTML = idx;
                        }
                        else {
                            if (data[e][name + "_Text"]) {
                                _opar.innerHTML = data[e][name + "_Text"].decode();
                            }
                            else {
                                if (data[e][name]) {
                                    if (type == "images") {
                                        var jsonstr = data[e][name].decode();
                                        if (jsonstr.length > 3) {
                                            var imgs = jsonstr.toJson();
                                            var html = '<div class="efiles-body eimages_view" ebinded="true">';
                                            for (var i = 0; i < imgs.length; i++) {
                                                html += '<div url="' + imgs[i].url + '" style="width:90px;height:110px;"><img src="' + imgs[i].url + '" /><img title="删除" class="del" src="' + '../images/none.gif" /></div>';
                                            }
                                            html += '</div>';
                                            _opar.innerHTML = html;
                                        }
                                    }
                                    else {
                                        _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);
        idx++;
        //alert(tr.outerHTML);
    });
    //alert(clsname);
    if (clsname == "excelTable" || clsname == "eDataTable") {

        var tr = $(table).find(">thead>tr>td:contains('序号')");
        if (tr.length > 0) {
            var _index = tr.index();
            //alert(_index + "::" + $(tbody).find("tr").length);
            //选项卡隐藏的会取不到
            $(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 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 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 + ":X");
    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;
        if (inputs[i].getAttribute("postname")) { postname = inputs[i].getAttribute("postname"); }
      
        if (postname.toLowerCase() == "index") { continue; }

        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" && $(inputs[i]).attr("etype") == "switcher") { continue; }
        if ((type == "radio" || type == "checkbox") && inputs[i].checked == false) { value = ""; continue; }

        if (postname.toLowerCase().indexOf("eformdata_") > -1) //子模块对象 
        {
            var _json = value.toJson();
            _json = _json.get(postname);
            json.append(_json);
        }
        else
        {
            //alert(postname + ":" + typeof (json[postname]));
           // alert(postname + ":" + value);
            //if(!json[postname])
            if (typeof (json[postname]) == "undefined") {
                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="";
    }
    //alert(json.toJson());
    //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;
}

function ItemToJson(div) //div
{
    var _modelid = div.attr("id").replace("eformlist_", "");
    var txtid = div.attr("id").replace("eformlist_", "eformdata_");
    var _data = "[]".toJson();

    resetCount(div);
    div.find(">dl").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());
}

//Excel式添加



//搜索回填窗口
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") {
            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();
        }
    });
};



//选择添加
//回填到表单
var fillparent = null;
var form_area;//保存区域对象Jquery对象


//配置的自定义模块
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_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 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); }
}

//OK
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();
}
//OK
function form_add(obj, modelid, title, width, height, url) {
    var html = getAddHTMLN(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, area); }
	    if (typeof (form_add_finish) == "function") { form_add_finish(modelid, area); }
	}
	 , 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 = getAddHTMLN(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, area); }
	    if (typeof (form_edit_finish) == "function") { form_edit_finish(modelid, area); }
	}
	  , 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");
        tr = $(obj).parents("tr[eRowID]:first");
        if (tr.length == 0) { return; }
        tr = tr[0];
    }

    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");
    //}
    var tr = $(obj).parents("tr[eRowID]:first");
    if (tr.length == 0) { return; }
    tr = tr[0];
    //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 otds = $(otr).find(">td");
    var row_index = -1;
    for (var i = 0; i < otds.length; i++) {
        if (otds[i].innerHTML.toLowerCase().indexOf("{row:index}") == 0) {
            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 = areaToJson(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");
    var otds = $(otr).find(">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;
}