var alterState;
var divQxsz = "divQxsz";
var strTableQxsz = "TQxsz";
var cellX, cellY;

//删除管理员信息
function delItemP0702(rowId) {
    try {
        window.top.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (strRet) {//回调函数
            if (msgBox.dlgRst.Yes == strRet) {
                var selItem = $("#" + strTableP0702).getRowData(rowId);
                var jsonCzy = '{"czydm":"' + selItem.czydm + '"}';
                var msg = ParseData(window.external.DoOptions(strTableP0702, "Delete", jsonCzy));
                if (msg.ReturnCode != 0) {
                    window.top.cihoAlert(msg.MSG, msgBox.dlgBtn.Ok);
                }
                else {
                    $("#" + strTableP0702).delRowData(rowId);
                    //设定新增按钮的位置
                    setAddBtnPostion();
                }
            }
        });
    } catch (e) { }
}

//打开操作员权限设置窗口
function openSetP0702(rowId) {
    try {
        var selItem = $("#" + strTableP0702).getRowData(rowId);
        creatDiv_ShowDlgHaveTbl(divQxsz, "操作员权限设置", true, false, strTableQxsz, 600);

        //创建对话框
        $("#" + divQxsz + "_pop_box_top").html('&nbsp;<h3 id="idH3">操作员：' + selItem.a2 + '</h3>');
        //添加按钮
        strItemHtml = "<div class=\"clr\"></div>";
        strItemHtml += "<div class=\"box_btn_width\">";
        strItemHtml += "    <div class=\"box_btn\">";
        strItemHtml += "        <div class=\"btn01\"><a id=\"btnSaveQxsz\"  style=\"cursor:pointer\">保存</a></div>";
        strItemHtml += "    </div>";
        strItemHtml += "</div>";

        $(".pop_box", "#" + divQxsz).append(strItemHtml);
        $("#" + divQxsz + "_divform").append("<table id='" + strTableQxsz + "'></table>");

        //注册事件
        $("#btnSaveQxsz", "#" + divQxsz).click(function () {
            saveMyData(divQxsz, 0, strTableQxsz);
            return false;
        });

        //获取列配置和数据
        var config = ParseData(window.external.DoOptions(strTableQxsz, 'GetTableConfig', '{}'));
        var cNames = config.colNames;
        var cModel = config.colModel;
        var jsonStr = '{"czydm":"' + selItem.czydm + '"}';
        var s = ParseData(window.external.DoOptions(strTableQxsz, 'GetList', jsonStr));

        if (s.ReturnCode != 0) {
            window.top.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        }
        var mydata = s.Records;
        createTreeGrid(strTableQxsz, cNames, cModel, mydata, "b1");

        //配置列配置
        $("#" + strTableQxsz).setColProp("a3", { formatter: 'checkbox', editoptions: { value: '1:0' },
            formatoptions: { disabled: false }
        });
        loadTreeData(strTableQxsz, mydata);
        $(":input", "#" + divQxsz).change(function () {
            $("#" + divQxsz).data("change", true);
        });
        $("#" + divQxsz).data("change", false);

        $("#" + strTableQxsz).click(function (event) {
            if ($(event.target).is(":checkbox")) {
                var nodeId = $(event.target).parent().parent().attr("id");
                var node = $("#" + strTableQxsz).getRowData(nodeId);
                var parent = $("#" + strTableQxsz).getNodeParent(node);
                var children = $("#" + strTableQxsz).getNodeChildren(node);
                if ($(event.target).is(":checked")) {                            //选中checkbox
                    for (var i = 0; i < children.length; i++) {
                        $("#" + children[i].bh + " :checkbox", this).attr("checked", true);
                    }
                    if (parent) {
                        $("#" + parent.bh + " :checkbox", this).attr("checked", true);
                    }
                } else {                                                                      //取消选中checkbox
                    for (var i = 0; i < children.length; i++) {
                        $("#" + children[i].bh + " :checkbox", this).attr("checked", false);
                    }
                    if (parent) {
                        var siblings = $("#" + strTableQxsz).getNodeChildren(parent);
                        var bool = false;
                        for (var i = 0; i < siblings.length; i++) {
                            if ($("#" + siblings[i].bh + " :checkbox", this).is(":checked")) {
                                bool = true;
                            }
                        }
                        if (!bool) { $("#" + parent.bh + " :checkbox", this).attr("checked", false); }
                    }
                }
            }
        });
        $("#" + strTableQxsz).setGridHeight(300);
        resizeGridScroll(strTableQxsz);
    } catch (e) { }
}

