$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';
$(function () {
    /*判断浏览器是否是ie8  解决ie8弹出框居中问题*/
    var ua = navigator.userAgent.toLowerCase();
    if (window.ActiveXObject) {
        if (ua.match(/msie ([\d.]+)/)[1] == '8.0') {
            $(window).resize(function () {
                $.each($(".moveModel > .modal-dialog"), function () {
                    $(this).css("left", ($(window).width() - $(this).width()) / 2);
                    $(this).css("top", "40px");
                })
            })
        }
    }
    //下拉框  含搜索的
    $('.chosen-select').chosen({allow_single_deselect: true, no_results_text: "无匹配数据", width: "100%"});
    //resize the chosen on window resize
    $(window).on('resize.chosen', function () {
        $.each($('.chosen-select'), function (index, obj) {
            $(obj).next().css("width", 0);
            var w = $(obj).parent().width();
            $(obj).next().css("width", w);
        });
        $.each($('.chosen-single-select'), function (index, obj) {
            $(obj).next().css("width", 0);
            var e = $(obj).parent().width();
            $(obj).next().css("width", e);
        })
    }).trigger('resize.chosen');

    //绑定回车键
    $(document).keydown(function(event){
        if(event.keyCode==13){
            $("#search").trigger("click");
        }
    });

    $("#SaveBtn").click(function () {
        var msg = valiteData(".tableA");
        if (msg && msg != 'undefined')
            tipInfo(msg);
        else
            valiteValue();

    });

    /*表单校验 end*/
    $(".hideButton").click(function () {
        $("#tableForm").find(".form-control").tooltip("destroy").removeAttr("aria-invalid").removeAttr("title").removeAttr("style");
        $('#tableForm')[0].reset();
        $(".Pop").hide();
        $("#valiteType").val("");
        $("#dm").removeAttr("disabled");
    });
    //生成表格
    BdcFyTableConfigGrid();
    fillTable();

    //新增
    $("#addData").click(function () {
        $("#limitTablePop,#modal-backdrop-pop").show();
        $(window).trigger('resize.chosen');
        $("#title").html("新增配置");
        $("#valiteType").val("add");
        $('#tableForm')[0].reset();
        $("#dm").removeAttr("disabled");
    });
    //删除
    $("#delData").click(function () {
        var ids = $('#limit-table-grid-table').jqGrid('getGridParam', 'selarrrow');
        delRule(ids, configUrl + "/bdcZdFy/delBdcZdFy", "limit-table-grid-table");
    });
    //修改
    $("#updateData").click(function () {
        var ids = $('#limit-table-grid-table').jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0) {
            tipInfo("请选择一条数据!");
            return;
        }
        if (ids.length > 1) {
            tipInfo("只能同时修改一条数据!");
            return;
        }
        var data = $('#limit-table-grid-table').getRowData(ids);
        $("#title").html("修改配置");
        $("#dm").attr("disabled", "disabled");
        $("#dm").val(data.DM);
        $("#fymc").val(data.MC);
        $("#valiteType").val("update");
        //字段赋值
        $("#limitTablePop,#modal-backdrop-pop").show();
        $(window).trigger('resize.chosen');
    });

    $("#search").click(function () {
        var fymc = $("#fymcSearch").val();
        $("#limit-table-grid-table").jqGrid('setGridParam', {
            datatype: 'json',
            page: 1,
            url: configUrl + "/bdcZdFy/getBdcZdFyPagesJson?mc=" + encodeURI(fymc)
        }).trigger("reloadGrid"); //重新载入
    });
    //resize to fit page size
    $(window).on('resize.jqGrid', function () {
        var contentWidth;
        if ($("#limitTableContent").width() > 0) {
            contentWidth = $("#limitTableContent").width();
        }
        $("#limit-table-grid-table").jqGrid('setGridWidth', contentWidth);
    });

    //获取列表数据
    function fillTable() {
        $("#limit-table-grid-table").jqGrid('setGridParam', {
            datatype: 'json',
            page: 1,
            url: configUrl + "/bdcZdFy/getBdcZdFyPagesJson",
            postData: {}
        }).trigger("reloadGrid"); //重新载入
    }
})


