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

/*基础*/
document.write('<script src="' + virtualPath + 'Scripts/jquery.js"></script>');


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

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


function getVirtualPath()
{
    var elements = document.getElementsByTagName('script');
    var element=elements[elements.length-1];
    var src=element.getAttribute("src");
    if(src.toLowerCase().indexOf("/")==0)
    {
        var i= src.toLowerCase().indexOf("/scripts/");
        if(i>0)
        {
            return src.substring(0,i+1);
        }
    }
    if(src.toLowerCase().indexOf("http")>-1)
    {
        var i= src.toLowerCase().indexOf("/scripts/");
        if(i>0)
        {
            return src.substring(0,i+1);
        }
    }
    //if(src.startsWith("/")){return "/";}
    if(src.indexOf("/")==0){return "/";}
    var virtualPath="";
    if(src.indexOf("../")>-1)
    {
        for(var i=0;i<src.match(/\.\.\//ig).length;i++)
        {
            virtualPath+="../";
        }
    }
    return virtualPath;
};
function viewStyle(styleid,width,height)
{
    var _width=typeof(width)=="undefined" ? "95%" : width;
    var _height=typeof(height)=="undefined" ? "95%" : height;	

    var url = virtualPath + "Plugins/viewStyle.aspx?styleid=" + styleid;
    url += "&t=" + now();
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title: '预览样式',
        moveOut: true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area: [_width, _height],
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) {
            arrLayerIndex.pop();
        }
    });
};

function treecheckbox_selectall(obj)
{
    $(obj).parent().find("input[type='checkbox']").prop("checked",true);
};
function treecheckbox_invert(obj)
{
    $(obj).parent().find("input[type='checkbox']").each(function(i,el){
        el.checked=!el.checked;
    });
};
function treecheckbox_cancel(obj)
{
    $(obj).parent().find("input[type='checkbox']").prop("checked",false);
};
function getAction()
{
    return document.location.href.getquerystring("act");
};
function TreeModelUpdate()
{
    if (treefromact == "del") {
        var tr = $("tr[eRowID='" + treefromid + "']");
        var parid = tr.attr("parentid");
        if (parid.length > 0)
        {
            var trs = tr.parents("tbody:first").find("tr[parentid='" + parid + "']");
            if (trs.length == 1)
            {
                var ptr = $("tr[eRowID='" + parid + "']");
                if (ptr.find(".treeItem a").hasClass("open")) { ptr.find(".treeItem a").removeClass("open"); }
                if (ptr.find(".treeItem a").hasClass("close")) { ptr.find(".treeItem a").removeClass("close"); }
            }
        }
        hideTreeModelTrs(tr);
        tr.remove();

    }
    else if (treefromact == "add") {
        var url = document.location.href;
        url = url.removequerystring("page");
        url = url.addquerystring("parid", treefrompid);
        $.ajax({
            type: "get",
            async: false,
            url: url,
            dataType: "json",
            success: function (data) {
                if (typeof (data.trs) != "undefined") {
                    if (treefrompid.length > 0)
                    {
                        var tr = $("tr[eRowID='" + treefrompid + "']");
                        var a = tr.find(".treeItem a");
                        if (!a.hasClass("open") && !a.hasClass("close")) {
                            a.addClass("close");
                            a.attr("onclick", "getTreeModelList(this,'" + treefrompid + "');");
                            //a.attr("onclick", "showTreeModelList(this);");
                        }
                        else {
                            var clickstr = a.attr("onclick");
                            if (a.hasClass("open"))
                            {
                                var url = document.location.href;
                                url = url.removequerystring("page");
                                url = url.addquerystring("parid", treefrompid);
                                $.ajax({
                                    type: "get",
                                    async: false,
                                    url: url,
                                    dataType: "json",
                                    success: function (data) {
                                        if (typeof (data.trs) != "undefined") {
                                            removeTreeModelTrs(tr);
                                            tr.after(data.trs);
                                            var _width = parseInt(a.get(0).parentNode.style.textIndent);
                                            a.parents("tbody:first").find("tr[parentid='" + treefrompid + "'] .treeItem").css("text-indent", (_width + 25) + "px");
                                        }
                                    }
                                });
                                return;
                            }
                            if (a.hasClass("close"))
                            {
                                removeTreeModelTrs(tr);
                                a.attr("onclick", "getTreeModelList(this,'" + treefrompid + "');");
                                return;
                            }
                        }
                    }
                    else
                    {
                        $(".eDataTable tbody tr").remove();
                        $(".eDataTable tbody").append(data.trs);
                    }
                }
            }
        });
    }
    else {
        var tr = $("tr[eRowID='" + treefromid + "']");
        replaceTreeModelTr(tr);
    }
};
function replaceTreeModelTr(tr)
{
    var url = document.location.href;
    url = url.removequerystring("page");
    url = url.addquerystring("rowid", treefromid);
    $.ajax({
        type: "get",
        async: false,
        url: url,
        dataType: "json",
        success: function (data) {
            if (typeof (data.trs) != "undefined") {
                var odiv = tr.find(".treeItem");
                tr.attr("eRowID", treefromid + "_bak");
                tr.after(data.trs);
                tr.hide();
                var ntr = $("tr[eRowID='" + treefromid + "']");
                var ndiv = ntr.find(".treeItem");
                ndiv.attr("style", odiv.attr("style"));
                ndiv.find("a").attr("class", odiv.find("a").attr("class"));
                ndiv.find("a").attr("onclick", odiv.find("a").attr("onclick"));
                tr.remove();
                //tr.prop("outerHTML", data.trs);////data.table.decode()                  
                //var ntr = document.createTextNode();//tr.replaceWith()               
            }
        }
    });
};

//获取添加方式,0:逐个添加;1:选择添加;2:Excel式添加;3:叠加添加
function getAddMode(obj)
{
    var tb = $(obj).parents("table:first");
    if (tb.length == 0) return 0;
    var addmode = tb.attr("addmode");
    return parseInt(addmode);
};
//获取当前行号
function getRowNumber(obj)
{
    return $(obj).parents("[eitemrow]:first").index() + 1;
};
//获取最新行号
function getNextRowIndex(obj) {
    var addmode = getAddMode(obj);
    var result = 1;
    switch (addmode)
    {
        case 0://逐个添加
        case 1://选择添加
        case 2://Excel式添加
            result = $(obj).parents("table:first").find(">tbody").children().length + 1;
            break;
        case 3://叠加添加
            result = getParentBody(obj).find(">dl").length + 1;
            break;
    }
    return result;
};
//更新顺序号
function resetNumber(table)
{
    var tbody = $(table).find(">tbody");
    if ($(table).find(">thead").text().indexOf("序号") > -1) {
        tbody.find(">tr:visible").each(function (i, el) {
            $(this).find(">td:eq(1)").html(i + 1);
        });
    }
};
//重命名控件
function renameControls(area,idx)
{
    $(area).find("input[type!='hidden'],select,textarea").each(function (i, el) {
        var name = $(this).attr("postname");
        $(this).attr("name", "row_" + idx + "_" + name);
        //$(this).attr("id", "row_" + idx + "_" + name);
    });
};
//获取上级对象
function getParentBody(obj)
{
    return $(obj).parents("[eitemrow]:first").parent();
    /*
    var tb = $(obj).parents("table:first");
    if (tb.length == 0) return null;
    var addmode = tb.attr("addmode");
    var modelid = tb.attr("modelid");
    switch (addmode) {
        case "0"://逐个添加
        case "1"://选择添加
        case "2"://Excel式添加
            return tb.find("tbody");
        case "3"://叠加添加
            return $(obj).parents("[eitemrow]:first").parent();
    }
    return null;
    */
};
//更新子表数量
function resetCount(area)//tbody or div
{   
    var count = 0;
    if ($(area).get(0).tagName == "TBODY")
    {
        count = $(area).find(">tr:visible").length;
        $(area).parent().parent().find("input[id^='count_']").val(count);
    }
    else
    {
        count = $(area).find(">dl:visible").length
        $(area).parent().find("input[id^='count_']").val(count);
    }
};
//解决select选择状态不被克隆
function updateSelected(obj)
{
    $(obj).find("select").each(function (i, el) {
        var opt = el.options[el.selectedIndex];
        $(opt).attr("selected", "selected");
    });
};
//复制行
function copyItem(obj)
{
    var tb = $(obj).parents("table:first");
    if (tb.length == 0) return;
    var addmode = tb.attr("addmode");
    //alert(addmode);
    var modelid = tb.attr("modelid");

    var input = getobj("eformdata_" + modelid);
    var model = input.value.toJson();
    var _model = model.get("eformdata_" + modelid);
    var robj = null;

    if (addmode == "0")//0逐个添加
    {      
        var tr = $(obj).parents("tr[eitemrow]:first");
        if (tr.length == 0) { return; }
        tr = tr[0];
        updateSelected(tr); //解决select选择状态不被克隆
        var index = tr.Index();

        var item = _model[index].toJson();
        var itemjson = new eJson2(item.toJson());
        clearJsonID(itemjson);//清除ID
        _model.splice(index + 1, 0, itemjson);//在指定位置插入JSON
        var clonetr = tr.cloneNode(true);
        var idx = getNextRowIndex(obj);
        renameControls(clonetr,idx);//重命名控件
        robj = clonetr;//返回对象
        $(tr).after(clonetr);
        $(input).val(model.toJson());
        resetNumber(tb);//更新顺序号
        resetCount($(tbody));//更新子表数量
    }
    if (addmode == "1" || addmode == "2" || addmode == "4") //选择添加 Excel式添加
    {
        var tr = $(obj).parents("tr[eitemrow]:first");
        if (tr.length == 0) { return; }
        tr = tr[0];
        updateSelected(tr); //解决select选择状态不被克隆
        var index = tr.Index();
        var item = _model[index].toJson();
        var itemjson = new eJson2(item.toJson());
        clearJsonID(itemjson);//清空JSON的ID
        _model.splice(index + 1, 0, itemjson);//在指定位置插入JSON
        var clonetr = tr.cloneNode(true);

        var idx = getNextRowIndex(obj);
        renameControls(clonetr,idx);//重命名控件
        robj = clonetr;//返回对象
        $(clonetr).find("[name='ID']").val('');//清空控件的ID
        $(tr).after(clonetr);
        $(input).val(model.toJson());

        resetNumber(tb);//更新顺序号
        resetCount($(tbody));//更新子表数量
    }
    if (addmode == "3") //叠加添加
    {
        var dl = $(obj).parents("dl:first");
        if (dl.length == 0) { return; }
        dl = dl[0];       
        updateSelected(dl); //解决select选择状态不被克隆
        var index = dl.Index();
        var item = _model[index].toJson();
        var itemjson = new eJson2(item.toJson());
        clearJsonID(itemjson);//清空JSON的ID
        _model.splice(index + 1, 0, itemjson);//在指定位置插入JSON
        var clonedl = dl.cloneNode(true);
        $(clonedl).find("[postname='ID']").val('');//清空控件的ID
        robj = clonedl;//返回对象
        var _max = $(dl).parent().find(">dl").length + 1;
        $(clonedl).find("input[type='radio']").each(function (i, el) {
            el.name = el.name.replace("row_" + (index + 1), "row_" + _max);
        });

        $(dl).after(clonedl);
        $(input).val(model.toJson());

        resetCount(dl.parent());//更新子表数量
    }
    if (tb[0].parent) { Table_Init_Tbody(tb[0].parent); }
    if (typeof (copyItem_finish) == "function") { copyItem_finish(modelid, robj,obj); }
};
function clearJsonID(data)
{
    if (data["ID"]) {
        data["ID"] = "";
    }
    if (data["PKID"]) {
        data["PKID"] = "";
    }
    data.foreach(function(e)
    {
        if (typeof (data[e]) == "object")
        {
            var node = data[e];
            //alert(node.toJson());alert(e + "::" + typeof (data[e]))
            node.foreach(function (x) {
                clearJsonID(node[x]);
            });
        }
    });
};


//回填类型数据{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);
        }
    });
};
//重新加载控件选项
function reloadControl(id)
{
    var url = "model.aspx?appitem=" + document.location.href.getquerystring("appitem");
    url = url.addquerystring("act", "add");
    url = url.addquerystring("obj", id);
    url = url.addquerystring("t", now());
    $.ajax({
        type: "GET",
        async: false,
        url: url,
        dataType: "json",
        success: function (data) {
            if (!data) { return; }
            var box = $("#" + id + "_box");
            ReFillControl(box, id, data);
        }
    });
};
var subModel = function (modelid, area) 
{
    if(isCN(modelid))
    {
        var ctrl=$("[modelname='"+ modelid +"']");
        if(ctrl.length==1)
        {
            modelid = ctrl.attr("modelid");
        }
    }
    if (typeof (area) == "undefined") { area=$(document); }
    this.area = area;
    var pmodel = this;
    this.modelid = modelid;
    this.table = this.area.find("#eformlist_" + modelid);
    this.tbody = this.table.find(">tbody");
    this.tfoot = this.table.find(">tfoot");
    this.input = this.area.find("#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.addRows = function(data)
    {
        $.each(data,function(i,item)
        {
            //for(var e in item)
            //{
                //alert(e + ":" + );
           // }
            var json= new eJson2(item);
           // alert(json.toJson() + ":" + pmodel.addmode );
            if(pmodel.addmode == 0)//逐个添加
            {
                var html=getModelAddHTML(pmodel.modelid);
                var tmp = document.createElement("div");
                tmp.innerHTML = html;
               
                //alert(3);
                model_bindarea(tmp, json);//绑定数据到表单
                //alert(5);

                var obj = areaToJson(tmp);
                //alert(json.toJson() + "::" + obj.toJson());

                pmodel.data.append(obj);
                var tr=pmodel.addItem();
                model_bind(obj, tr);//绑定数据到行
            }
            else
            {
                var tr=pmodel.addItem();
                model_bindarea(tr, json);
                var obj = areaToJson(tr);
                pmodel.data.append(obj);
                var idx = pmodel.curRowIndex();
                renameControls(tr, idx); //重命名控件
            }
        });
        pmodel.resetNumber();//更新顺序号
        pmodel.resetCount();//更新子表数量
        pmodel.resetValue();
    };
    //添加行
    this.addItem = function (callback) {
        var tr = this.tfoot.find("tr")[0].cloneNode(true);
        if (typeof (callback) == "function") {
            callback(tr);
        }
        if(this.addmode == 110)
        {
            var html=getModelAddHTML(this.modelid);
            var tmp = document.createElement("div");
            tmp.innerHTML=html;
            //model_bindarea(tmp, data);

            var obj = areaToJson(tmp);
            //alert(obj.toJson());
            model_bind(obj, tr);
        }
        var trsum=this.tbody.find("[etype='sum']:first");
        if(trsum.length==0)
        {
            this.tbody[0].appendChild(tr);
        }
        else
        {
            trsum.before(tr);
        }
        return tr;
    };
    //根据json内容重新输出

    //清除数据和tbody内容
    this.Clear = function ()
    {
        this.tbody.find(">tr").remove();
        while(this.data.length>0)
        {
            this.data.pop();
        }
        $("input[id='count_" + modelid + "']").val(0);
        this.resetValue();
    };
    //复制行
    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.Count = function ()
    {
        return this.tbody.find(">tr:visible").length;
    };
    this.NameToID=function(id)
    {
        if(isCN(id))
        {
            //var ctrl=$(".eform [fieldname='"+ id +"']");          
            //if(ctrl.length>0)
            //{
            //id=$(ctrl[0]).attr("postname");
            //alert(ctrl.length + "::" + id);
            //}
            var ctrl=$("div[fieldname='"+ id +"']");
            if(ctrl.length>0)
            {
                return $(ctrl[0]).attr("id").replace(/_box/g,'');
            }
        }
        return id;
    };
    this.Max = function (id)
    {
        id=this.NameToID(id);
        var result = 0;
        for (var i = 0; i < this.data.length; i++)
        {
            if (this.data[i]["Delete"] == "true") { continue; }
            if (typeof (this.data[i][id]) == "undefined") { continue; }
            if (parseFloat(this.data[i][id]) > result)
            {
                result = parseFloat(this.data[i][id]);
            }
        }
        return result;
    };
    this.Min = function (id) {
        id=this.NameToID(id);
        var result = 0;
        for (var i = 0; i < this.data.length; i++) {
            if (this.data[i]["Delete"] == "true") { continue; }
            if (typeof (this.data[i][id]) == "undefined") { continue; }
            if (result == 0)
            {
                result = parseFloat(this.data[i][id]);
                continue;
            }
            if (parseFloat(this.data[i][id]) < result)
            {
                result = parseFloat(this.data[i][id]);
            }
        }
        return result;
    };
    this.Avg = function (id)
    {
        id=this.NameToID(id);
        var ct = 0;
        var result = 0;
        for (var i = 0; i < this.data.length; i++) {
            if (this.data[i]["Delete"] == "true") { continue; }
            if (typeof (this.data[i][id]) == "undefined") { continue; }            
            result += parseFloat(this.data[i][id]);
            ct++;
        }
        if (ct == 0) {return 0;}
        return result/ct;
    };
    this.Sum = function (id) {
        id=this.NameToID(id);
        var result = 0;
        for (var i = 0; i < this.data.length; i++) {
            if (this.data[i]["Delete"] == "true") { continue; }
            if (typeof (this.data[i][id]) == "undefined") { continue; }
            result += parseFloat(this.data[i][id]);
        }
        return result;
    };
    //更新子表数量
    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();
        if (modelid == "9d276415-aae7-4182-85d1-80314d1a767d") {
            //alert(modelid + ":" + this.tbody.find(">tr").length);
        }
        this.tbody.find(">tr").each(function (i, el) {
            //clearPack(el);
            var drow = areaToJson(el,false);
            data.append(drow);
            //addPack(el);
        });
        this.model["eformdata_" + modelid] = data;
        if (modelid == "9d276415-aae7-4182-85d1-80314d1a767d") {
            //alert(data.toJson());
        }
        this.data = data;
        this.resetValue();
    };
    return this;
};
function clearPack(node) {
    var inputs = $(node).find("input[pack]");
    for (var i = 0; i < inputs.length; i++) {
        if ($(inputs[i]).parents('tfoot').length == 0) {
            $(inputs[i]).removeAttr("pack");
        }
    }
    var selects = $(node).find("select[pack]");
    for (var i = 0; i < selects.length; i++) {
        if ($(selects[i]).parents('tfoot').length == 0) {
            $(selects[i]).removeAttr("pack");
        }
    }
    var textareas = $(node).find("textarea[pack]");
    for (var i = 0; i < textareas.length; i++) {
        if ($(textareas[i]).parents('tfoot').length == 0) {
            $(textareas[i]).removeAttr("pack");
        }
    }
};
function addPack(node) {
    var inputs = $(node).find("input");
    for (var i = 0; i < inputs.length; i++) {
        if ($(inputs[i]).parents('tfoot').length == 0) {
            $(inputs[i]).attr("pack", "true");
        }
    }
    var selects = $(node).find("select");
    for (var i = 0; i < selects.length; i++) {
        if ($(selects[i]).parents('tfoot').length == 0) {
            $(selects[i]).attr("pack", "true");
        }
    }
    var textareas = $(node).find("textarea");
    for (var i = 0; i < textareas.length; i++) {
        if ($(textareas[i]).parents('tfoot').length == 0) {
            $(textareas[i]).attr("pack", "true");
        }
    }
};