function closeMyDlg(dlgId, va, strTableName) {
    if (dlgId == "divEmail" || dlgId == "divEmptymm") {
        cihoDlgClose(dlgId);
        return;
    }
    var isChange = $("#" + dlgId).data("change");
    if (isChange) {
        window.parent.cihoAlert(
            msg.other.haveChange, msgBox.dlgBtn.YesNoCancel, function (strRet) {//回调函数
                if (msgBox.dlgRst.Yes == strRet) {
                    if (dlgId == "divBindPC") {
                        afterSaveClick();
                    } else {
                        var b = saveMyData(dlgId, "czydm", strTableName);
                        if (b) {
                            cihoDlgClose(dlgId);
                        }
                    }
                } else if (msgBox.dlgRst.No == strRet) {
                    cihoDlgClose(dlgId);
                }
            }
        );
    } else {
        cihoDlgClose(dlgId);
    }
}

/*
strType:新增
strType:修改
弹出窗口，设置操作类型
strType：1，新增窗口、2，修改窗口、3，修改密码
*/
function alterItemP0702(strType) {
    alterState = strType;
    $("#" + strDivP0702).empty();
    creatDiv_ShowDialog(strDivP0702, "操作员维护", false, true, strTableP0702,"400");
    var elements = createInputs(strTableP0702, strType);
    $("#" + strDivP0702 + "_divform").append(elements);

    if (strType == 2) {                                                                         //修改赋默认值
        var item = $("#" + strTableP0702).getRowData(selRowId);
        $("#a2", "#" + strDivP0702).val(item.a2);
        $("#a3", "#" + strDivP0702).val(item.a3);
        $("font.required:gt(1)").hide();
    }

    $("#a3", "#" + strDivP0702).keypress(function (event) {
        var w = String.fromCharCode(event.keyCode);
        if (!/^\w$/.test(w)) { return false; }
    }).bind("paste dragenter", function () { return false; }).css("ime-mode", "disabled").attr("maxlength", "50");

    $("#a2,#a3,#pwd,#againPwd", "#" + strDivP0702).focus(function () { this.select(); });
    $(".pop", "#" + strDivP0702).css("width", "400px");
    $("#" + strDivP0702).data("change", false);
    $("#" + strDivP0702 + "_divform :input").change(function () {
        $("#" + strDivP0702).data("change", true);
    });
}

//生成表单，修改时，添加数据
function createInputs(strTableName, strType) {
    var colNames = $("#" + strTableName).getGridParam("colNames");
    var colModel = $("#" + strTableName).getGridParam("colModel");

    var eleArray = [];
    eleArray.push('<ul id="logInfo">');
    for (var i = 0; i < colNames.length; i++) {
        if (colModel[i].index == "a2" || colModel[i].index == "a3") {
            switch (colModel[i].edittype) {
                case "text":
                    eleArray.push('<li><span>');
                    if (colModel[i].editrules && colModel[i].editrules.required)
                        eleArray.push('<font class="required" color="red">*</font>');
                    eleArray.push(colNames[i]);
                    eleArray.push('：</span>');
                    eleArray.push('<input type="');
                    eleArray.push(colModel[i].edittype);
                    eleArray.push('" name="');
                    eleArray.push(colModel[i].name);
                    eleArray.push('" id="');
                    eleArray.push(colModel[i].name);
                    eleArray.push('" maxlength="50"  onkeypress="return checkValidate(event)" onpaste="return false"/>');
                    break;
            }
            eleArray.push('</li>');
        }
    }

    //列配置中不存在的列配置
    eleArray.push('<li class="bott" style="margin:0;">只允许输入字母、数字和下划线</li>');
    eleArray.push('<li class="bott" style="margin:0;"><font class="required" color="red">*</font>密码：<input type="password" maxlength="50" name="pwd" id="pwd" onkeyup="changeLevelPwd.call(this)" onkeypress="return checkValidate(event)" onpaste="return false"/></li>');
    //eleArray.push('<li class="bott" style="text-align:left;padding-left:90px;margin:0;padding-top:0px;height: 56px; line-height: 26px;font-size:12px;"><span>密码长度6-50位，<br/>必须使用英文字母(区分大小写)、数字、特殊字符组成。<br/>密码强度为高才能保存。</span></li>');
    eleArray.push('<li class="gaga" style="text-align:left;padding-left:90px;margin:0;padding-top:10px;"><font color="gray">密码强度:<span id="level"></span></font><table class="mima"><tr><td></td><td></td><td></td></tr></table></li>');
    eleArray.push('<li><font class="required" color="red">*</font>确认密码：<input type="password" maxlength="50" name="againPwd" id="againPwd" onkeypress="return checkValidate(event)" onpaste="return false"/></li>');
    eleArray.push('</ul>');
    return eleArray.join("");
}