//删除判断是否没有选择数据
function delRule(ids, url, gridId) {
    if (ids.length == 0) {
        tipInfo("请选择一条数据!");
        return;
    }
    showConfirmDialog("删除", "是否删除？", "del", "'" + ids + "','" + url + "','" + gridId + "'", "", "");
}

//打开table页面
function toLimitTable() {
    $("#limitTablePop").hide();
    $("#myModal").show();
}

//提示
function tipInfo(msg) {
    bootbox.dialog({
        message: "<h3><b>" + msg + "</b></h3>",
        title: "",
        buttons: {
            main: {
                label: "关闭",
                className: "btn-primary",
            }
        }
    });
}

//auth表格初始化
function BdcFyTableConfigGrid() {
    var grid_selector = "#limit-table-grid-table";
    var pager_selector = "#limit-table-grid-pager";
    //resize on sidebar collapse/expand
    var parent_column = $(grid_selector).closest('[class*="col-"]');
    $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
        if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
            $(grid_selector).jqGrid('setGridWidth', parent_column.width());
        }
    });
    jQuery(grid_selector).jqGrid({
        datatype: "local",
        height: 'auto',
        jsonReader: {id: 'DM'},
        colNames: ['法院代码', '法院名称','dm'],
        colModel: [
            {name: 'DM', index: 'DM', width: '50%', sortable: false},
            {name: 'MC', index: 'MC', width: '50%', sortable: false},
            {name: 'DM', index: 'DM', width: '0%', sortable: false, hidden: true}
        ],
        viewrecords: true,
        rowNum: 5,
        rowList: [5, 10, 15],
        pagerpos: "left",
        pager: pager_selector,
        altRows: false,
        multiboxonly: true,
        multiselect: true,
        loadComplete: function () {
            var table = this;
            setTimeout(function () {
                updatePagerIcons(table);
                enableTooltips(table);
                $(grid_selector).jqGrid('setGridWidth', $("#limitTableContent").width());
            }, 0);
        },
        ondblClickRow: function (rowid) {
        },
        caption: "",
        autowidth: true
    });

}

//replace icons with FontAwesome icons like above
function updatePagerIcons(table) {
    var replacement =
        {
            'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
            'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
            'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
            'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
        };
    $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
        var icon = $(this);
        var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

        if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
    })
}

function enableTooltips(table) {
    $('.navtable .ui-pg-button').tooltip({container: 'body'});
    $(table).find('.ui-pg-div').tooltip({container: 'body'});
}

function valiteValue() {
    if (isNaN($("#dm").val())) {
        tipInfo("法院代码请输入数字！");
        return false;
    }

    $.ajax({
        url: configUrl + '/bdcZdFy/valite?valiteType=' + $("#valiteType").val(),
        type: 'get',
        data: {dm: $("#dm").val(), mc: $("#fymc").val()},
        success: function (data) {
            if (data && data != 'undefiend') {
                alert(data);
            } else {
                saveorupdate();
            }
        },
        error: function (data) {
        }
    });
}

function saveorupdate() {
    $.ajax({
        url: configUrl + '/bdcZdFy/saveBdcZdFy?dm=' + encodeURI($("#dm").val()) + "&mc=" + encodeURI($("#fymc").val()) ,
        type: 'post',
        dataType: 'json',
        success: function (data) {
            alert(data.result);
            $("#limitTablePop,#modal-backdrop-pop").hide();
            //此处可以添加对查询数据的合法验证
            $("#limit-table-grid-table").jqGrid('setGridParam', {
                datatype: 'json',
                page: 1
            }).trigger("reloadGrid"); //重新载入
            $('#tableForm')[0].reset();
        },
        error: function (data) {
            alert("保存失败");
            $("#limitTablePop,#modal-backdrop-pop").hide();
            $('#tableForm')[0].reset();
        }
    });
}

function del(ids, url, gridId) {
    $.getJSON(url + "?ids=" + encodeURIComponent(ids), {}, function (jsonData) {
        setTimeout($.unblockUI, 10);
        alert(jsonData.result);
        $('#' + gridId).trigger("reloadGrid");
    })
}