/*
$.each(data, function(key,val) {
    console.log(val.name);
  });
*/



//区域到JSON：来源formToJson
function areaToJson(area, loop) {
    if (typeof (loop) == 'undefined') { loop = true; }
    var elements = $(area).find("input,select,textarea");
    if (elements.length == 0) return new eJson2();
    var ctrls = new Array();
    if (loop)
    {
        clearPack($(area));
        $(area).find(".excelTable,.overlaytable").each(function (i, el)
        {
            if ($(this).parents('tfoot').length == 0) {
                var len = $(this).parents(".excelTable,.overlaytable").length;
                $(this).attr("level", len);
                ctrls.push($(this));
            }
        });
        ctrls = ctrls.sort(function (a, b) {
            //return $(a).attr('level') - $(b).attr('level');//升序
            return $(b).attr('level') - $(a).attr('level');//降序
        });
        //alert(ctrls.length);
        $.each(ctrls, function (index, el) {
            var modelid = $(this).attr("id").replace("eformlist_", "");
            var _area = $(this).parent();
            var model = new subModel(modelid, _area);
            model.pack();
            $(this).attr("pack", "false");
        });


    }
    //
    $(area).find(".excelT4able,.overlay4table").each(function (i, el) {
        if ($(this).attr("exclude") == "undefined" || $(this).attr("exclude") != "true") {
            if ($(this).parents('tfoot').length == 0) {
                var modelid = $(this).attr("id").replace("eformlist_", "");
                //tbody_pack(modelid, $(area));
            }
        }
    });
    var json = new eJson2();
    for (var i = 0; i < elements.length; i++) {

        if ($(elements[i]).parents('tfoot').length > 0) { continue; }
       
        var pack = $(elements[i]).attr("pack");
        if (pack == "true") { 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; }

      

        var type = "";
        if (elements[i].getAttribute("type")) { type = elements[i].getAttribute("type").toString().toLowerCase(); }

        if (type.length == 0) {
            if (elements[i].tagName.toLowerCase() != "select" && elements[i].tagName.toLowerCase() != "textarea") {
                continue;
            }
        }
        
        if (type == "submit" || type == "button" || type == "reset") { continue; }
        if (type == "checkbox" && $(elements[i]).attr("etype") == "switcher") { continue; }
        if((type == "radio" || type=="checkbox") && elements[i].checked==false){continue;}

        $(elements[i]).attr("pack", true);
        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;
        }
        var postname = elements[i].name;
        if (elements[i].getAttribute("postname")) {
            postname = elements[i].getAttribute("postname");
        }
        if (elements[i].name.toLowerCase().indexOf("eformdata_") > -1) //子模块对象 
        {
            var _json = value.toJson();
            _json = _json.get(postname);
            json.append(postname, _json);
            json[postname] = _json;
        }
        else
        {
            value = value.autotrim(trimtype).encode() || "";           
           
            if (typeof (json[postname]) == "undefined") {
                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);
                    }
                }
            }
            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 (typeof (json[postname + "_Text"]) == "undefined") {

                        json[postname + "_Text"] = removeHTMLTag(elements[i].getAttribute("text")).encode();
                    }
                    else {
                        json[postname + "_Text"] += "," + removeHTMLTag(elements[i].getAttribute("text")).encode();
                    }
                }
            }
            if (elements[i].name.toLowerCase().indexOf("_text") > -1 && (elements[i].getAttribute("etype") == "singleuser" || elements[i].getAttribute("etype") == "multipleuser")) {
                if (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();
                }
            }
        }
    }
    return json;
};


//回填窗口 原：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();
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title: title,
        moveOut: true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        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"]);
    });
    var model = new parent.subModel(modelid);
    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);
    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(ctrl.length==0)
        {
            //内容框
            var div=$(area).find("div[fieldname='" + e + "']");
            if(div.length==1)
            {
                var e2=div.attr("id").replace(/_box/g,'');
                ctrl=$(area).find("[postname='" + e2 + "']");               
            }
        }
        if(ctrl.length==0)
        {
            ctrl=$(area).find("[fieldname='" + e + "']");//隐藏域中文
        }

        //物料名称
        //if(e=="物料"){ alert(e+"::" + ctrl.length);}
        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) {

                    if (e.toLowerCase() == "id")
                    {                        	
                        if ($(ctrl).parents('tfoot').length > 0) { return; }
                    }
                    //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];
                    if(typeof(v)=='string')
                    {
                        v=v.decode();
                    }
                    
                    //alert(v);
                    //return;
                    ctrl.value = v; //如果select无值匹配，则会赋值失败。
                    //alert( ctrl.value );
                    ctrl.setAttribute("ovalue", v);

                    var editreadonly = Attribute(ctrl, "editreadonly");
                    if (v.length > 0 && editreadonly == "true") {
                        ctrl.setAttribute("readOnly", "true");
                    }
                    if (ctrl.onchange && ctrl.value.length>0) 
                    {
                        $(ctrl).trigger("change");
                    }
                    var etype = Attribute(ctrl, "etype").toLowerCase();
                    if(etype=="select")
                    {
                        if(ctrl.value.length==0)
                        {
                            $(ctrl).find("option:contains('"+ v +"')").attr("selected",true);
                        }
                    }
                    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 area = $(obj).parent();
    var model = new subModel(modelid,area);
    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)
{
    var area = $(obj).parents(".overlaytable:first").parent();
    var _back = confirm('确认要删除吗？');
    if (!_back) { return; }
    var tr = $(obj).parents("tr[eitemrow]:first");
    var model = new subModel(modelid, area);
    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);
};