/*-----------------------------------------------------------------------------
//数据有效性验证：
//              必填项，是否为空；
//              数据格式是否正确。
//正常：返回true
//      否则false
//alterState:   1：新增   2：修改，3：修改密码
-----------------------------------------------------------------------------*/
function saveMyData(dlgId, nextStep, strTableName) {

    if (dlgId == "divP0702") {
        var auth = false;
        if (alterState == 1) {
            auth = authInputsAdd() && authPwd();
        } else {
            auth = authInputsAlter() && authPwd();
        }
        if (!auth) { return; }

        var a2 = trim($("#a2", "#" + dlgId).val());
        var a3 = $("#a3", "#" + dlgId).val();
        var a4 = convertSpecial($("#pwd", "#" + dlgId).val());
        var s = null;

        if (alterState == 1) {                      //执行新增
            var record = '{"a2":"' + a2 + '","a3":"' + a3 + '","a4":"' + a4 + '","zt":"True"}';
            s = ParseData(window.external.DoOptions("TCzywh", "Add", record));
        } else if (alterState == 2) {               //执行修改
            var selItem = $("#" + strTableName).getRowData(selRowId);
            var pwd = "";
            if (a4) {
                pwd = ',"a4":"' + a4 + '"';
            }
            var record = '{"czydm":"' + selItem.czydm + '","a2":"' + a2 + '","a3":"' + a3 + '"' + pwd + '}';
            s = ParseData(window.external.DoOptions("TCzywh", "Edit", record));
        }
        if (s.ReturnCode == 0) {                   //保存成功！
            var item = ParseData(record);
            item.czydm = s.czydm;
            if (alterState == 1) {//执行新增
                item.a6 = "True";
                $("#" + strTableName).addRowData(s.id, item);
            } else {
                $("#" + strTableName).setRowData(selRowId, item);
            }
            var t = window.top.objLoginInfo;
            window.top.objLoginInfo = ParseData(window.external.DoOptions("TSAMS_Menus", "GetUserInfo", "{}"));

            if (nextStep == 1) {//保存退出
                cihoDlgClose(dlgId);
            } else {//保存新增
                alterState = 1;
                $("#" + dlgId).data("change", false);
                $(":input[name]", "#" + dlgId).val("");
                changeLevelPwd.call($("#pwd")[0]);
                $("font.required:gt(1)").show();
            }

            //设定【新增】按钮的位置
            setAddBtnPostion();
            return true;
        } else {                                            //保存失败！
            window.top.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        }
    } else {
        var a1 = $("#" + strTableP0702).getRowData(selRowId).czydm;
        var a2 = $("#" + strTableName).getCol("a2");
        var a3 = $("#" + strTableName).getCol("a3");
        var jsonArr = [];
        for (var i = 0, count = a2.length; i < count; i++) {
            jsonArr.push('{"czydm":"' + a1 + '","a4":"' + a2[i] + '","a2":"' + a3[i] + '"}');
        }
        var jsonStr = '{"Records":[' + jsonArr.join(",") + ']}';
        var s = ParseData(window.external.DoOptions(strTableQxsz, 'Edit', jsonStr));
        if (s.ReturnCode == 0) {
            window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok, function () {
                $("#" + dlgId).data("change", false);
                cihoDlgClose(dlgId);
            });
        }
    }
}