//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;
};


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

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

    }
    else
    {
        html='<a href="'+ href +'" class="button" style="padding-left:10px;padding-right:10px;margin-left:5px;"'+ (fun.length==0?'': ' onclick="'+ fun +'"' ) + (target.length==0?'':' target="_blank"')+'><span style="margin-right:0px;padding-right:0px;">'+ text+'</span></a>';
        //html = '<a href="' + href + '" class="Button"' + (fun.length == 0 ? '' : ' onclick="' + fun + '"') + (target.length == 0 ? '' : ' target="_blank"') + '>' + text + '</a>';
    }	
    box.append(html);
};
function number_minus(obj)
{
    var par=$(obj).parent();
    var ipt=par.find(".number");
    var step=ipt.attr("step")||1;
    var val=$(ipt).val()||0;	
    var value=parseFloat(val) - parseFloat(step);
    var minvalue=$(ipt).attr("minvalue");
    if(minvalue && minvalue.length>0 && value<parseFloat(minvalue))value=minvalue;
    ipt.val(value);
};
function number_plus(obj)
{
    var par=$(obj).parent();
    var ipt=par.find(".number");	
    var step=ipt.attr("step")||1;
    var val=$(ipt).val()||0;
    var value=parseFloat(val) + parseFloat(step);
    var maxvalue=$(ipt).attr("maxvalue");
    if(maxvalue && maxvalue.length > 0 && value > parseFloat(maxvalue)) value=maxvalue;
    ipt.val(value);
};
function getDistance(GPSLng,GPSLat,Lng,Lat)
{
    var result = (6378137.0 * Math.acos(Math.sin(GPSLat / 180 * Math.PI) * Math.sin(Lat / 180 * Math.PI) + Math.cos(GPSLat / 180 * Math.PI) * Math.cos(Lat / 180 * Math.PI) * Math.cos((GPSLng - Lng) / 180 * Math.PI))) / 1;
    return result;
};
/*
function getDistance2(lon1, lat1, lon2, lat2) {
    var toRad = (deg) => deg * Math.PI / 180;
    var R = 6371000; // 地球半径（米）
    
    var radLat1 = toRad(lat1);
    var radLon1 = toRad(lon1);
    var radLat2 = toRad(lat2);
    var radLon2 = toRad(lon2);
    
    var dlat = radLat2 - radLat1;
    var dlon = radLon2 - radLon1;
    
    var a = Math.sin(dlat / 2) ** 2 +
              Math.cos(radLat1) * Math.cos(radLat2) * Math.sin(dlon / 2) ** 2;
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    
    return R * c;
}
*/
function hideField(id,area)
{
    //alert($("#M42_F21,#M42_F22").length);
    area=area||$;
    var ipt=area.find("#" + id);
    var par=ipt.parents("li:first");
    ipt.attr("notnull",false);
    par.hide();
};
function showField(id,notnull,area)
{	
    area=area||$;
    var ipt=area.find("#" + id);
    var par=ipt.parents("li:first");
    ipt.attr("notnull",notnull);
    par.show();
    var field=par.find("div:eq(0)");
    if(notnull)
    {		
        if(field.text().indexOf("*")==-1)
        {
            field.prepend("<ins>*</ins>");
        }
    }
    else
    {
        field.find("ins").remove();
    }
};
function setSwitcher(obj)
{
    var prev=$(obj).prev();
    prev.val(obj.checked ? 1 : 0);
    //alert(prev.attr("type"));
};
function setfillValue(id,value,mult)
{
    if(mult)
    {
        var val=$("#" + id).val();
        if(val.length>0) val+="\n";
        val+=value;
        $("#" + id).val(val);
    }
    else
    {
        $("#" + id).val(value);
        layer.close(arrLayerIndex.pop());
    }
};
function fillValue(obj,mult)
{
    var par=$(obj).parent();
    var input=par.find("input,textarea");
    if(input.length==0) return;
    input=input[0];
    var url=document.location.href;
    url=url.removequerystring("id");
    url=url.addquerystring("act","add");
    //url=url.addquerystring("mult",mult);
    url=url.addquerystring("obj",input.name);
    url+="&t=" + now();
    $.ajax({
        type: "GET",
        async: false,
        url: url,
        dataType: "json",
        success: function(data)
        {
            //alert(JSON.stringify(data));
            var html='<ul style="padding:0;margin:0;">';
            $.each(data, function()
            {
                var val=this["value"].encode().replace(/\r/g,"").replace(/\n/g,"\\u000a");
                html+='<li style="padding:8px;border:1px dashed #ccc;margin-bottom:10px;line-height:23px;color:#444;border-radius: 4px;cursor:pointer;" onclick="setfillValue(\'' + input.id + '\',\''+ val +  '\','+ mult +');">' + this["text"] + '</li>'; 
            });
            html+='</ul>';			
			
            layer.open({
                type: 1, //Page层类型
                title: "内容选择",
                skin: 'layui-layer-prompt',
                moveOut:true,
                shadeClose: true,
                btn:[],
                area:IsMobile() ? ['95%','80%'] : ["600px" , "450px"],
                content: html,
                yes: function(index, layero){
                    //layer.close(index);
                },
                cancel: function(index, layero)
                {
                    arrLayerIndex.pop();
                },
                success: function(layero, index)
                {
                    arrLayerIndex.push(index);
                },
                end : function(index){arrLayerIndex.pop();}
            });
        }
    });
};
function Resize_eControl(area)
{
    if(!IsMobile()){ return;}
    area=area||document;	
    $(area).find(".eform .filterSelect").each(function (index, val) {
        var td = getParent(this, "td");	
        if(!$(td).is(':visible')){return true;}			
        var ele = $(this);
        ele.css("width",  ($(td).width() - 2) + "px");
    });
    $(area).find(".eform .text").each(function (index, val) {
        var td = getParent(this, "td");
        //if($(td).width()<10){alert($(td).is(':visible')); return true;}
        if(!$(td).is(':visible')){return true;}			
        var ele = $(this);
        if(ele.parent().attr("etype")=="rndcode")
        {
            ele.css("width", "100px");
            return true;
        }
        if(ele.parent().attr("etype")=="password")
        {
            ele.css("width", ($(td).width() - 80) + "px");
            return true;
        }
        if(ele.parent().attr("etype")=="fileselect" || ele.parent().attr("etype")=="pathselect")	
        {
            ele.css("width", ($(td).width() - 106) + "px");
            return true;
        }
        if(ele.parent().attr("etype")=="text" && ele.parent().find("a:contains('选择')").length > 0)	
        {
            ele.css("width", ($(td).width() - 60) + "px");
            return true;
        }
        if(ele.parent().attr("etype")=="datatextbutton")	
        {
            ele.css("width", ($(td).width() - 60) + "px");
            return true;
        }
        if(ele.parent().parent().attr("etype")=="selinput")	
        {
            ele.css("width",  ($(td).width() - 25) + "px");
            return true;
        }
        if(ele.parent().attr("etype")=="searchselect")	
        {
            ele.css("width", "40px");
            return true;
        }
        if(ele.parent().attr("etype")=="dateregion"){
            ele.css("width", "100px");
            return true;
        }
        if(ele.parent().attr("etype")=="date"){
            ele.css("width", $(td).width() + "px");
            return true;
        }
        if (this.getAttribute("eautowidth") == null)
        {
            ele.css("width", $(td).width() + "px");
        }
    });
    $(area).find(".eform i:not([class])").hide();
    $(area).find(".eform select").each(function (index, val) {
        var td = getParent(this, "td");
        if(!$(td).is(':visible')){return true;}
        var ele = $(this);
        if(ele.parent().attr("etype")=="searchselect")	
        {
            ele.css("width", ($(td).width() -70 ) + "px");
            return true;
        }           
        ele.css("width", ($(td).width()) + "px");
    });
    $(area).find(".eform textarea").each(function (index, val) {
        var td = getParent(this, "td");
        if(!$(td).is(':visible')){return true;}
        var ele = $(this);
        //移动端编辑器要去掉
        if(ele.parent().attr("etype")=="textarea")
        {
            if(ele.parent().find("a:contains('选择')").length > 0)
            {
                ele.css("width", ($(td).width() - 60) + "px");
            }
            else
            {
                ele.css("min-width", ($(td).width() - 16) + "px");
                ele.css("width", $(td).width() + "px");
            }
        }
        else
        {
        }            
    });
    $(area).find(".eform iframe").each(function (index, val) {
        var td = getParent(this, "td");
        if(!$(td).is(':visible')){return true;}
        var ele = $(this);
        ele.attr("width", ($(td).width()) + "px");
    });
};
var signid = null;
var signtokenid = null;
var signTime = null;
var signidx=null;
var signlink=null;
function openSignDlg(obj,area)
{
	signlink=obj;
	var url = virtualPath + "Plugins/signMobile.aspx?signtokenid="+ signtokenid +"&signid="+ signid +"&mode=mobile"+"&area=" + area;
	layer.open({
		type: 2,
		skin: 'layui-layer-rim', //加上边框
        title: '签名',
		moveOut:false,
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
		area:['60%','60%'],
        content: [url,'no'], 
        success: function (layero, index) { arrLayerIndex.push(index); setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);},
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
};
function removeSignTemp()
{
	var url = virtualPath + "Plugins/signMobile.aspx?signtokenid="+ signtokenid +"&signid="+ signid +"&act=removesigntemp&t=" + now();
	$.ajax({
        type: 'get',
        url: url,
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
        }
    });	
};
function checkSign()
{
	clearTimeout(signTime);
	var url = virtualPath + "Plugins/signMobile.aspx?signtokenid="+ signtokenid +"&signid="+ signid +"&act=getsignstate&t=" + now();
	$.ajax({
        type: 'get',
        url: url,
		async: false,
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
			if(data.state=="1" && signidx)
			{
				layer.close(signidx);
			}			
			if(data.base64.length>10)
			{				
				var img = new Image;
				img.onload = function(){
					var canvas = document.getElementById("esign");
					var tow=0,toh=0;
					if (img.width / canvas.clientWidth < img.height / canvas.clientHeight)
					{
						toh = canvas.clientHeight;
						tow = parseInt(img.width * toh / img.height);
					}
					else
					{
						tow = canvas.clientWidth;
						toh = parseInt(img.height * tow / img.width);
					}
					canvas.getContext("2d").clearRect(0, 0,  canvas.clientWidth,  canvas.clientHeight);
      				canvas.getContext("2d").drawImage(img,0,0,tow,toh);
					$(canvas).attr("wCount", 300);
    			};
				img.src = "data:image/png;base64," + data.base64;
				removeSignTemp();
			}
			else
			{
				signTime = window.setInterval(checkSign,2000);
			}
        },
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			signTime = window.setInterval(checkSign,2000);
		}
    });		
};
function getDefaultSign(area)
{
	var url = virtualPath + "Plugins/signMobile.aspx?area="+ area +"&act=getdefaultsign";
	$.ajax({
        type: 'get',
        url: url,
		async: false,
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
			//layer.msg(JSON.stringify(data));
			//signid=data.signid;
			//signtokenid=data.signtokenid;
			//baseurl=data.baseurl;
			if(data.base64.length>10)
			{
				var img = new Image;
				img.onload = function(){
					var canvas = document.getElementById("esign");
					var tow=0,toh=0;
					if (img.width / canvas.clientWidth < img.height / canvas.clientHeight)
					{
						toh = canvas.clientHeight;
						tow = parseInt(img.width * toh / img.height);
					}
					else
					{
						tow = canvas.clientWidth;
						toh = parseInt(img.height * tow / img.width);
					}
					canvas.getContext("2d").clearRect(0, 0,  canvas.clientWidth,  canvas.clientHeight);
      				canvas.getContext("2d").drawImage(img,0,0,tow,toh);
					$(canvas).attr("wCount", 300);
    			};
				img.src = "data:image/png;base64," + data.base64;
			}
        }
    });	
};
function getSignToken(area)
{	
	var url = virtualPath + "Plugins/signMobile.aspx?area="+ area +"&act=getsigntoken";
	var baseurl="";
	$.ajax({
        type: 'get',
        url: url,
		async: false,
        //contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
			//layer.msg(JSON.stringify(data));
			signid=data.signid;
			signtokenid=data.signtokenid;
			baseurl=data.baseurl;
        }
    });	
	if(signid.length==0)return;
	var url = virtualPath + "Plugins/URLCode.aspx?scale=3&url="+ encodeURIComponent(baseurl + "Plugins/signMobile.aspx?signid=" + signid + "&signtokenid=" + signtokenid);
	//alert(url);
	//alert(baseurl + "Plugins/signMobile.aspx?signid=" + signid + "&signtokenid=" + signtokenid);
	//return;
	var html='<div style="padding-top:25px;text-align:center;"><img src="' + url + '"></div>';
	signidx=layer.open({
		type: 1,
    	closeBtn:'2',//设置为第二种样式
    	skin:'demo-class',  
		scrollbar:false,
		shadeClose: true,
		area:['240px','240px'],
    	//title:['扫码签名','15px'],
		//title:false,
		title:'扫码签名',
		// shade: true,
		btn:[],
    	content: html,
		success: function(layero, index){
			signTime = window.setInterval(checkSign,2000);
		},
		end: function(){
			signidx=null;
		}
	});
};
function obtainZoom()
{
    var ratio = 0,
        screen = window.screen,
        ua = navigator.userAgent.toLowerCase();
    if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
    } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
        }
    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
    }
    if (ratio) {
        ratio = Math.round(ratio * 100);
    }
    return ratio;
};
function resizing(){
	
    var m = obtainZoom();
    var v=100/Number(m);
    //document.title=m + "::" + v;
	
    //alert(
    //document.body.style.zoom = 100/Number(m);
    //document.zoom = 100/Number(m);
    return;
    if(Number(m) == 125){
        var bodySize = Number(m)+5+"%";
        //$("body").css("background-size",bodySize+""+bodySize);
    }else{
        var bodySize=Number(m)+"%";
        //$("body").css("background-size",bodySize+""+bodySize);
    }
};
//resizing();
if(window.addEventListener){window.addEventListener("load",function(){resizing();}, false);}else{window.attachEvent("onload",function(){resizing();});}
function readMappingModel(modelid,frmid,idname)
{
	var id=$("#"+frmid).val()||"";
	if(id.length==0)
	{
		layer.msg("请选择数据!");
		return;
	}
	idname= idname || "id";
	var url=document.location.href;
	url=url.removequerystring("id");
	url=url.addquerystring("modelid",modelid);
	url=url.addquerystring("act","mappingview");
	url=url.addquerystring("ajax","true");
	url=url.addquerystring(idname,id);
	url+="&t=" + now();
	var box=$("#mapmodelbody_" + modelid.replace(/-/g,"_"));
	if(box)
	{
		$.ajax({
			type: 'get',
			url: url,	
			dataType: "html",
			success: function(html)
			{
				var reg = /<body[^>]*>([\s\S]+?)<\/body>/i;
				var m = reg.exec(html);
				if(m)
				{
					box.html(m[1]);
				}
				
			}
		});
	}
};
function viewMappingModel(title,modelid,frmid,idname,width,height,value)
{
	var id=value||$("#"+frmid).val()||"";
	if(id.length==0)
	{
		layer.msg("请选择数据!");
		return;
	}
	idname= idname || "id";
	var url=document.location.href;
	url=url.removequerystring("id");
	url=url.addquerystring("modelid",modelid);
	url=url.addquerystring("act","mappingview");
	url=url.addquerystring("ajax","true");
	url=url.addquerystring(idname,id);
	url+="&t=" + now();
	parent.layer.open({
      type: 2,
      title: title,
	  moveOut:true,
      maxmin: true,
      shadeClose: true, //点击遮罩关闭层
      area :[width,height],
	  // content: [url,'no'], 
	  content: url,
	  success: function(layero, index){parent.arrLayerIndex.push(index);},
	  cancel: function(index, layero){parent.arrLayerIndex.pop();},
	  end : function(index){parent.arrLayerIndex.pop();}
    });	
};
function initCharts(id,type,option,data)
{
	var box=$('#' + id + '_box');	
	var width=box.width();
	var height=box.height();
	var radius=parseInt(box.width()/data.length/2*0.85);//根据宽度计算	
	if(radius > parseInt(height*0.7/2)){radius=parseInt(height*0.7/2);}//根据高度计算
	//alert(parseInt(radius/30 * 5));
	
	var space= parseInt((width-radius * 2 * data.length) /  (data.length+1));
	if(type=="gauge" || type=="roundprogress")
	{
		for(var i=0;i<data.length;i++)
		{
			var item=option.series[0];
			if(i>0)
			{
				item=clone(option.series[0]);
				option.series.push(item);
			}
			item.radius=radius+'px';
			item.center[0]= (space + radius + (i*radius*2) + (i*space)) + 'px';
			item.data[0].name=data[i][0];
			item.data[0].value=data[i][1];
			if(type=="gauge"){continue;}
			var size=parseInt(radius/30 * 5);
			if(size>20){size=20;}			
			item.axisLine.lineStyle.width=size;
			item.progress.width=size;
			
			
			size=parseInt(radius/30 * 8);
			if(size>24){size=24;}
			if(size<12){size=12;}
			item.title.fontSize=size;
			
			size=parseInt(radius/30 * 11);
			if(size>28){size=28;}
			if(size<12){size=12;}			
			item.detail.fontSize=size;
		}
	}
	if(type=="radar")
	{
		if(data[0].length)//一维
		{
			var value=[];
			for(var i=0;i<data.length;i++)
			{
				//alert(data[i][1]);
				var obj={};
				obj["name"]=data[i][0];
				obj["max"]=parseInt(parseInt(data[i][1]) * 1.2);
				option.radar.indicator.push(obj);
				option.legend.data.push(data[i][0]);
				
				value.push(data[i][1]);
			}
			var _data={};
			_data["name"]='';
			_data["value"]=value;
			option.series[0].data.push(_data);
			//console.log(option);
		}
		else//多维
		{
			for(p in data[0])
			{
				if(p=="name"||p=="text"){continue;}
				var obj={};
				obj["name"]=p;
				obj["max"]=0;
				option.radar.indicator.push(obj);
			}
			
			for(var i=0;i<data.length;i++)
			{
				//if(i>0){continue;}
				var value=[];
				var _data={};
				for(p in data[i])
				{
					if(p=="name"||p=="text")
					{
						option.legend.data.push(data[i][p]);
						_data["name"]=data[i][p];
					}
					else
					{						
						value.push(data[i][p]);	
						for(var j=0;j<option.radar.indicator.length;j++)
						{
							if(option.radar.indicator[j]["name"]==p)
							{
								if(option.radar.indicator[j]["max"]<data[i][p]*1.2)
								{
									option.radar.indicator[j]["max"]=parseInt(data[i][p]*1.2);
									//alert(option.radar.indicator[j]["max"]);
								}
								continue;
							}
						}
					}
				}
				_data["value"]=value;
				option.series[0].data.push(_data);
			}
			
			
			//console.log(option);
		}
	}
};
var lastpictureobjid=null;
function openPictureEditor(obj,lastobjid)
{	
    //lastpictureobj=$(obj).siblings("img");
    lastpictureobjid=lastobjid;
    var url = virtualPath + "Plugins/pictureeditor/index.html";
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title: '在线编辑图片',
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area:['90%','98%'],
        content: [url,'no'], 
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
};
var quickviewIndex = null;
var quickviewJson=null;
function _parent()
{
    try
    {
        if (parent.layer) {
            return parent;
        }       
    }
    catch (e) {
    }
    return self;
};
function _top() {
    try {
        if (top.layer) {
            return top;
        }
    }
    catch (e) {
    }
    return self;
};
function QuickShoweTab(obj)
{
    var edataid=$("#quickviewbody").attr("edataid");    
    var json=quickviewJson;//$(".eDataTable tr[eRowID='" + edataid + "']").attr("viewdata");
    var json=decode64(json);
    //alert(json);
    //alert(edataid);
    var data=JSON.parse(json);
    var url=$(obj).attr("_dataurl");
    if(url.indexOf("quick")==-1) url=url.addquerystring("act","quickview");	
    url=url.addquerystring("ajax","true");
	
    //var regex = /{data:(.*?)}/gi;
    //var arr1 = url.match(regex);
    //alert(arr1);
    //alert(url);
    var reg= new RegExp("{data:(.*?)}","gi");
    //alert(url.match(reg));
    //var arr;
    /*
 	while ((arr = reg.exec(url)) != null) //会少项  new RegExp不能带全局
	{		
		var name=arr[1].toLowerCase();
		if(typeof(data[name]) != 'undefined')
		{
			url=url.replace(arr[0],data[name]);			
			//alert(arr[0] + "::" + data[name]);
		}
 	}
	*/
    if(url.match(reg))
    {
        var arr = url.match(reg);
        for(var i=0;i<arr.length;i++)
        {
            var name=arr[i].toLowerCase().split(":")[1].replace("}","");
            if(typeof(data[name]) != 'undefined')
            {
                url=url.replace(arr[i],data[name]);
            }
        }
    }
    var index=$(obj).index();
    var dd=$(obj).parent().parent().children().eq(1);
    var div=dd.children().eq(index);
    //div.html("123");
    var lastid=$(obj).attr("edataid");
    //alert(lastid +"::"+ edataid);
    if(lastid != edataid || 1>0)
    {
        $(obj).attr("edataid", edataid);
        $.ajax({
            type: "GET",
            async: true,
            url:url,
            dataType: "html",
            success: function(html)
            {
                var backstr=html;
                var reg = /<body[^>]*>([\s\S]+?)<\/body>/i;
                var m = reg.exec(html);
                if(m)
                {
                    backstr=m[1];   
                }
                div.html(backstr);
			
            }	
        });	
    }
    //alert($(obj).index() +":" +url);	
    showeTab(obj);
};
function QuickView(obj,type,quickviewmodelid,shade,width,height,url,json)
{  
    
	//var json=decode64(json);
	//alert(json);
	//var data=JSON.parse(json);

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

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

	//if ($(obj).parents("tbody:first").find("tr[class='select']").length > 1) { return; }
	
	var rowid=$(obj).attr("eRowID");
	quickviewJson=$(obj).attr("viewdata");
	if(window.quickviewID==rowid)
	{
		//return;
	}
	
	window.quickviewID=rowid;
	if(url.length==0)
	{
		url=document.location.href;
		url=url.addquerystring("id",rowid);
		if(quickviewmodelid.length>0)
		{url=url.addquerystring("quickviewmodelid",quickviewmodelid);}
	}
	if(url.indexOf("=quick")==-1) url=url.addquerystring("act","quickview");	
	url=url.addquerystring("ajax","true");
	//layer.msg(type);
	if(type==6)
	{
	
		if($("#quickviewbody").find("dd.qv").length>0)
		{
			$("#quickviewbody").attr("edataid", rowid);
			var cur= $("#quickviewbody").find("dd.qv").prev().find(".cur").get(0);
			QuickShoweTab(cur);
			//alert(dt.length);
			return;
		}
		var lastcur=$("#quickviewbody .eTab dt a.cur").index();
		$.ajax({
		    type: "GET",
		    async: true,
		    url:url,
		    dataType: "html",
		    success: function(html)
		    {
			var backstr=html;
			var reg = /<body[^>]*>([\s\S]+?)<\/body>/i;
			var m = reg.exec(html);
			if(m)
			{
			    backstr=m[1];   
			}
			if($("#quickviewbody").find("dd.qv").length==0)
			{
				$("#quickviewbody").html(backstr);
			}
			else
			{
				$("#quickviewbody dd.qv div:eq(0)").html(backstr);
			}
			$("#quickviewbody").attr("edataid", rowid);
			if(lastcur>0)
			{
				var lastobj=$("#quickviewbody .eTab dt a:eq("+ lastcur +")").get(0);
				showeTab(lastobj);
			}
		},
	    error: function (XMLHttpRequest, textStatus, errorThrown) 
		{
	       
	    }
		});	
		return;
	}

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

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

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


	  content: url,
	  yes: function(index, layero){
	
	  },
	  cancel: function(index, layero){
		  //关闭
		  arrLayerIndex.pop();
	  },
	  success: function (layero, index)
	  {
	      arrLayerIndex.push(index);
	      quickviewIndex = index;
	      setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
	  },
	  end : function(index){quickviewIndex=null;window.quickviewID=null;arrLayerIndex.pop();}
    });	
};
function unPivotConfig()
{
    var url = document.location.href;
    url = url.removequerystring("mode");
    document.location.assign(url);
};
function PivotConfig(area)
{	
    var url= "../Plugins/PivotConfig.aspx?";
    if(typeof(AppItem)=="string" && AppItem.length > 0){url+="AppItem=" + AppItem;}
    if(typeof(ModelID)=="string" && ModelID.length > 0){url+="ModelID=" + ModelID;}	
    var sessionid=document.location.href.getquerystring("sessionid");
    if(sessionid.length>0){url+="&sessionid="+sessionid;}
    if(area){url+="&area=" + area;}
    var arr=document.location.href.getquerys();
    for(var i=0;i<arr.length;i++)
    {
        //url=url.addquerystring(arr[i].name,arr[i].value);	
    }
    //url=url.addquerystring("act","pivot");	
    //url+="&t=" + now();
    layer.open({
        type: 2,
        title: "数据透视",
        // title:['信息提示框','120px'],
        //maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area:IsMobile() ? ['95%','95%'] : ["530px" , "450px"],   
        // content: [url,'no'], 
        btn: ['确定', '取消'],
        content: url,
        yes: function (index, layero) {
            var doc = layero.find('iframe')[0].contentWindow.document;
            //alert($(doc).find("tbody select[name='parentid'] option:selected"));		  
            if($(doc).find("tbody select[name='parentid'] option:selected[value='']").length>0)
            {
                layer.msg("请选择自定义的列!");
                return;
            }
            if ($(doc).find("tbody input[name='groups']:checked").length < 1) {
                layer.msg("请选择分组字段!");
                return;
            }
            layero.find('iframe')[0].contentWindow.saveConfigs(index);
            arrLayerIndex.pop();
            layer.close(index);
            setTimeout(function(){
                document.location.assign(document.location.href.addquerystring("mode","pivot")); 
            },1000);
        },
        btn2: function(index, layero)
        {
            arrLayerIndex.pop();
            var url=document.location.href;
            if(url.indexOf("pivot")>-1)
            {
                url=url.removequerystring("mode");
                document.location.assign(url);
            }
        },
        cancel: function(index, layero){
            //关闭
            arrLayerIndex.pop();
        },
        success: function(layero, index){arrLayerIndex.push(index);},	  
        end : function(index){arrLayerIndex.pop();}
    });		
};
//获取记录集
function simple_getRecordData(id,qstr) 
{
    qstr=qstr||"";
    var url = virtualPath + "Plugins/getRecordData.aspx?id=" + id + qstr;
    var result = null;
    $("#mask").show();
    setTimeout(function () { $("#mask").hide(); }, 6000);
    $.ajax({
        type: "get",
        async: false,
        url: url,
        dataType: "json",
        success: function (data) {
            result = data;
            $("#mask").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) 
        {
            $("#mask").hide();
        }
    });
    return result;
}
//
function simple_updateTable(datasource,name,fields)
{
    datasource=datasource||"";
    var data=new Object();
    if(datasource.length > 0)
    {
        data["datasource"]= datasource;//数据源
    }
    data["name"]= name;//表名
    data["fields"]=fields;
    return updateTable(data);
};
//更新表
function updateTable(obj)
{
    var url = virtualPath + "Plugins/tableUpdate.aspx";
    var result = null;
    $("#mask").show();
    setTimeout(function () { $("#mask").hide(); }, 6000);
    $.ajax({
        type: "post",
        contentType: 'application/json',
        async: false,
        url: url,
        data: JSON.stringify(obj),
        dataType: "json",
        success: function (data) {
            result = data;
            $("#mask").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) 
        {
            $("#mask").hide();
        }
    });
    return result;
};
//全屏
function openFullscreen() {
  var  elem = document.documentElement;
    if (elem.requestFullscreen) {
        elem.requestFullscreen();
    } else if (elem.webkitRequestFullscreen) { // Safari
        elem.webkitRequestFullscreen();
    } else if (elem.mozRequestFullScreen) { // Firefox
        elem.mozRequestFullScreen();
    } else if (elem.msRequestFullscreen) { // IE/Edge
        elem.msRequestFullscreen();
    }
}
//退出全屏
function quitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) { // Safari
        document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) { // Firefox
        document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) { // IE/Edge
        document.msExitFullscreen();
    }
}
//执行动作
function simple_execAction(params)
{
    var url=document.location.href;
    if(params.indexOf("&")>0){ url+="&";}
    url+=params;
    ajaxGet(url);
    reloadDoc();
};
function simple_getProcedureData(datasource,name,params)
{
    datasource=datasource||"";
    var data=new Object();
    if(datasource.length > 0)
    {
        data["datasource"]= datasource;//数据源
    }
    data["name"]= name;
    data["params"]= params;//参数
    return getProcedureData(data);
};
function getProcedureData(obj) {
    var url = virtualPath + "Plugins/getProcedureData.aspx";
    var result = {};
    $("#mask").show();
    setTimeout(function () { $("#mask").hide(); }, 6000);
    $.ajax({
        type: "post",
        async: false,
        url: url,
        data: obj,
        dataType: "json",
        success: function (data) {
            result = data;
            $("#mask").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) 
        {
            $("#mask").hide();
        }
    });
    return result;
};

function simple_execProcedure(datasource,name,params)
{
    datasource=datasource||"";
    var data=new Object();
    if(datasource.length > 0)
    {
        data["datasource"]= datasource;//数据源
    }
    data["name"]= name;
    data["params"]= params;//参数
    return execProcedure(data);
};
function execProcedure(obj)
{   
    var url = virtualPath + "Plugins/Procedure.aspx";
    var result={};
    $("#mask").show();
    setTimeout(function () { $("#mask").hide(); }, 6000);
    $.ajax({
        type: "post",
        async: false,
        url:url,
        data:obj,
        dataType: "json",
        success: function (data)
        {
            result=data;
            $("#mask").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) 
        {
            $("#mask").hide();
        }
    });
    return result;
};
function execMethod(obj)
{
    var url = virtualPath + "Plugins/Reflection.aspx";
    var data={};
    $("#mask").show();
    setTimeout(function () { $("#mask").hide(); }, 6000);
    $.ajax({
        type: "post",
        async: false,
        data:obj,
        url:url,
        dataType: "json",
        success: function (_data)
        {
            data=_data;
            $("#mask").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) 
        {
            $("#mask").hide();
        }
    });
    return data;
};
function saveStream(stream) {
    //alert(typeof(stream));
    var url = virtualPath + "Plugins/ProUpload.aspx?type=image";
    //if($(obj).parent().attr("MaxWidth").length>1) {url+="&PictureMaxWidth=" + $(obj).parent().attr("MaxWidth");}
    var formData = new FormData();
    formData.append('files', stream, "aaa.png");
    $.ajax({
        type: "post",
        async: false,
        data: formData,
        url: url,
        dataType: "json",
        contentType: false,
        cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        success: function (data) {
            //alert(JSON.stringify(data));
            if (data.errcode == "0") {
                var box = $("#" + lastpictureobjid + "_box");
                if (data.files.length > 0) {
                    $("#" + lastpictureobjid).val(data.files[0].url);
                    box.find("img").attr("src", data.files[0].url);
                    if (box.find("iframe").length > 0) {
                        var _url = box.find("iframe").attr("src");
                        _url = _url.addquerystring("act", "finsh");
                        _url = _url.addquerystring("file", data.files[0].url);
                        box.find("iframe").attr("src", _url);

                    }
                    //lastpictureobj.siblings("input").val(data.files[0].url);
                    //lastpictureobj.attr("src",data.files[0].url);
                    //$("#" + $(obj).attr("id").replace("_file","")).val(data.files[0].url);

                }
                lastpictureobjid = null;
                layer.close(arrLayerIndex.pop());
            }
            else {
                layer.msg(data.message);
            }
            //
            //
            /*
			layer.msg(data.message);
			obj.value="";
			var callback=$(obj).attr("callback");
			if(callback)
			{
				//eval("if(typeof(" + callback + ")=='function'){" + callback + "(" + data.files +  ");}");
				if(data.files)
				{
					eval(callback + "(data.files);");
				}
				else
				{
					eval(callback + "(data);");
				}
			}
			*/
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) { }
    });
};
var serverIds = [];
var localIds = [];
//配置
function WeChatConfig(area)
{
    var acc = getWeChatShareData(area);
    acc = acc[0];
    wx.config({
        debug: false,
        appId: acc.appid,
        timestamp: parseInt(acc.timestamp),
        nonceStr: acc.noncestr,
        signature: acc.signature,
        jsApiList: ['checkJsApi', 'chooseImage', 'uploadImage', 'downloadImage'],
        complete: function (ret) {
            //alert("wx.config.complete:" + JSON.stringify(ret))
        }
    });
};
//选择图片
function WeChatChooseImage(obj, area,callback) {
    wx.chooseImage({
        count: 9, // 默认9
        sizeType: ['compressed'], //   可以指定是original原图还是compressed压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            localIds = res.localIds;
            WeChatSyncUpload(obj, area, callback);
        }
    });
};
//上传图片
function WeChatSyncUpload(obj, area, callback)
{
    if (!localIds.length || localIds.length == 0) {
        var json = '[';
        for (var i = serverIds.length - 1; i >= 0; i--) {
            if (i < serverIds.length - 1) json += ',';
            json += '{"mediaid":"' + serverIds[i] + '"}';
        }
        json += ']';

        var data = WeChatDownloadImages(json, area);
        callback(data);
    }
    else {
        var localId = localIds.pop();
        wx.uploadImage({
            localId: localId,
            isShowProgressTips: 0,
            success: function (res) {
                serverIds.push(res.serverId);
                WeChatSyncUpload(obj, area, callback);
            }
        });
    }
};
//下载图片
function WeChatDownloadImages(json,area)
{
    var url = virtualPath + "Plugins/Tencent/WeChat/downloadImages.aspx";
    if (area) { url += "?area=" + area; }
    var data = [];
    $.ajax({
        type: "post",
        data: { data: json },
        async: false,
        url: url,
        dataType: "json",
        success: function (_data) {
            serverIds = [];
            data = _data.files;
        }
    });
    return data;
};

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

    var url=$(obj).val();
    if(url.toLowerCase().indexOf("http")==0)
    {
        var title=getHtmlTitle(url);
        txt.val(title);
    }
    //alert(url.toLowerCase().indexOf("http"));
};
function addFromLink(obj,id)
{
    //var url="http://www.eketeam.com/";
    //var title=getHtmlTitle(url);
    //alert(title);
    //return;
    var input=$("#" + id);
    var ol=$(obj).parent().find("ol");
    layer.open({
        type: 1 //Page层类型
	,title: "添加连接"
	,skin: 'layui-layer-prompt'
	,moveOut:true
	,shadeClose: true
    ,btn:["确定","取消"]	
   	,area : ["400px" , "260px"]  
    ,content: '<div>地址：<input id="url" type="text" class="layui-layer-input" value="" onblur="flinkblur(this);" placeholder="连接地址">名称：<input style="margin-top:10px;" id="name" type="text" class="layui-layer-input" value="" placeholder="连接名称"></div>'
    ,yes: function(index, layero){
        //为空判断
        var model=input.val().toJson();
        //model.Convert=true;	
        var data=new Object();
        data["url"]=$(layero).find("#url").val();
        data["name"]= $(layero).find("#name").val();
	
        ol.append('<li onclick="editFromLink(this,\'' + id + '\');">' + $(layero).find("#name").val() + '<a href="javascript:;" class="del" onclick="delFromLink(this,\'' + id + '\');">&nbsp;</a></li>');	
		
        model.append(data);	
        input.val(model.toJson());
        layer.close(index);
	  
    }
    });
	
};
//文件查看
function viewFile(path,width,height)
{
    if(path.toLowerCase().indexOf("upload/")>0){path=path.substring(path.toLowerCase().indexOf("upload/"));}
    var _width=typeof(width)=="undefined" ? "80%" : width;
    var _height=typeof(height)=="undefined" ? "80%" : height;	
    if(path.indexOf(".mp3")>-1)
    {
        _width="360px";
        _height="160px";
    }
    if(path.indexOf(".mp4")>-1)
    {
        if(IsMobile())
        {
            _width="90%";
            _height="360px";
        }
        else
        {
            _width="680px";
            _height="560px";
        }
    }
    var url = virtualPath + "Plugins/viewFile/default.aspx?path=" + path;
    layer.open({
        type: 2,
        title: "文件预览",
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area : [_width,_height],
        // content: [url,'no'], 
        content: url,
        success: function(layero, index){},
        cancel: function(index, layero){},
        end : function(index){}
    });	
};
//人员选择
var UserSelectParent;
function removeUserSelect(obj)
{
	layer.confirm('', {btn: ['确定', '取消'], title: "确认要清空吗?",shadeClose: true}, function (idx, layero) {
		var box=$(obj).parent().parent();
		$(obj).parent().find(".body").attr('title','');
		$(obj).parent().find(".body").html('');	
		box.find("input").val('');
		layer.close(idx);
    });	
	
};
function openUserSelectN(obj,controlid,area,multi)
{
    var vpath=obj.getAttribute("vpath");
    UserSelectParent=$(obj).parent().parent();//box
    //alert(UserSelectParent.get(0).tagName);
    var title=$(obj).parent().parent().attr("fieldname");
    var url=(vpath == null ? virtualPath : vpath) + "Plugins/UserSelectN.aspx?obj=" + controlid + "&multi=" + multi;
    if(area){url+="&area=" + area;}
    url+= "&t=" + now()
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title: title,//'人员选择',
        moveOut:true,
        maxmin: true,
        btn:["确定"],
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
        area:IsMobile() ? ['95%','80%'] : ["65%" , "85%"],    
        content: url,
        success: function (layero, index) {
            arrLayerIndex.push(index); 
            setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
        },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
};
function openUserSelect(obj,controlid,area)
{
    var vpath=obj.getAttribute("vpath");
    UserSelectParent=$(obj).parent().parent();
    var title=$(obj).parent().attr("fieldname");
    var url=(vpath == null ? virtualPath : vpath) + "Plugins/UserSelect.aspx?obj=" + controlid;
    if(area){url+="&area=" + area;}
    url+= "&t=" + now()
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title: title,//'人员选择',
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
        area:IsMobile() ? ['95%','80%'] : ["600px" , "500px"],    
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
};
function openDepartmentSelect(obj,controlid,area)
{
    var vpath=obj.getAttribute("vpath");
    UserSelectParent=$(obj).parent().parent();
    var title=$(obj).parent().attr("fieldname");
    var url=(vpath == null ? virtualPath : vpath) + "Plugins/DepartmentSelect.aspx?obj=" + controlid ;
    if(area){url+="&area=" + area;}
    url+= "&t=" + now()
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title:title,// '部门选择',
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
        area:IsMobile() ? ['95%','95%'] : ["600px" , "500px"],    
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });	
	
};
function openCompanySelect(obj,controlid,area)
{
    var vpath=obj.getAttribute("vpath");
    UserSelectParent=$(obj).parent().parent();
    var title=$(obj).parent().attr("fieldname");
    var url=(vpath == null ? virtualPath : vpath) + "Plugins/CompanySelect.aspx?obj=" + controlid ;
    if(area){url+="&area=" + area;}
    url+= "&t=" + now()
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title:title,// '部门选择',
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
        area:IsMobile() ? ['95%','95%'] : ["600px" , "500px"],    
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });		
};
function openOrganizationalSelect(obj,controlid,area)
{
    var vpath=obj.getAttribute("vpath");
    UserSelectParent=$(obj).parent().parent();
    var title=$(obj).parent().attr("fieldname");
    var url=(vpath == null ? virtualPath : vpath) + "Plugins/OrganizationalSelect.aspx?obj=" + controlid ;
    if(area){url+="&area=" + area;}
    url+= "&t=" + now()
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title:title,// '部门选择',
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        //area: ['600px', '500px'],
        area:IsMobile() ? ['95%','95%'] : ["600px" , "500px"],    
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop(); }
    });		
};
function getRndCode(picid,type)
{
    if(type == 0 && document.getElementById(picid).src.indexOf("none.gif") == -1) {
        return;
    }
    document.getElementById(picid).src = virtualPath + "Plugins/RndPic.aspx?t=" + now();
};
//自定义导入程序
function custom_import(title,url)
{
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title: title,
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area: ['400px', '300px'],
        content: url,
        success: function (layero, index) { arrLayerIndex.push(index); },
        cancel: function (index, layero) { arrLayerIndex.pop(); },
        end: function (index) { arrLayerIndex.pop();document.location.assign(document.location.href); }
    });
};
//显示自定义项
function check_InputValue(obj)
{
    var span=$(obj).parent();	
	
    if(span.find("input[inputvalue]").length>0)
    {
        var value=span.find("input[inputvalue]").attr("inputvalue");
        if(obj.tagName=="SELECT")
        {
            //alert($(obj).val());
            if(value==$(obj).val())
            {
                span.find("input[inputvalue]").show();
            }
            else
            {
                span.find("input[inputvalue]").hide();
            }
            return;
        }
        if(span.find("input[value='" + value + "']:checked").length==1)
        {
            span.find("input[inputvalue]").show();
        }
        else
        {
            span.find("input[inputvalue]").hide();
        }
    }
};
//列表选择
function getSelectIDS1()
{
    var sels=$("input[name='selitem']:checked");
    if(sels.length==0) return "";
    var ids="";
    for(var i=0;i<sels.length;i++)
    {
        if(i>0){ids+=",";}
        ids+=sels[i].value;
    }
    return ids;
};
function unselectAll()//取消选择所有
{
    var tbody = getSelectBody();
    var sels = tbody.find("tr[class='select']");
    var qdlg = $("#quickviewbody");
    if (sels.length > 1 || qdlg.length == 0)
    {
        
        if (qdlg.length == 1)
        {
            var edataid = qdlg.attr("edataid");
            sels.each(function (i, elem) {
                var erowid = $(elem).attr("eRowID");
                if (erowid != edataid)
                {
                    $(this).attr("class", "");
                    var chk = $(this).find("input[name='selitem']");
                    if (chk.length > 0) {
                        chk.prop("checked", false);
                        chk.attr("checked", false);
                    }
                }
            });
        }
        else
        {
            sels.each(function (i, elem) {
                $(this).attr("class", "");
                var chk = $(this).find("input[name='selitem']");
                if (chk.length > 0) {
                    chk.prop("checked", false);
                    chk.attr("checked", false);
                }
            });
        }
        var chkall = $("input[name='selallitem']");
        if (chkall.length > 0) {
            chkall.prop("checked", false);
            chkall.attr("checked", false);
        }
        selectItems_check(tbody);
    }
};
function selectAll()//选择所有
{
    var tbody = getSelectBody();   
    var sels = tbody.find("tr[etype!='sum']");
    sels.each(function (i, elem) {
        $(this).attr("class", "select");
        var chk = $(this).find("input[name='selitem']");
        if (chk.length > 0) {
            chk.prop("checked", true);
            chk.attr("checked", true);
        }
    });
    var chkall = $("input[name='selallitem']");
    if (chkall.length > 0)
    {
        chkall.prop("checked", true);
        chkall.attr("checked", true);
    }
    selectItems_check(tbody);
};
function prevRecord()//上一条记录
{
    var chkall = $("input[name='selallitem']");
    if (chkall.length > 0) {
        return;
    }
    var tbody = getSelectBody();
    var sels = tbody.find("tr[class='select']");
    if (sels.length == 1)
    {
        if (sels.prev().length == 1)
        {
            sels.attr("class", "");
            sels.prev().attr("class", "select");
            //alert(typeof (sels.prev()[0].click));
            //sels.prev().trigger("click");
            sels.prev()[0].click();
        }
    }
};
function nextRecord()//下一条记录
{
    var chkall = $("input[name='selallitem']");
    if (chkall.length > 0) {
        return;
    }
    var tbody = getSelectBody();
    var sels = tbody.find("tr[class='select']");
    if (sels.length == 1)
    {
        if (sels.next().length == 1)
        {
            var etype = sels.next().attr("etype");

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

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


    if($("input[name='selitem']:checked").length==0)
    {
        $("#btn_PrintMore").hide();
        $("#btn_selMore").hide();
        $("#btn_delMore").hide();
        $("#btn_editMore").hide();
        $(".selectMore").hide();
    }
    else
    {
        $("#btn_PrintMore").show();
        $(".selectMore").show();
        $("#btn_selMore").show();
        $("#btn_editMore").show();
        var count=0;
        $("input[name='selitem']:checked").each(function(i,elem)
        {			
            count+=$(elem).parents("tr:first").find("a[href*='act=del']").length;
            count+=$(elem).parents("tr:first").find("a[_href*='act=del']").length;
            count+=$(elem).parents("tr:first").find("a[ehref*='act=del']").length;
        });
        if(count==0)
        {
            $("#btn_delMore").hide();
        }
        else
        {
            $("#btn_delMore").show();		
        }
    }
    if(typeof(select_callback)=="function")
    {
        select_callback();
    }		
};
//删除-全选
function selectdelItems(obj)
{
    $("input[name='delitem']").prop("checked",obj.checked);
    deleteMore_check();
};
//是否有可删除项判断
function deleteMore_check()
{
    //alert($("input[name='delitem']:checked").length);
    if($("input[name='delitem']:checked").length==0)
    {
        $("#btn_delMore").hide();
    }
    else
    {
        var count=0;
        $("input[name='delitem']:checked").each(function(i,elem)
        {			
            count+=$(elem).parents("tr:first").find("a[href*='act=del']").length;
            count+=$(elem).parents("tr:first").find("a[_href*='act=del']").length;
            count+=$(elem).parents("tr:first").find("a[ehref*='act=del']").length;
        });
        if(count==0)
        {
            $("#btn_delMore").hide();
        }
        else
        {
            $("#btn_delMore").show();
        }
    }
};
//对比按钮事件
function contrastMore()
{
    var ids = getSelectIDS();
    if (ids.length == 0) {
        layer.msg("请选择要对比的数据!");
        return;
    }
    var url = document.location.href;
    url += url.indexOf("?") > -1 ? "&" : "?";
    url += "act=viewmore&id=" + ids;
    var table = getobj("eDataTable");
    var ajax = parseBool(table.getAttribute("ajax"));
    if (!ajax) {
        document.location.assign(url);
        return;
    }
    url = url.addquerystring("ajax", "true");
    layer.open({
        type: 2,
        title: "对比",
        moveOut: true,
        shadeClose: true, //点击遮罩关闭层
        //area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"],
        //offset: [rect.top + "px", rect.left + "px"],
        area: ["95%", "95%"],
        content: url,
        success: function (layero, index) {
            arrLayerIndex.push(index);
        },
        cancel: function (index, layero) {
            arrLayerIndex.pop();
        }
    });
};
function delrequest(url)
{
    url=url.addquerystring("ajax","true");
    $.ajax({
        type: 'get',
        async: false,
        url: url,	
        dataType: "html",
        success: function(data)
        {
        }
    });
};
function deleteMore(delmode)
{
    delmode=delmode||0;
    //alert(delmode);
    var ids = getSelectIDS("del");
    if (ids.length == 0) {
        layer.msg("请选择要删除的数据!");
        return;
    }
    var chkall = $("input[name='selallitem']")[0].checked || false;
    var page = getobj("page");
    var mode= document.location.href.getquerystring("mode");//recycle
    if (delmode == 0 || !chkall) {
        var url = document.location.href;
        url = url.addquerystring("act", "delmore");
        url = url.addquerystring("ids", ids);
        layer.confirm('确认要删除所选数据吗?', {
            title: "删除", shadeClose: true, area: ['220', '160'], btn: ['删除', '取消'],
            btn1: function (idx, layero) {
                if (top != self)//Frame打开
                {
                    delrequest(url);
                    Search();
                    layer.close(idx);
                }
                else
                {
                    document.location.assign(url);
                }
            }
        });
    }
    else
    {
        layer.confirm('请选择打印范围?', {title: "删除",shadeClose: true, btn: ['删除已选', '删除所有', '取消']},
			function (idx, layero)
			{
			    //删除已选
			    layer.close(idx);
			    var url=document.location.href;
			    url=url.addquerystring("act","delmore");
			    url=url.addquerystring("ids",ids);
			    if(top!=self)//Frame打开
			    {
			        delrequest(url);
			        Search();
			    }
			    else
			    {
			        document.location.assign(url);
			    }
				
			},function(idx, layero)
			{
			    //删除所有
			    layer.close(idx);
			    var url=document.location.href;
			    url=url.addquerystring("act","delmore");
			    if(top!=self)//Frame打开
			    {
			        delrequest(url);
			        Search();
			    }
			    else
			    {
			        document.location.assign(url);
			    }
			}
		);
    }
};
//编辑所选按钮事件
function editMore(obj, width, height)
{
    if (!width) width = "95%";
    if (!height) height = "95%";
    var ids = getSelectIDS("edit");
    if (ids.length == 0)
    {
        layer.msg("请选择要编辑的数据!");
        return;
    }
    var chkall = $("input[name='selallitem']")[0].checked || false;
    if (!chkall) 
    {
        var url = document.location.href;
        if (ids.indexOf(",") > -1 || 3>1)
        {
            url = url.addquerystring("act", "editmore");
            url = url.addquerystring("ids", ids);
        }
        else
        {
            url = url.addquerystring("act", "edit");
            url = url.addquerystring("id", ids);
        }
        if (top != self)//Frame打开
        {
            url = url.addquerystring("ajax", "true");
            top.layer.open({
                type: 2,
                title: "批量修改",
                moveOut: true,
                maxmin: true,
                shadeClose: true, //点击遮罩关闭层
                area: [width, height],
                content: url,
                success: function (layero, index) {
                    top.arrLayerIndex.push(index);
                }, 
                cancel: function (index, layero) {
                    top.arrLayerIndex.pop();
                },
                end: function (index) {
                    top.arrLayerIndex.pop();
                }
            });
        }
        else {
            document.location.assign(url);
        }
    }
    else
    {
        layer.confirm('请选择编辑范围?', {title: "编辑",shadeClose: true, btn: ['编辑已选', '编辑所有', '取消']},
			function (idx, layero)
			{
			    //修改已选
			    layer.close(idx);
			    var url=document.location.href;
			    url = url.addquerystring("act","editmore");
			    url = url.addquerystring("ids",ids);
			   
			    //alert("修改已选:" + url);
			    //return;
			    if(top!=self)//Frame打开
			    {
			        url = url.addquerystring("ajax", "true");
			        top.layer.open({
			            type: 2,
			            title: "批量修改",
			            moveOut: true,
			            maxmin: true,
			            shadeClose: true, //点击遮罩关闭层
			            area: [width, height],
			            content: url,
			            success: function (layero, index) {
			                top.arrLayerIndex.push(index);
			            }, 
			            cancel: function (index, layero) {
			                top.arrLayerIndex.pop();
			            },
			            end: function (index) {
			                top.arrLayerIndex.pop();
			            }
			        });
			    }
			    else
			    {
			        document.location.assign(url);
			    }
				
			},function(idx, layero)
			{
			    //修改所有
			    layer.close(idx);
			    var url=document.location.href;
			    url = url.addquerystring("act","editmore");

			    //alert("修改所有:" + url);
			    //return;
			    if(top!=self)//Frame打开
			    {
			        url = url.addquerystring("ajax", "true");
			        top.layer.open({
			            type: 2,
			            title: "批量修改",
			            moveOut: true,
			            maxmin: true,
			            shadeClose: true, //点击遮罩关闭层
			            area: [width, height],
			            content: url,
			            success: function (layero, index) {
			                top.arrLayerIndex.push(index);
			            }, 
			            cancel: function (index, layero) {
			                top.arrLayerIndex.pop();
			            },
			            end: function (index) {
			                top.arrLayerIndex.pop();
			            }
			        });
			    }
			    else
			    {
			        document.location.assign(url);
			    }
			}
		);
    }
};
//批量打印
function printMore()
{
    //var ids = getSelectIDS();
    var ids = getSelectIDS("print");
    if (ids.length == 0) {
        layer.msg("请选择要打印的数据!");
        return;
    }
    //alert(ids);
    //return;
    var chkall = $("input[name='selallitem']")[0].checked || false;
    if (!chkall) 
    {
        var url = document.location.href;
        url = url.addquerystring("act", "print");
        url = url.addquerystring("id", ids);
        url = url.addquerystring("ajax", "true");
        var table = getobj("eDataTable");
        var ajax = parseBool(table.getAttribute("ajax"));
        if (!ajax) {
            //document.location.assign(url);
            //return;
        }
   
        var parentDOM = top || window;
        parentDOM.layer.open({
            type: 2,
            title: "打印",
            moveOut: true,
            shadeClose: true, //点击遮罩关闭层
            //area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"],
            //offset: [rect.top + "px", rect.left + "px"],
            area: ["95%", "95%"],
            content: url,
            maxmin: true,
            success: function (layero, index) 
            {
                parentDOM.arrLayerIndex.push(index);
                setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
            },
            cancel: function (index, layero) {
                parentDOM.arrLayerIndex.pop();
            },
            end: function (index) {
                parentDOM.arrLayerIndex.pop();
            }
        });
    }
    else
    {
        layer.confirm('请选择打印范围?', {title: "打印",shadeClose: true, btn: ['打印已选', '打印所有', '取消']},
			function (idx, layero)
			{
			    //打印已选
			    layer.close(idx);
			    var url=document.location.href;
			    url = url.addquerystring("act","print");
			    url = url.addquerystring("id",ids);
			    url = url.addquerystring("ajax", "true");
			    var parentDOM = top || window;
			    parentDOM.layer.open({
			        type: 2,
			        title: "打印",
			        moveOut: true,
			        shadeClose: true, //点击遮罩关闭层
			        //area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"],
			        //offset: [rect.top + "px", rect.left + "px"],
			        area: ["95%", "95%"],
			        content: url,
			        maxmin: true,
			        success: function (layero, index) 
			        {
			            parentDOM.arrLayerIndex.push(index);
			            setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
			        },
			        cancel: function (index, layero) {
			            parentDOM.arrLayerIndex.pop();
			        },
			        end: function (index) {
			            parentDOM.arrLayerIndex.pop();
			        }
			    });
				
			},function(idx, layero)
			{
			    //打印所有
			    layer.close(idx);
			    var url=document.location.href;
			    url = url.addquerystring("act","print");
			    url = url.addquerystring("ajax", "true");
			    var parentDOM = top || window;
			    parentDOM.layer.open({
			        type: 2,
			        title: "打印",
			        moveOut: true,
			        shadeClose: true, //点击遮罩关闭层
			        //area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"],
			        //offset: [rect.top + "px", rect.left + "px"],
			        area: ["95%", "95%"],
			        content: url,
			        maxmin: true,
			        success: function (layero, index) 
			        {
			            parentDOM.arrLayerIndex.push(index);
			            setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
			        },
			        cancel: function (index, layero) {
			            parentDOM.arrLayerIndex.pop();
			        },
			        end: function (index) {
			            parentDOM.arrLayerIndex.pop();
			        }
			    });
			}
		);
    }
};
//刷新窗口数据
function reloadDoc()
{
    if(top!=self)
    {
        Search();
    }
    else
    {
        document.location.assign(document.location.href);
    }
};
//get请求
function ajaxGet(url)
{
    url=url.addquerystring("ajax","true");
    url=url.addquerystring("t",now());
    $.ajax({
        type: 'get',
        async: false,
        url: url,
        dataType: "html",
        success: function(data){
        }
    });
};
//post请求
function ajaxPost(url,obj)
{
    url=url.addquerystring("ajax","true");
    $.ajax({
        type: 'post',	
        async: false,
        url: url,
        data:obj,
        dataType: "html",
        success: function(data){
            //layer.msg(data);
        }
    });
};
function getTableRows(obj)
{
	var table=$("#" + obj);
	var tbody=table.find(">tbody");	
	var trs=tbody.find(">tr:visible");
	return trs;
};
function TableSum(id,name)
{
    var table=$("#" + id);
    var tbody=table.find(">tbody");	
    var trs=tbody.find(">tr:visible");
    var result=0;
    trs.each(function(i,el){		
        var hj=getHTMLValue($(this).find("[postname='" + name + "']").val());//合计
        result+=hj;
    });
    return result;
};
//去掉多余HTML返回数值类型
function getHTMLValue(html)
{
    var value=0;
    html=html.replace(/ /g,"");
    html=html.replace(/&nbsp;/g,"");
    html=html.replace(/,/g,"");
    if(html.length==0){return value;}
    try 
    {		
        value = html.indexOf(".") > -1 ? parseFloat(html) : parseInt(html);
    }
    catch(e)
    {
        return 0;
    }
    return value;
};
//生成拼音
function MakePinyin(obj,objid)
{	
    var value = obj.value.length==0 ? "" : pinyinUtil.getFirstLetter(obj.value, true).toString();
    $("#" + objid).val(value);
    //$("#" + objid).attr("ovalue",value);
};
function IsMobile() 
{
    var userAgentInfo = navigator.userAgent.toLowerCase();
    var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone","iPad", "iPod", "Windows CE", "Windows Mobile", "UCWeb", "Midp"];
    var flag = false;
    for(var i = 0; i < Agents.length; i++) 
    {
        if (userAgentInfo.indexOf(Agents[i].toLowerCase()) > -1) 
        {
            flag = true;
            break;
        }
    }
    return flag;
};
function getReportHeight(obj)
{
    var rep=obj.parent();
    var height=rep.height();
    if(rep.find("h1").height()){height-=rep.find("h1").height()+14;}
    if(rep.find("p").height()){	height-=rep.find("p").height()+14;}
    return height;
};
function fonticonselect(obj)
{
    var url = "../Plugins/FontIconSelect.aspx?obj=" + obj;
    layer.open({
        type: 2,
        title: "选择图标",
        shadeClose: true, //点击遮罩关闭层
        area: ["1000px", "600px"],
        content: url,
        success: function (layero, index) {
            arrLayerIndex.push(index);
        },
        cancel: function (index, layero) {
            arrLayerIndex.pop();
        }
    });
};
function fileorpath_clear(obj)
{
    $("#" + obj).val('');
    if(typeof(fileLibrary_select_finish)=="function"){fileLibrary_select_finish(obj);}
};
var fileLibraryobj=null;
function fileLibrary_select(obj,path,basepath)
{
    fileLibraryobj=getEventObject();
    var url = "../Plugins/FileSelect.aspx?obj=" + obj + (path.length > 0 ? "&path=" + path : "");
    if(basepath && basepath.length > 0){url+="&basepath=" + basepath;}
    url+= "&t=" + now();
    layer.open({
        type: 2,
        title: "选择文件",
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area:IsMobile() ? ['95%','95%'] : ["60%" , "80%"],    
        //area : ["60%" , "80%"],	
        // content: [url,'no'], 
        content: url,
        success: function(layero, index){arrLayerIndex.push(index);},
        cancel: function(index, layero){arrLayerIndex.pop();},
        end : function(index){
            if(typeof(fileLibrary_select_finish)=="function"){fileLibrary_select_finish(obj);}
            arrLayerIndex.pop();
        }
    });	
};
function path_select(obj,path)
{
    var url = "../Plugins/PathSelect.aspx?obj=" + obj + (path.length > 0 ? "&path=" + path : "");
    url+= "&t=" + now();
    layer.open({
        type: 2,
        title: "选择目录",
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area:IsMobile() ? ['95%','95%'] : ["60%" , "40%"],    
        btn: ['确定','取消'],
        //area : ["60%" , "80%"],	
        // content: [url,'no'], 
        content: url,
        yes: function(index,layero)
        {
            var path=$(layero).find('iframe')[0].contentWindow.document.location.href.getquerystring("path");
            $("#" + obj).val(path);
            arrLayerIndex.pop();
            layer.close(index);
        },
        success: function(layero, index){arrLayerIndex.push(index);},
        cancel: function(index, layero){arrLayerIndex.pop();},
        end : function(index){arrLayerIndex.pop();}
    });	
};
//Excel导入
var uploadTempFile="";
function excel_import(area)
{
    /*
    layer.alert('欢迎访问 hangge.com', {
      resizing: function(layero){
        console.log(layero);
      }
    });
    */
    var iframeWin;
    var url= "../Customs/base/ExcelImport.aspx?area=" + area;
    if(typeof(AppItem)=="string" && AppItem.length > 0){url+="&AppItem=" + AppItem;}
    if(typeof(ModelID)=="string" && ModelID.length > 0){url+="&ModelID=" + ModelID;}
    url+= "&t=" + now();
    layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title: "Excel导入",
        moveOut:true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area : ['95%' , '90%'],
        content: url,
        success: function(layero, index){
            arrLayerIndex.push(index);
		  
            //var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            //iframeWin = layero.find('iframe')[0].contentWindow;
            // var path=$(layero).find('iframe')[0].contentWindow.document.location.href.getquerystring("path");
            iframeWin = layero.find('iframe')[0];

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

            //alert( layero.find('iframe')[0].contentWindow.document.location);
        },
        end : function(index, layero, iframe){		  
            //arrLayerIndex.pop();
            //var _body = layer.getChildFrame('body', index);
            //var win=$("#layui-layer-iframe" + index);			
            //alert(win.contentWindow);
            //var res = window["layui-layer-iframe" + index].callbackdata(); 
            if(uploadTempFile.length>0)
            {
                removefile(uploadTempFile);
                uploadTempFile="";
            }
			 
            // alert( layero );
            //var file=iframeWin.document.location.href.getquerystring("file");
            //alert("end" + file);
            document.location.assign(document.location.href);
        }
    });
};