//验证表单————判断是否存在重复值，验证用户输入的有效性
function authInputsAdd() {
    var czymc = $.trim($("#divP0702_divform input[name='a2']").val());
    var loginId = $.trim($("#divP0702_divform input[name='a3']").val());
    if (!czymc) {
        window.top.cihoAlert(msg.sz.czy.nameEmp, msgBox.dlgBtn.Ok);
        //操作员不能为空！
        return false;
    }
    if (!loginId) {
        //"请输入登录名！"
        window.top.cihoAlert(msg.sz.czy.logNameEmp, msgBox.dlgBtn.Ok);
        return false;
    }

    var a2 = isKeyExist(strTableP0702, "a2", czymc); //判断jqgrid中是否存在a2
    if (a2) {
        //"操作员名称重复！"
        window.top.cihoAlert(msg.sz.czy.existName, msgBox.dlgBtn.Ok);
        return false;
    }
    var a3 = isKeyExist(strTableP0702, "a3", loginId);
    if (a3) {
        //"登录名重复！"
        window.top.cihoAlert(msg.sz.czy.existLogName, msgBox.dlgBtn.Ok);
        return false;
    }
    return true;
}

function authInputsAlter() {
    var czymc = $.trim($("#divP0702_divform input[name='a2']").val());
    var loginId = $.trim($("#divP0702_divform input[name='a3']").val());
    if (!czymc) {
        window.top.cihoAlert(msg.sz.czy.nameEmp, msgBox.dlgBtn.Ok);
        //操作员不能为空！
        return false;
    }
    if (!loginId) {
        //"请输入登录名！"
        window.top.cihoAlert(msg.sz.czy.logNameEmp, msgBox.dlgBtn.Ok);
        return false;
    }
    var a2 = isJqExist("a2", czymc, true, strTableP0702); //判断jqgrid中是否存在a2
    var a3 = isJqExist("a3", loginId, true, strTableP0702);
    if (a2) {
        //"操作员名称重复！"
        window.top.cihoAlert(msg.sz.czy.existName, msgBox.dlgBtn.Ok);
        return false;
    }
    if (a3) {
        //"登录名重复！"
        window.top.cihoAlert(msg.sz.czy.existLogName, msgBox.dlgBtn.Ok);
        return false;
    }
    return true;
}

function authPwd() {
    var pwd = $("#pwd").val();
    var againPwd = $("#againPwd").val();

    if (alterState == 1 && !pwd) {          //新增时必须输入密码
        //"请输入密码！"
        window.top.cihoAlert(msg.ma.pwdEmp, msgBox.dlgBtn.Ok);
        return false;
    }

//    if (pwd && getLevelPwd(pwd) < 3) {
//        //验证密码强度
//        window.top.cihoAlert(msg.ma.pwdStrong, msgBox.dlgBtn.Ok);
//        return false;
//    }

    if (pwd === againPwd) {
        return true;
    }
    else {
        //"两次输入的密码不一致！"
        window.top.cihoAlert(msg.ma.checkMa, msgBox.dlgBtn.Ok);
        return false;
    }
}

// =================jqgrid非重复值判断==============
//添加时判断jqgrid某列中是否存在值
//colName---判断的列名
//val----------要比较的值
//bSel--------是否比较选中行的值
//tdId---------grid 的id
function isJqExist(colName, val, bSel, tbId) {
    val = val.toUpperCase();
    var exist = false;
    var cols = $("#" + tbId).getCol(colName);
    if (bSel) {
        var selId = $("#" + tbId).getGridParam("selrow");
        var selIdx = $("#" + tbId).getInd(selId) - 1;
        for (var i = 0; i < cols.length; i++) {
            if (i != selIdx) { if (val == cols[i].toUpperCase()) { exist = true; break; } }
        }
    } else {
        for (var i = 0; i < cols.length; i++) {
            if (val == cols[i].toUpperCase()) {
                exist = true; break;
            }
        }
    }
    return exist;
}

function changeLevelPwd() {
    var pwd = $(this).val();
    var level = getLevelPwd(pwd);
    var msg = ["低", "低", "中", "高"];

    if (level == -1 || level == 0) {//如果level大于0 
        $("table.mima td").css({ "background-image": "url('../../Content/Default/images/mima_02.gif')", "background-repeat": "no-repeat", "background-position": "bottom" });
    } else {
        $("table.mima td:lt(" + (level) + ")").css({ "background-image": "url('../../Content/Default/images/mima_01.gif')", "background-repeat": "no-repeat", "background-position": "bottom" });
        $("table.mima td:gt(" + (level - 1) + ")").css({ "background-image": "url('../../Content/Default/images/mima_02.gif')", "background-repeat": "no-repeat", "background-position": "bottom" });
    }
    if (level == -1) {
        $("#level").text("");
    } else {
        $("#level").text(msg[level]);
    }
}

//获取密码的强度等级
function getLevelPwd(pwd) {
    var score = 0;
    if (pwd.length <= 5) {
        score = 0;
    } else {
        if (/[0-9]/.test(pwd)) {
            score++;
        }
        if (/[a-z]/.test(pwd)) {
            score++;
        }
        if (/[A-Z]/.test(pwd)) {
            score++;
        }
        if (/\W/.test(pwd)) {
            score++;
        }
    }
    if (!pwd) {
        score = -1;
    }
    if (score >= 3) {
        return 3;
    } else {
        return score;
    }
}

//改变操作员的状态，启用、停用
function changeZt(tbId, rowId) {
    if (tbId == "TpbindPC") {
        $("#divBindPC").data("change", true);
        if (rowId) {
            var item = $("#" + tbId).getRowData(rowId);
            if (item.mxguid) {
                $("#" + tbId).setCell(rowId, "flag", 2);                               //2代表更新
            } else {
                $("#" + tbId).setCell(rowId, "flag", 1);                               //1代表新增
            }
        }
    } else {
        var selItem = $("#" + strTableP0702).getRowData(selRowId);
        if (selItem.zt == "已启用") {
            var record = '{"czydm":"' + selItem.czydm + '","zt":"False"}';
            var s = ParseData(window.external.DoOptions("TCzywh", "Edit", record));
            if (s.ReturnCode == 0) {
                $("#" + strTableP0702).setCell(selRowId, "zt", "False");
            } else {
                window.top.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
            }
        }
        else {
            var record = '{"czydm":"' + selItem.czydm + '","zt":"True"}';
            var s = ParseData(window.external.DoOptions("TCzywh", "Edit", record));
            if (s.ReturnCode == 0) {
                $("#" + strTableP0702).setCell(selRowId, "zt", "True");
            } else {
                window.top.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
            }
        }
    }
}

//格式化操作员状态
function formateZt(cellvalue) {
    if (cellvalue == "True") {
        return "已启用";
    } else {
        return "已停用";
    }
}

function createGridP0702(strTableID, colNames, colModel, funcSelectRow, funcGridComplete) {
    $("#" + strTableID).jqGrid({
        datatype: "local",
        width: 500,
        height: "100%",
        //height:"100",
        colNames: colNames,
        colModel: colModel,
        rownumbers: true,
        sortable: false,
        rownumWidth: 30,
        onSortCol: function () {
            $("div.operate").hide();
        },
        gridComplete: function () {
            //把参数中的方法加到当前事件中
            if (funcGridComplete) {
                funcGridComplete.call(this);
            }
        },
        onSelectRow: function (rowId) {
            //把参数中的方法加到当前事件中
            if (funcSelectRow) {
                var strFloatButtonHtml = funcSelectRow.call(this, rowId);
                //当参数中的方法返回值不为空时，执行创建浮动层方法
                if (strFloatButtonHtml) {
                    createFloatButton.call(this, rowId, strFloatButtonHtml,true);
                }
            }
        }
    }).parent(".ui-jqgrid-bdiv").siblings().css("width", "100%");

    //增加表头‘序号’列
    //$("table.ui-jqgrid-htable th:first", $("#gbox_" + strTableID)).text("序号");
    $("#" + strTableID).setLabel("rn", "序号");
    $("#" + strTableID).setGridHeight(100);
    //设定表格的高度
   // $("#gbox_" + strTableID).css("height", "100");
    //$("#gbox_" + strTableNameP0601).css("height", iHeight);
}