//异步加载20251119
function asyncLoad(obj,objIds)
{
    var url=document.location.href;	
    url=url.removequerystring("debug");
    var pid=obj.value;
    if(obj.tagName=="SELECT")
    {
        if(obj.options[obj.selectedIndex].getAttribute("code"))
        {
            if(obj.options[obj.selectedIndex].getAttribute("code").length>0)
            {
                pid=obj.options[obj.selectedIndex].getAttribute("code");
            }
        }
    }
    else
    {
        if(obj.getAttribute("code"))
        {
            if(obj.getAttribute("code").length>0)
            {
                pid=obj.getAttribute("code");
            }
        }
    }
    var objid=objIds.split(",");
    for(var t=0;t<objid.length;t++)
    {
        var file="";
        try
        {
            var arr=document.location.href.split("/");
            file=arr[arr.length-1].split(".")[0] + ".aspx";
        }
        catch(e)
        {
            file="Model.aspx";
        }
        var _pid=pid;
        if(!_pid)
        {
            if(obj.tagName=="SELECT")
            {
				
                if(obj.options[obj.selectedIndex].getAttribute("code"))
                {
                    if(obj.options[obj.selectedIndex].getAttribute("code").length>0)
                    {
                        _pid=obj.options[obj.selectedIndex].getAttribute("code");
                    }
                }
            }
            else
            {			
                switch(obj.type)
                {
                    case "radio":
                        if(obj.getAttribute("code"))
                        {
                            if(obj.getAttribute("code").length>0)
                            {
                                _pid=obj.getAttribute("code");
                            }
                        }
                        break;
                    case "checkbox":
                        if(obj.getAttribute("code"))
                        {
                            if(obj.getAttribute("code").length>0)
                            {
                                _pid=obj.getAttribute("code");
                            }
                        }
                        break;
                }
            }
        }
        var _url= file +  (!document.location.href.getquerystring("act") ? "?act=getdata" : "?act=edit");
        if(typeof(AppItem)=="string" && AppItem.length > 0){_url+="&AppItem=" + AppItem;}
        if(typeof(ModelID)=="string" && ModelID.length > 0){_url+="&ModelID=" + ModelID;}
        if(url){_url=url;}
        _url += "&Pid=" + _pid;
        _url += "&obj=" + objid[t];
        var query="";
        if(typeof(asyncLoad_before)=="function")
        {
            var _back = asyncLoad_before(objid[t]);
            if(typeof(_back)=="object")
            {
                query=_back.query.replace("?","");				
                if(query.length>0)
                {
                    var arr=query.split("&");
                    for(var x=0;x<arr.length;x++)
                    {
                        var arr2=arr[x].split("=");
                        if(arr2.length==2)
                        {
                            _url=_url.addquerystring(arr2[0],arr2[1]);
                        }
                        //alert(arr[x] + "::" + arr2.length);
                    }
                    //alert(query + "::" + arr.length);
                    //if(query.indexOf("&")!=0){query="&" + query;}	
                    //alert(_url);
                }
            }
        }
        //if(query.length>0){_url+=query;}
        _url += "&t=" + now();
        //alert(_url);		
        var fillarea = $(obj).parents("[eitemrow]:first");
        //搜索
        if(fillarea.length == 0)
        {
            fillarea = $(obj).parents("form:first");
        }
        //return;		
        $.ajax({
            type: "GET",
            async: false,
            url: _url,
            dataType: "json",
            success: function(data)
            {
                //alert(JSON.stringify(data));
                if (!data) { return; }
                var box=fillarea.find("#" + objid[t] + "_box");

                ReFillControl(box,objid[t], data);
			
                if(typeof(asyncLoad_finish)=="function"){asyncLoad_finish(pid,objid[t]);}			
			
                /*
                //$("#" + ObjID).empty();			
                 */
            }
        });
    }	
};
//重新填充控件选项，异步加载和
function ReFillControl(box,id,data)
{
    var html = '';
    var controltype = box.attr("etype");
    switch (controltype) {
        case "text":
        case "textarea":
            if (data.length > 0)
            {
                box.find("[postname='" + id + "']").val(data[0]["value"]);
            }
            else {
                var dvalue = box.find("[postname='" + id + "']").attr("defaultvalue");
                box.find("[postname='" + id + "']").val(dvalue);
            }
            break;
        case "filterselect":
            var selv=box.find("input[type='hidden']:eq(0)").val();
            var selv2=box.find("input[type='hidden']:eq(1)").val();
            box.find("li").remove();
            box.find("input[type='hidden']:eq(0)").val('');
            box.find("input[type='hidden']:eq(1)").val('');
            box.find("span:eq(0)").find("span:eq(0)").text('请选择');
            $.each(data, function () {
                box.find("ul").append('<li value="' + this["value"] + '" onclick="set_filterText(this);"' + (typeof (this["code"]) != "undefined" ? ' code="' + this["code"] + '"' : '') + '>' + this["text"] + '</li>');
            });

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

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

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

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

                }

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

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

    //alert(treefrommode + "::" + treefromid);
    if(typeof(frametop)== "undefined"){frametop=1;}
    if(url.toLowerCase().indexOf("appitem=")==-1)
    {
        if(typeof(AppItem)=="string" && AppItem.length>0){url=url.addquerystring("AppItem",AppItem);}
    }
    var action = url.toLowerCase().getquerystring("act");
    var act = url.toLowerCase().getquerystring("act");
    //alert(action);
    if(obj.getAttribute("etext"))
    {
        var _text = obj.getAttribute("etext");
        var _href = url.getquerystring("appitem").length > 0 ? url.getquerystring("appitem") : url;
        //outText(_href);
        //var tab = $(".eFrameTab dt a[_href='" + _href + "']");
        var tab = $(top.document).find(".eFrameTab dt a[_href='" + _href + "']");
        // top.document.title = tab.length + "::" + action;
        //outText(tab.length);
        var allowOpen = 1;

        if (typeof (top.frameTagCount) != "undefined") { allowOpen = top.frameTagCount; }
        
	    
        //if (tab.length == 0 || allowOpen == 0) { // allowOpen == 0 时会重复打开
        if (tab.length == 0) {
            url = url.removequerystring("act");
            var eappid = "";
            var app = $(".applists a.cur");
            if (app.length > 0) {
                eappid = app.attr("eappid");
            }
            parent.eFrameTab_add(url, _text, eappid);
            if (action.length > 0) {
                setTimeout(function () {
                    //parent.goLink(obj, width, height, frametop, ismax);
                    var curtab = $(parent.document).find(".eFrameTab dt a.cur");
                    var win = $(parent.document).find(".eFrameTab dd iframe:eq(" + curtab.index() + ")").get(0).contentWindow;
                    win.goLink(obj, width, height, frametop, ismax);
                    //alert(typeof (doc.goLink));
                }, 1000);
            }
            return;
        }
        else
        {
	        
            if (action.length == 0)
            {
                var eappid = "";
                var app = $(".applists a.cur");
                if (app.length > 0) {
                    eappid = app.attr("eappid");
                }
                parent.eFrameTab_add(url, _text, eappid);
                return;
            }
	       
            parent.eFrameTab_show(tab.index());
            /*
	        var _url = url.removequerystring("act");
	        var eappid = "";
	        var app = $(".applists a.cur");
	        if (app.length > 0) {
	            eappid = app.attr("eappid");
	        }
	        parent.eFrameTab_add(_url, _text, eappid);
            */

            var curtab = $(parent.document).find(".eFrameTab dt a.cur");	       
            var win = $(parent.document).find(".eFrameTab dd iframe:eq(" + curtab.index() + ")").get(0).contentWindow;
            if (action.length > 0 )
            {
                url = url.addquerystring("ajax", "true");
            }
            win.layer.open({
                type: 2
				  , title: _text //$(obj).text()
				  , moveOut: true
				  , maxmin: true
				  , shadeClose: true //点击遮罩关闭层
                //,area: [(rect.right-rect.left) + "px",(rc.bottom-rc.top-rect.top-10) + "px"]
                //,offset: [rect.top + "px", rect.left + "px"]
                //,area: ["95%","95%"]
				  , area: [width, height]
				  , content: url
				  , success: function (layero, index) {
				      if (ismax) {
				          win.layer.full(index);
				      }
				      win.arrLayerIndex.push(index);
				      setTimeout(function () { layero.find('iframe')[0].contentWindow.focus(); }, 500);
				  }
				  , cancel: function (index, layero) {
				      win.arrLayerIndex.pop();
				  }
				  , end: function (index) {
				      win.arrLayerIndex.pop();
				  }
            });

            return;
        }
	    
        /*
        parent.eFrameTab_add(url, _text);
        return;
        */
    }
    //layer.msg("DD");
    if(url.toLowerCase().indexOf("=del")>-1)
    {
        var _back=confirm('确认要删除吗？');
        if(!_back){return;}		
    }
    //展示	
    var eframe = obj.getAttribute("eframe") || "true";
    //alert(eframe + "LL: " + action);
    if(url.toLowerCase().indexOf("value=")==-1 &&  url.toLowerCase().indexOf("=del")==-1 &&  url.toLowerCase().indexOf("=cancel")==-1  && (eframe=="true" || action=="li3st" || url.toLowerCase().indexOf("=add")>-1 || url.toLowerCase().indexOf("=edit")>-1 || url.toLowerCase().indexOf("=copy")>-1 || url.toLowerCase().indexOf("=view")>-1 || url.toLowerCase().indexOf("=print")>-1 ))
    {
        //alert(1 + ":" + url);
        //if(url.indexOf(".aspx")== -1){url="ModelInfo.aspx" + url;}
        //else{url=url.replace("Model.aspx","ModelInfo.aspx");}
        //if(typeof(AppItem)=="string" && AppItem == url.getquerystring("appitem") )		

        if(url.toLowerCase().indexOf("act=")>-1 && action!="list"){url=url.addquerystring("ajax","true");}
        //alert(url + "::" + url.toLowerCase().indexOf("=print"));

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

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

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

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

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

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

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

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


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

    //alert(url);
    //return;

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

            try
            {
                deleteObject(Loading);
            }
            catch(e)
            {
            }
            //selectMore_check();
            etable_init();
            init_quickviewBody();
            $("span.more").each(function(index, val) {
                var ele = $(this);		
                ele.on("click", function() {
                    showOptionMenu(this);			
                });	
					
            });
			   
            var table=document.getElementById("eDataTable");
            if(table)
            {
                /*
                if(table.parent)
                {
                     Table_Init_Tbody(table.parent);
                }
                */
				  
            }
			   
        }
    });
};
//提交搜索
function goSearch(frm,ajax)
{
    if(typeof(search_before)=="function")
    {
        var _back=search_before(frm);
        if(!_back){return false;}
    }
    var info=getSearchInfo(frm);
    document.location=info.url.replace(/\+/g,'%2B');//+号解码会变空格
    return false;
};
function getEasyUISearch(frm)
{
    var obj=new Object();
    var info=getSearchInfo(frm);
    var hash=info.hash;
    var keys = hash.keys();
    //for(var entry in keys)
    for(var i=0;i<keys.length;i++)
    {
        //var key=keys[entry];
        var key=keys[i];
        var value=hash.get(key);
        obj[key] = value;
    }	
    return obj;
};
function showPower(obj)
{
    var div=obj.parentNode;
    div=div.nextSibling;
    while(div.tagName!="DIV")
    {
        div=div.nextSibling;
    }
    //if(div.nodeType==3){div=div.nextSibling;}
    if(obj.className=="close")
    {
        obj.className="open";
        div.style.display="";
    }
    else
    {
        obj.className="close";
        div.style.display="none";
    }
};
//角色选择、取消选择
function selectRoles(obj)
{
    //var url="?act=getrole&roleid=" + obj.value + "&t=" + now();

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

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

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

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

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

function selectselItems(obj)
{
    //$("input[name='fillselitem']").prop("checked",obj.checked);
    //$("input[name='fillselitem']:not(:checked)").each(function(i,el){
    $("input[name='fillselitem']:not(:checked)").each(function(i,el){
        $(this).get(0).click();
    });
};

//兼容自动上传文件
function autoupload_check(obj)
{	
    var allowexts=obj.getAttribute("allowexts") || "";
    var preventexts=obj.getAttribute("preventexts") || "";
    if(allowexts.length>0){allowexts+=".";}
    if(preventexts.length>0){preventexts+=".";}
    if (obj.files)
    {		
        for(var i=0;i<obj.files.length;i++)
        {
            var ext=obj.files[i].name.fileExtension();
            if(ext.length==0||ext.indexOf(".")!=0)
            {
                obj.value = "";
                top.layer.msg("文件类型错误!");
                return false;
            }
            if(allowexts.length>0)
            {
                if(allowexts.toLowerCase().indexOf(ext + ".") == -1)
                {
                    obj.value = "";
                    //layer.msg("文件类型" +  ext + "被禁止上传!");
                    top.layer.msg("只允许上传" + allowexts.substring(0,allowexts.length-1) + "类型的文件!");
                    return false;
                }
            }
            else
            {
                if(preventexts.toLowerCase().indexOf(ext + ".") > -1)
                {
                    obj.value = "";
                    top.layer.msg("文件类型" +  ext + "被禁止上传!");
                    return false;
                }
            }
        }
    }
    else
    {
        var ext=obj.value.fileExtension();
        if(ext.length==0||ext.indexOf(".")!=0)
        {
            obj.value = "";
            top.layer.msg("文件类型错误!");
            return false;
        }
        if(allowexts.length>0)
        {
            if(allowexts.toLowerCase().indexOf(ext + ".") == -1)
            {
                obj.value = "";
                //layer.msg("文件类型" +  ext + "被禁止上传!");
                top.layer.msg("只允许上传" + allowexts.substring(0,allowexts.length-1) + "类型的文件!");
                return false;
            }
        }
        else
        {
            if(preventexts.toLowerCase().indexOf(ext + ".") > -1)
            {
                obj.value = "";
                top.layer.msg("文件类型" +  ext + "被禁止上传!");
                return false;
            }
        }
    }
    if(typeof(autoPost)=="function" && obj.name.toLowerCase()=="imgfile")
    {
        Form1.submit();
    }
    //alert(obj.name);
    return true;	
};
function autoupload_change(obj)
{
    var attach=obj.value;
    if(attach == undefined || attach == "")
    {
        //alert("请选择文件");
        return;
    }
    var result=autoupload_check(obj);
    if(!result){return;}
	
    var posturl=obj.getAttribute("posturl");
    var url = posturl == null ? virtualPath + "Plugins/ProUpload.aspx?type=file" : posturl;
    if(url=="auto")
    {
        url=document.location.href.addquerystring("act","upload");
        url=url.addquerystring("ajax","true");
    }
    //if($(obj).parent().attr("MaxWidth") && $(obj).parent().attr("MaxWidth").length>1) {url+="&PictureMaxWidth=" + $(obj).parent().attr("MaxWidth");}
    var maxWidth=$(obj).parent().attr("MaxWidth");
    if(maxWidth && maxWidth.length>1){url+="&PictureMaxWidth=" + maxWidth;}	
    if (obj.files)
    {
        autopostfile(obj,url);
    }
    else
    {
        autopostfile_ie(obj,url);
    }
};
function autopostfile(obj,url)
{
    var formData = new FormData();
    for(var i=0;i<obj.files.length;i++)
    {
        formData.append('files', obj.files[i], obj.files[i].name);
    }
    $.ajax({
        type: "post", 
        async: false,
        data:formData,
        url:url,
        dataType: "json",
        contentType: false,
        cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        success: function (data)
        {
            //layer.msg(data.message);
            obj.value="";
            var callback=$(obj).attr("callback");
            if(callback)
            {
                //eval("if(typeof(" + callback + ")=='function'){" + callback + "(" + data.files +  ");}");
                if(data.files)
                {
                    eval(callback + "(data.files);");
                }
                else
                {
                    eval(callback + "(data);");
                }
            }			
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {}
    });
};
function autopostfile_ie(obj,url)
{
    $.ajaxFileUpload ({
        type: "post",
        async: false,
        url: url, //用于文件上传的服务器端请求地址 
        secureuri: false, //一般设置为false 
        fileElementId: $(obj).attr("id"), //文件上传空间的id属性  <input type="file" id="file" name="file" /> 
        dataType: "json", //返回值类型 一般设置为json 
        success: function (data, status)  //服务器成功响应处理函数
        {
            layer.msg(data.message);
            obj.value="";
            var callback=$(obj).attr("callback");
            if(callback)
            {
                //eval("if(typeof(" + callback + ")=='function'){" + callback + "(" + data.files +  ");}");
                if(data.files)
                {
                    eval(callback + "(data.files);");
                }
                else
                {
                    eval(callback + "(data);");
                }
            }
        }, 
        error: function (data, status, e)//服务器响应失败处理函数
        {
            //alert("error");
            //alert(e); 
        } 
    });	
    //alert(2);
};
//删除临时文件
function removefile(file)
{
    if(file.toLowerCase().indexOf("upload/")>0){file=file.substring(file.toLowerCase().indexOf("upload/"));}
    var url=virtualPath + "Plugins/ProUpload.aspx?act=del&file=" + file;
    $.get({url:url,async:false});
};
//读取excel文件返回json
function exceltojson(file)
{
    if(file.toLowerCase().indexOf("upload/")>0){file=file.substring(file.toLowerCase().indexOf("upload/"));}
    var url= virtualPath + "Plugins/ExcelToJson.aspx?path=" + file;
    var obj=[];
    $.ajax({
        type: "get",
        async: false,
        url: url,
        dataType: "json",
        success: function(result)
        {
            obj=result.data;
        }
    });
    return obj;
};
function addrow(obj,modelid)
{
    var table=$("#eformlist_" + modelid);
    if(!table){return null;}
    var tbody=table.find(">tbody");
    var tfoot=table.find(">tfoot");
    if(tfoot.length>0)
    {
        var tr=tfoot[0].getElementsByTagName("tr")[0].cloneNode(true);
        var _max=tbody.children().length + 1;
        $(tr).find("input[type='radio']").each(function(i,el){
            $(this).attr("name","row_" + _max + "_" + $(this).attr("name"));	 
        });	
        tbody[0].appendChild(tr);
        tbody.find(">tr:visible").each(function(i,el){
            //$(this).find("td:eq(1)").html(i+1);
            var tdnum=$(this).find("td:eq(1)");
            if(tdnum.attr("class")=="num")
            {
                tdnum.html(i+1);
            }
        });
        var count=getobj("count_" + modelid);
        if(count)
        {
            count.value = tbody.find(">tr:visible").length;
        }
        return tr;
    }
    return null;
};
//Base64字符串转JSON对象
function Base64ToObject(values) {
    var json = decode64(values);
    return JSON.parse(json);
};
//获取同级表单元素的共同上级。
function getFillParent(elem) {
    var obj = $(elem).parents("table:first");
    var cls = obj.attr("class").toLowerCase();
    if (cls == "edataview") {
        return obj[0];
    }
    else {
        return $(elem).parents("tr:first")[0];
    }
};
//选择数据维护-原始
function selectTable(obj)
{
    var url = virtualPath + "Plugins/selectTable.aspx";
    var result = null;
    $.ajax({
        type: "post",
        contentType: 'application/json',
        async: false,
        url: url,
        data: JSON.stringify(obj),
        dataType: "json",
        success: function (data) {
            result = data;
        }
    });
    return result;
};
function simple_selectTable(datasource,name,fields,action)
{
    datasource=datasource||"";
    action=action||"write";
    var data=new Object();
    if(datasource.length > 0)
    {
        data["datasource"]= datasource;//数据源
    }
    data["name"]= name;//表名
    data["fields"]=fields;
    data["action"]=action;
    return selectTable(data);
};
function simple_selectDataCount(datasource,name,conds,group)
{
    datasource=datasource||"";
    var data=new Object();
    if(datasource.length > 0)
    {
        data["datasource"]= datasource;//数据源
    }
    data["name"]= name;//表名
    data["conds"]=conds;
    data["group"]=group;
    data["action"]="count";
    return selectTable(data);
};

//恢复选择状态
function simple_resetSelected(data)
{
    $.each(data,function(i,item)
    {
        var cond="";
        for(p in item)
        {
            if(typeof(item[p])=="function"){continue;}
            if( p.toLowerCase()=="selected"){continue;}
            cond+="["+ p +"='" +  item[p] + "']";
        }

        var tr= $("#eDataTable:first tbody tr" + cond);
        //alert(cond + ":" + tr.length);
        if(item["selected"])
        {
            tr.addClass("select");
            tr.find("[name='selitem']").attr("checked",true);
            tr.find("[name='selitem']").prop("checked",true);
        }
    });
};
//删除字段
function simple_removeFields(data,fields)
{
    var arr=fields.split(",");
    for(var i=0;i<arr.length;i++)
    {
        $.each(data,function(idx,item)
        {
            if(item[arr[i]] != "undefined")
            {
                delete item[arr[i]];
            }
        });
    }
};
//添加字段
function simple_insertFields(data,fields)
{
    var arr=fields.split(",")
    for(var i=0;i<arr.length;i++)
    {
        var field=arr[i].split(":");
        if(field.length<2) continue;
        $.each(data,function(i,item){
            item[field[0]]=field[1];
        });
    }
};
function insertField(data,field,value)
{
    $.each(data,function(i,item){
        item[field]=value;
    });
};
function simple_renameFields(data,fields)
{
    var arr=fields.split(",")
    for(var i=0;i<arr.length;i++)
    {
        var field=arr[i].split(":");
        if(field.length<2) continue;
        $.each(data,function(i,item){
            if(item[field[0]] != "undefined")
            {
                item[field[1]]=item[field[0]];
                delete item[field[0]];
            }
        });
    }
};
function renameField(data,name,newname)
{
    $.each(data,function(i,item){
        item[newname]=item[name];
        delete item[name];
    });
};
//子模块数量
function simple_model_count(modelid)
{
    var model=new subModel(modelid);
    return model.Count();
};
//子模块-最大值
function simple_model_max(modelid,id)
{
    var model=new subModel(modelid);
    return model.Max(id);
};
//子模块-最小值
function simple_model_min(modelid,id)
{
    var model=new subModel(modelid);
    return model.Min(id);
};
//子模块-平均值
function simple_model_avg(modelid,id)
{
    var model=new subModel(modelid);
    return model.Avg(id);
};
//子模块-汇总
function simple_model_sum(modelid,id)
{
    var model=new subModel(modelid);
    return model.Sum(id);
};
//子模块-清空数据
function simple_model_clear(modelid)
{
    var model=new subModel(modelid);
    return model.Clear();
};
//跳转URL
function simple_gotourl(url,title)
{
    document.location.assign(url);
};
//选择字段
function simple_selectFields(data,fields)
{
    fields="," + fields.toLowerCase() + ",";
    $.each(data,function(i,item){
        for(p in item)
        {
            if(typeof(item[p])=="function"){continue;}
            if(fields.indexOf("," + p.toLowerCase() + ",")==-1)
            {
                delete item[p];
            }
        }
    });
};
//获取所有行
function simple_getTableData(conds)
{
    var data=getAllTableRows();
    var arr=conds.split(",");
    for(var i=0;i<arr.length;i++)
    {
        ExcludeTableRow(data,arr[i]);
    }
    return data;
};
//所有选择的行
function getAllTableRows()
{
    var trs = $("#eDataTable:first tbody tr");
    var tds = $("#eDataTable:first thead tr td");   
    var result = [];
    trs.each(function (i, el) {
        var item = {};
        item["id"] = $(el).attr("erowid");
        item["selected"]= $(el).hasClass("select") ? true : false;
        for (var i = 0; i < el.attributes.length; i++) {
            var attrib = el.attributes[i];
            if(attrib.name=="class")continue;
            if(attrib.name=="erowid")continue;
            if(attrib.name=="style")continue;
            if(attrib.name=="width")continue;
            if(attrib.name=="height")continue;
            if(attrib.name=="viewdata")continue;
            if(attrib.name.indexOf("on")>-1)continue;
            item[attrib.name] = attrib.value;
        }

        for (var i = 0; i < tds.length; i++)
        {
            var txt = tds[i].innerText.replace(/\\n/g, "").trim();
            if (txt == "操作") continue;
            if (txt.length > 0)
            {
                var value = $(el).find("td:eq(" + i + ")").text()||'';
                if (isNumber(value.replace(/,/g,"")))
                {
                    item[txt] = parseFloat(value.replace(/,/g, ""));
                }
                else if (isDate(value))
                {
                    item[txt] = new Date(Date.parse(value));
                }
                else 
                {

                    item[txt] = value == null ? "" : value ;
                }
            }
        }
        result.append(item);
    });
    //alert(JSON.stringify(result));
    return result;
};
//排除不符合条件的行
function ExcludeTableRow(data, expression)
{
    var reg = new RegExp("(?<field>.*?)(>|<|=)(?<value>.*?)", "gi");
    //var regex = /^\s*(?<field>[a-zA-Z_]\w*)\s*(?<operator>[<>]=?|=|!=)\s*(?<value>.+?)\s*$/;
    var regex = /^\s*(?<field>.*?)\s*(?<operator>[<>]=?|==|=|!=)\s*(?<value>.+?)\s*$/;
    var mc =expression.match(regex);
    if (!mc) {return;};
    var field=mc.groups["field"];
    var operator=mc.groups["operator"];
    var value=mc.groups["value"];
    //alert(mc.groups["field"] + "::" + mc.groups["operator"] + "::" + mc.groups["value"]);
    for (var i = data.length - 1; i >= 0; i--) 
    {
        var type=typeof(data[i][field]);
        if(type!='undefined')
        {
            switch (operator)
            {
                case ">":
                    if(data[i][field] > parseFloat(value))
                    {
                        //data.splice(i, 1);
                        data[i]["selected"] = false;
                    }
                    break;
                case "<":
                    if(data[i][field] < parseFloat(value))
                    {
                        //data.splice(i, 1);
                        data[i]["selected"] = false;
                    }
                    break;
                case "=":
                case "==":
                    if(type=='number' && data[i][field] == parseFloat(value))
                    {
                        //data.splice(i, 1);
                        data[i]["selected"] = false;
                    }
                    else
                    {
                        if(data[i][field] == value)
                        {
                            //data.splice(i, 1);
                            data[i]["selected"] = false;
                        }
                    }
                    break;
            }
        }
    }
    //alert(data.length);
};


//获取选择行
function simple_getSelectRows(conds)
{
    var data=getAllSelectRows();
    var arr=conds.split(",");
    for(var i=0;i<arr.length;i++)
    {
        ExcludeRow(data,arr[i]);
    }
    return data;
};
//所有选择的行
function getAllSelectRows()
{
    //alert( $("#eDataTable:first thead").text());
    var trs = $("#eDataTable:first tbody tr.select");
    var tds = $("#eDataTable:first thead tr td");   
    var result = [];
    trs.each(function (i, el) {
        var item = {};
        item["id"] = $(el).attr("erowid");
        for (var i = 0; i < el.attributes.length; i++) {
            var attrib = el.attributes[i];
            if(attrib.name=="class")continue;
            if(attrib.name=="erowid")continue;
            if(attrib.name=="style")continue;
            if(attrib.name=="width")continue;
            if(attrib.name=="height")continue;
            if(attrib.name.indexOf("on")>-1)continue;
            if(attrib.name=="viewdata")continue;
            item[attrib.name] = attrib.value;
        }


        for (var i = 0; i < tds.length; i++)
        {
            var txt = tds[i].innerText.replace(/\\n/g, "").trim();
            if (txt == "操作") continue;
            if (txt.length > 0)
            {
                var value = $(el).find("td:eq(" + i + ")").text()||'';
                if (isNumber(value.replace(/,/g,"")))
                {
                    item[txt] = parseFloat(value.replace(/,/g, ""));
                }
                else if (isDate(value))
                {
                    item[txt] = new Date(Date.parse(value));
                }
                else 
                {

                    item[txt] = value == null ? "" : value ;
                }
            }
        }
        result.append(item);
    });
    //alert(JSON.stringify(result));
    return result;
};
//排除不符合条件的行
function ExcludeRow(data, expression)
{
    var reg = new RegExp("(?<field>.*?)(>|<|=)(?<value>.*?)", "gi");
    //var regex = /^\s*(?<field>[a-zA-Z_]\w*)\s*(?<operator>[<>]=?|=|!=)\s*(?<value>.+?)\s*$/;
    var regex = /^\s*(?<field>.*?)\s*(?<operator>[<>]=?|==|=|!=)\s*(?<value>.+?)\s*$/;
    var mc =expression.match(regex);
    if (!mc) {return;};
    var field=mc.groups["field"];
    var operator=mc.groups["operator"];
    var value=mc.groups["value"];
    //alert(mc.groups["field"] + "::" + mc.groups["operator"] + "::" + mc.groups["value"]);
    for (var i = data.length - 1; i >= 0; i--) 
    {
        var type=typeof(data[i][field]);
        if(type!='undefined')
        {
            switch (operator)
            {
                case ">":
                    if(data[i][field] > parseFloat(value))
                    {
                        data.splice(i, 1);
                    }
                    break;
                case "<":
                    if(data[i][field] < parseFloat(value))
                    {
                        data.splice(i, 1);
                    }
                    break;
                case "=":
                case "==":
                    if(type=='number' && data[i][field] == parseFloat(value))
                    {
                        data.splice(i, 1);
                    }
                    else
                    {
                        if(data[i][field] == value)
                        {
                            data.splice(i, 1);
                        }
                    }
                    break;
            }
        }
    }
    //alert(data.length);
};
//打开模块
function simple_openModelSingle(obj, url, title, width, height) {

    if (!width) { width = "80%"; }
    if (!height) { height = "80%"; }
    url = url.addquerystring("layout", "false");
    url = url.addquerystring("single", "true");
    var box = $(obj).parents(".eform:first");
    var id = box.attr("id").replace("_box", "");
    var idx = self.layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title: title,
        moveOut: true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area: IsMobile() ? ['95%', '95%'] : [width, height],
        scrollbar: true,
        content: [url],
        success: function (layero, index) {
            parent.arrLayerIndex.push(index);
            /*
            var iframe = layero.find('iframe');
            var doc = iframe[0].contentWindow.document;
            alert(doc.title);
            parent.layer.title('新标题。。', index);  //再改变当前层的标题
            */
        },
        cancel: function (index, layero) { parent.arrLayerIndex.pop(); },
        end: function (index) {
            reloadControl(id);
            parent.arrLayerIndex.pop();
        }
    });
};
//ajax打开其他模块添加数据
function ajaxOpenModel(url, title, width, height, _reload) {
    if (typeof (_reload) === "undefined") {
        _reload = true;
    }
    url=url.addquerystring("layout","false");
    if (!width) { width = "80%"; }
    if (!height) { height = "80%"; }
    //alert(parent==self);
    var idx = self.layer.open({
        type: 2,
        skin: 'layui-layer-rim', //加上边框
        title: title,
        moveOut: true,
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        //area : ['800px' , '520px'],
        //area: [width,height],
        area: IsMobile() ? ['95%', '95%'] : [width, height],
        //content: [url,'no'],
        scrollbar: true,
        content: [url],
        success: function (layero, index) {
            //parent.arrLayerIndex.push(index);
            arrLayerIndex.push(index);
            //alert(index);
            //alert(layero);
            //window[layero.find('iframe')[0]['name']].focus();
            var iframeWin = window[layero.find('iframe')[0]['name']];
            //alert(iframeWin.document.location.href);
            var act = iframeWin.document.location.href.getquerystring("act");
            //alert(act);
            if (act == "view") { _reload = false; }
        },
        cancel: function (index, layero) { parent.arrLayerIndex.pop(); },
        end: function (index) {
            if (uploadTempFile.length > 0) {
                removefile(uploadTempFile);
                uploadTempFile = "";
            }
            if (_reload) {
                //document.location.assign(document.location.href);
                /*
                if (parent != self) {
                    parent.reloadDoc();
                }
                else {
                    reloadDoc();
                }
                */
                // parent.reloadDoc();
                if (parent != self) {
                    reloadDoc();
                }
                else
                {
                reloadDoc();
                }
            }
            parent.arrLayerIndex.pop();
        }
    });
};


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

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

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

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

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