//创建操作员grid、并绑定数据源
function doData() {
    strTableP0702 = "TCzywh";
    strDivP0702 = "divP0702";
    $("#" + strTableP0702).clearGridData();
    var config = ParseData(window.external.DoOptions(strTableP0702, 'GetTableConfig', ''));
    createGridP0702(strTableP0702, config.colNames, config.colModel, function (rowId) {
        selRowId = rowId;
        var selItem = $(this).getRowData(rowId);
        var zt = "";
        if (selItem.zt == "已启用") {
            zt = "停用";
        } else {
            zt = "启用";
        }
        var item = $(this).getRowData(rowId);
        if (item.a6 == "True") {
            var strBtns = "<a onclick='alterItemP0702(2);return false;'>修改</a>-<a onclick='delItemP0702(" + rowId + ");return false;'>删除</a>-<a onclick=\"changeZt();return false;\">" + zt + "</a>-<a onclick=\"openSetP0702(" + rowId + ");return false;\">权限设置</a>-<a onclick=\"bindPC(" + rowId + ");return false;\">绑定机器</a>";
        } else {
            var strBtns = "<a onclick='alterItemP0702(2);return false;'>修改</a>";
        }
        return strBtns;
    }, function () {
        var iHeight = window.parent.document.documentElement.clientHeight - 75 - 23 - 27 - 62;
        $("#" + strTableP0702).setGridHeight(iHeight);
        //$("#gbox_" + strTableP0702).css("height", iHeight);
    });
    $("#" + strTableP0702).setGridHeight(157);
    //$("#gbox_" + strTableP0702).css("height", "157px");
    $("#" + strTableP0702).setColProp("zt", { formatter: formateZt });
    var s = ParseData(window.external.DoOptions(strTableP0702, 'GetList', '{}'));

    for (var i = 0, count = s.Records.length; i < count; i++) {
        $("#" + strTableP0702).addRowData(s.Records[i].id, s.Records[i]);
    }
}

function bindPC(rowId) {
    var item = $("#" + strTableP0702).getRowData(rowId);
    var dlgId = "divBindPC";
    var tbId = "TpbindPC";
    creatDiv_ShowDlgHaveTbl(dlgId, "绑定机器", true, false, tbId, 600);

    //创建对话框
    $("#" + dlgId + "_pop_box_top").html('&nbsp;<h3 id="idH3">操作员：' + item.a2 + '</h3><a style="cursor:pointer" title="允许该操作员在本电脑上使用" onclick="addMAC();return false; ">允许该操作员在本电脑上使用</a>');
    //添加按钮
    strItemHtml = "<div class=\"clr\"></div>";
    strItemHtml += "<div class=\"box_btn_width\">";
    strItemHtml += "    <div class=\"box_btn\">";
    strItemHtml += "        <div class=\"btn01\"><a id=\"btnSaveBindPC\"  style=\"cursor:pointer\">保存退出</a></div>";
    strItemHtml += "    </div>";
    strItemHtml += "</div>";

    $(".pop_box", "#" + dlgId).append(strItemHtml);
    $("#" + dlgId + "_divform").append("<table id='" + tbId + "'></table>");

    //注册事件
    $("#btnSaveBindPC", "#" + dlgId).click(afterSaveClick);

    //获取列配置和数据
    var config = ParseData(window.external.DoOptions('TCzywh', 'DoOthers', '{"option":"4"}'));
    var cNames = config.colNames;
    var cModel = config.colModel;

    createDjGrid(tbId, cNames, cModel);
    $("#" + tbId).setLabel("rn", "序号");
    $(".ui-jqgrid-htable th:visible:last", "#" + dlgId).html('<img id="btnAdd" style="cursor:pointer" title="添加行" src="../../Content/Default/images/edit_add.gif" onclick="addNewRow(\'' + tbId + '\');return false; "/>');

    var s = ParseData(window.external.dooptions('TCzywh', 'DoOthers', '{"option":"1","czydm":"' + item.czydm + '"}'));
    if (s.ReturnCode != 0) {
        window.top.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        return;
    }

    var mylist = s.Records;
    loadGridData(tbId, mylist);
    initGridSet(tbId, dlgId);
    $("#" + dlgId).data("rowId", rowId);
    $("#" + dlgId).data("change", false);
    $("#" + tbId).data("records", []);
    $("#" + tbId).setGridHeight(141);
    resizeGridScroll(tbId);
}

function loadGridData(tbId, mylist) {
    var count = mylist.length > 5 ? mylist.length : 5;
    for (var i = 0; i < count; i++) {
        if (mylist[i]) { $("#" + tbId).addRowData(i + 1, mylist[i]); }
        else { $("#" + tbId).addRowData(i + 1, {}); }
    }
    $("#" + tbId).data("nextNum", count + 1);
    resizeGridScroll(tbId);
}

//添加空行
function addNewRow(strTableName) {
    var nextNum = $("#" + strTableName).data("nextNum") + 1;
    $("#" + strTableName).addRowData(nextNum, {});
    $("#" + strTableName).data("nextNum", nextNum);
    resizeGridScroll(strTableName);
}

//创建单据grid
function createDjGrid(strTableName, cNames, cModel) {
    $("#" + strTableName).jqGrid({
        datatype: "local",
        autowidth: true,
        colNames: cNames,
        colModel: cModel,
        rownumbers: true,
        footerrow: false,
        sortable: false,
        rownumWidth: 30,
        cellEdit: true,
        cellsubmit: "clientArray"
    });
}

function initGridSet(tbId, dlgId) {
    $("#" + tbId).setGridParam({
        "afterEditCell": function (rowId, cellname, value, iRow, iCol) {
            cellX = iRow; cellY = iCol;
            var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
            item.attr("maxlength", "50").change(function () {
                var mxguid = $("#" + tbId).getCell(rowId, "mxguid");
                if (mxguid) {
                    $("#" + tbId).setCell(rowId, "flag", 2);
                } else {
                    $("#" + tbId).setCell(rowId, "flag", 1);
                }
                $("#" + dlgId).data("change", true);
            }).focus(function () { this.select(); });
        }
    });
    bindDelEvent(tbId);
    $("#" + tbId).setGridHeight(170);
    //$("#gbox_" + tbId).css("height", "170px");
}

function afterSaveClick() {
    if (authBindPC()) {
        saveBindPC();
    }
    return false;
}

function saveBindPC() {
    var dlgId = "divBindPC";
    var tbId = "TpbindPC";

    var ids = $("#" + tbId).getDataIDs();
    var records = $("#" + tbId).data("records");

    for (var i = 0; i < ids.length; i++) {
        var item = $("#" + tbId).getRowData(ids[i]);
        if (item.a1 || item.a2) {
            var record = '{"mxguid":"' + item.mxguid + '","a1":"' + item.a1 + '","a2":"' + item.a2.toUpperCase() + '","flag":"' + item.flag + '"}';
            records.push(record);
        } else if(item.mxguid){
            var record = '{"mxguid":"' + item.mxguid + '","flag":"3"}';
            records.push(record);
        }
    }
    var rowId = $("#" + dlgId).data("rowId");
    var czydm = $("#TCzywh").getRowData(rowId).czydm;
    var jsonStr = '{"option":"2","czydm":"' + czydm + '","Records":[' + records + ']}';

    var s = ParseData(window.external.dooptions('TCzywh', 'DoOthers', jsonStr));
    if (s.ReturnCode == 0) {
        cihoDlgClose(dlgId);
    } else {
        window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        return false;
    }
}