//新增加
function fill_checkbox(viewid,pid,objid)
{
	
    var url= virtualPath + "Plugins/getData.ashx?viewid=" + viewid + "&pid=" + pid;
    var box=$("#"+ objid + "_box");
    box.html("");
	
    $.ajax({
        type: "GET",
        async: false,
        url: url,
        dataType: "json",
        success: function(data)
        {
            //alert(JSON.stringify(data));
            $.each(data, function(i,v)
            {
                //alert(i + "::" + v["value"] + "::" + this["text"]);
                box.append('<input etype="checkbox" type="checkbox" name="' + objid + '" id="' + objid + '_' + (i+1) + '" value="'+ this["value"] +'" text="'+ this["text"] +'"><label for="' + objid + '_' + (i+1) + '">'+ this["text"] +'</label>'); 
            });

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

	$.ajax({
	    type: "GET",
	    async: false,
	    url: url,
	    dataType: "json",
	    success: function(data)
	    {
	        //alert(JSON.stringify(data));
	        $("#" + objId).get(0).length=1;
	        if(!data){return;}
	        //$("#" + ObjID).empty();
	        $.each(data, function()
	        {
	            $("#" + objId).append('<option value="' + this["value"] + '">' + this["text"] + '</option>'); 
	        });
	    }
	});
};




function form_quickview(obj, appitem, ModelID, title, width, height) //自动模块
{
    if (width.toLowerCase().indexOf("px") == -1 && width.toLowerCase().indexOf("%") == -1) { width += "px"; }
    if (height.toLowerCase().indexOf("px") == -1 && height.toLowerCase().indexOf("%") == -1) { height += "px"; }
    var tr = null;
    if (obj.tagName == "TR" && obj.getAttribute("eRowID") != null) {
        tr = obj;
    }
    else {
        //tr=getParent(obj.parentNode,"tr");
        //if(tr.getAttribute("eRowID")==null){tr=getParent(tr.parentNode,"tr"); }
        tr = $(obj).parents("tr[eRowID]:first");
        if (tr.length == 0) { return; }
        tr = tr[0];
    }

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

    var ID = tr.getAttribute("eRowID");


    var url = document.location.href;
    url = url.removequerystring("id");
    url = url.removequerystring("act");
    url = url.addquerystring("ModelID", ModelID);
    url = url.addquerystring("act", "quickview");
    url = url.addquerystring("act", "viewsub");
    url = url.addquerystring("id", ID);
    url = url.addquerystring("appitem", appitem);
    //url=url.addquerystring("ajax","true");

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

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

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

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

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



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

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

    var frmobj = areaToJson(frm);	
    //alert("11:" + frmobj.toJson());//
    //return;
    var obj=new eJson2([]);
    obj.append(frmobj);


    //alert(obj.toJson());
    //return;
	
	
	
    var model=new eJson2();
    model.append("ModelID", modelid);
    model.append("eformdata_" + modelid, obj);
    var input = getobj("eformdata_" + modelid);
	
    //alert(model.toJson());
    //return;
    input.value= model.toJson();
	
    if (typeof localStorage === 'object') {
        var act = document.location.href.getquerystring("act");
        if (act == "add") {
            var appitem = document.location.href.getquerystring("appitem");
            localStorage.removeItem(appitem);
            if (saveTime) {
                clearTimeout(saveTime);
                saveTime = null;
            }
        }
    }
    	
    frmaddoredit.setAttribute("finsh","true");
    $("#mask").show();
    setTimeout(function () { $("#mask").hide(); }, 6000);
    //alert(model.toJson());
    ///alert(obj.toJson());
    //return;
    if(ajax)
    {
	
        $.ajax({
            type: 'post',
            async: false,
            url: $("#frmaddoredit").attr("action"),			
            data: "ajax=true&" + $("#frmaddoredit").serialize(),
            dataType: "json",
            success: function(data)
            {
                $("#mask").hide();
                //alert(JSON.stringify(data));
                var json=new eJson2(data);
                if(typeof(parent.postback)=="function")
                {
                    parent.postback(data);
                    return;
                }

                if(parseBool(data.success))
                {
                    if(frmaddoredit["id"] && frmaddoredit["id"].value){frmaddoredit["id"].value = json["id"];}
                    if(frmaddoredit["ID"] && frmaddoredit["ID"].value){frmaddoredit["ID"].value = json["id"];}
                    if(frm["id"] && frm["id"].value){frm["id"].value = json["id"];}
                    if(frm["ID"] && frm["ID"].value){frm["ID"].value = json["id"];}


                    if(top!=self)//Frame打开
                    {	
                        if(parent.arrLayerIndex.length>0 || 1>-0)
                        {
                            parent.layer.msg(data.message);
                            //$(parent.document).find(".excelTable > tbody > tr:visible"); //layui-layer1
                            var index = parent.layer.getFrameIndex(window.name);	
								
                            $(parent.document).find("#layui-layer-shade" + index).hide();								
                            $(parent.document).find("#layui-layer" + index).hide();
                            //alert(index);
                            //var _count=parent.arrLayerIndex.length;
                            var _count=$(parent.document).find(".eFrameTab dt a.cur").length;
                            //alert(_count + "B");
                            //parent.document.title=_count;
                            setTimeout(function(){
                                parent.layer.close(parent.arrLayerIndex.pop());
                                //parent.document.location.assign(parent.document.location.href);
                                if(_count==1)//eframe打开再打开判断有误
                                {
                                    var curtab = $(parent.document).find(".eFrameTab dt a.cur");										
                                    var doc = $(parent.document).find(".eFrameTab dd iframe:eq(" + curtab.index() + ")").get(0).contentWindow;
                                    if (doc.treefrommode == "tree") {
                                        doc.TreeModelUpdate();
                                    }
                                    else {
                                        doc.Search();
                                    }
                                }
                                else
                                {
                                    var win=$(parent.document).find("#layui-layer-iframe" + parent.arrLayerIndex[parent.arrLayerIndex.length-1]);										
                                    if(win.length>0)
                                    {
                                        if (win.get(0).contentWindow.treefrommode == "tree") {
                                            win.get(0).contentWindow.TreeModelUpdate();
                                        }
                                        else {
                                            win.get(0).contentWindow.Search();
                                        }
                                    }
                                    else
                                    {
                                        if(parent.treefrommode=="tree") {
                                            parent.TreeModelUpdate();
                                        }
                                        else {
                                            parent.Search();
                                        }
                                    }
                                }
                                //doc.location.assign(doc.location.href);
                                //if(parent.arrLayerIndex.length==0)parent.Search();
                            },1000);
								
                        }
                    }
                    else
                    {
                        //alert(66);
                    }
					
                }
                else
                {
					
                    //alert("失败!");
                }

				
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) 
            {
                $("#mask").hide();
            }
        });
    }
    else
    {
        //var btn=getEventObject();
	
        frmaddoredit.submit();
        /*
		return;
		var loading= document.createElement("div");
		loading.className="eform_loading";
		document.body.appendChild(loading);
		*/
    }
    //return;
};




//$(document).ready(function() { }); 
//$("#id").unbind("click").click(function(e){  });
var quick_input;
var quick_show=false;
var quick_clip=null;
var quick_keys="";
function quick_search()
{
    quick_keys = quick_input.value;
    document.onkeydown=function(e)
    {
        e=window.event||e;
        var src=e.srcElement||e.target;
        var _show=$("#eSearchBox > dd").is(':visible');
        if(e.keyCode==13 && _show)
        {
            //alert("##");
            return true; 
        }
		
        if(src.tagName != "BODY"){return true;}
        if(e.keyCode == 116 ){return true;}
        //document.title=e.keyCode;
        if(e.keyCode == 8 && quick_show )
        {
            if(quick_keys.length>0)
            {
                quick_keys=quick_keys.substring(0,quick_keys.length-1);
                quick_clip.innerHTML = quick_keys;
            }			
            if (e.stopPropagation){e.stopPropagation();}else{event.cancelBubble = true;}
            if (e.preventDefault){e.preventDefault();}else{e.cancelBubble = true;}
            return false;
        }
        if(e.keyCode<65 || e.keyCode>90){return false;}
		
        return true;
    };

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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