function authBindPC() {
    var dlgId = "divBindPC";
    var tbId = "TpbindPC";
    $("#" + tbId).saveCell(cellX, cellY);
    var ids = $("#" + tbId).getDataIDs();
    var records = $("#" + tbId).data("records");
    var errorMac = [];
    var Macs = [];
    for (var i = 0; i < ids.length; i++) {
        var item = $("#" + tbId).getRowData(ids[i]);
        if (item.a2 && /^([a-zA-Z0-9]{2}-){5}[a-zA-Z0-9]{2}$/.test(item.a2)) {
            for (var j = 0; j < Macs.length; j++) {
                if (Macs[j].toUpperCase() == item.a2.toUpperCase()) {
                    window.parent.cihoAlert("第【" + (i + 1) + "】行的MAC地址重复！", msgBox.dlgBtn.Ok);
                    return false;
                }
            }
            Macs.push(item.a2);
        }
        if (item.a2 && !/^([a-zA-Z0-9]{2}-){5}[a-zA-Z0-9]{2}$/.test(item.a2)) {
            errorMac.push(i + 1);
        }
    }
    if (errorMac.length > 0) {
        window.parent.cihoAlert("第【" + errorMac + "】行的MAC地址格式不正确！<br/>是否保存？", msgBox.dlgBtn.YesNoCancel, function (result) {
            //是
            if (result == msgBox.dlgRst.Yes) {
                saveBindPC();
            }
            //否
            else if (result == msgBox.dlgRst.No) {
                cihoDlgClose(dlgId);
            }
        });
        return false;
    }
    return true;
}

function bindDelEvent(strTableName) {
    $("#" + strTableName).delegate("tr[id]:visible", "hover", function (e) {
        if (e.type == "mouseenter") {
            var btn = '<a style="color:red;cursor:pointer;text-decoration:none" onclick="delDjRow(\'' + strTableName + '\',' + this.id + ');return false; ">删除</a>';
            $("#" + strTableName).setCell(this.id, "cz", btn);
        }
        if (e.type == "mouseleave") {
            $("#" + strTableName).setCell(this.id, "cz", " ");
        }
    });
}
//删除窗口中的grid数据
function delDjRow(strTableName, rowId) {
    $("#" + strTableName).saveCell(cellX, cellY);
    var delItem = $("#" + strTableName).getRowData(rowId);
    if (delItem.mxguid || delItem.flag) {//如果有商品代码
        window.parent.cihoAlert(
                    msg.del.delConfirm,
                     msgBox.dlgBtn.YesNo,
                     function (strRet) {
                         if (msgBox.dlgRst.Yes == strRet) {
                             $("#" + strTableName).delRowData(rowId);
                             if (delItem.mxguid) {
                                 var records = $("#" + strTableName).data("records");
                                 records.push('{"mxguid":"' + delItem.mxguid + '","flag":"3"}');
                                 $("#" + strTableName).data("records", records);
                                 changeZt(strTableName);
                             }
                         }
                     }
                );
    }
    else {
        $("#" + strTableName).delRowData(rowId);
    }
    resizeGridScroll(strTableName);
}

function addMAC() {
    var s = ParseData(window.external.dooptions('TCzywh', 'DoOthers', '{"option":"3"}'));
    if (s.ReturnCode == 0 && /^([a-zA-Z0-9]{2}-){5}[a-zA-Z0-9]{2}$/.test(s.MacAddress)) {

        var tbId = "TpbindPC";
        $("#divBindPC").data("change", true);
        $("#" + tbId).saveCell(cellX, cellY);
        var ids = $("#" + tbId).getDataIDs();
        for (var i = 0; i < ids.length; i++) {
            var item = $("#" + tbId).getRowData(ids[i]);
            if (item.a2 == s.MacAddress) {
                window.parent.cihoAlert("已存在本机器的MAC地址！", msgBox.dlgBtn.Ok);
                return false;
            }
            if (!item.a1 && !item.a2) {
                item.a1 = s.MachineName;
                item.a2 = s.MacAddress;
                item.flag = 1;
                $("#" + tbId).setRowData(ids[i], item);
                return;
            }
        }
        item.a1 = s.MachineName;
        item.a2 = s.MacAddress;
        item.flag = 1;
        var newId = $("#" + tbId).data("nextNum");
        $("#" + tbId).addRowData(newId, item);
        $("#" + tbId).data("nextNum", newId + 1);
    } else {
        window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        return false;
    }
}

//设定新增按钮的位置
function setAddBtnPostion() {
    var iTop = 27 * $("#TCzywh").jqGrid("getDataIDs").length + 80;
    $("#idDivAdd").css("top", iTop);
}


function isKeyExist(tbId, colName, val) {
    val = val.toUpperCase();
    var $tbId = $("#" + tbId);
    var ids = $tbId.getDataIDs();
    for (var i in ids) {
        var k = $tbId.getCell(ids[i], colName).toUpperCase();
        if (k == val) { return true; }
    }
}