var $table;
$(document).ready(function () {
    $table = $('#table');
    var wilayah_tingkat = $("#underline-title").attr("data-wilayah");
    $table.bootstrapTable({
        url: '/dashboard/json_wilayah' + (wilayah_tingkat == '1' ? '?kab=' : ''),
        height: $(window).height(),
        striped: true,
        sidePagination: 'server',
        idField: 'id',
        columns: [
            {
                field: 'nama',
                title: 'Nama Wilayah',
                sortable: true,
                halign: 'center',
                formatter: function (val, row, idx) {
                    return '<i class="fa fa-university"></i>&nbsp;' + val;
                }
            },
            {
                field: 'kode',
                title: 'Kode Region',
                sortable: true,
                align: 'left',
                halign: 'center'
            },
            {
                field: 'domain',
                title: 'Alamat SIG',
                halign: 'center',
                formatter: function (val, row, idx) {
                    return '<a href="http://' + val + '" target="_blank">http://' + val + '</a>';
                }
            }
        ],
        treeShowField: 'nama',
        parentIdField: 'pid',
        onLoadSuccess: function (data) {
            // jquery.treegrid.js
            $table.treegrid({
                initialState: 'collapsed',
                treeColumn: 0,
                expanderCollapsedClass: 'fa fa-caret-right',
                expanderExpandedClass: 'fa fa-caret-down',
                onChange: function () {
                    $table.bootstrapTable('resetWidth');
                }
            });
        }
    });

    if (wilayah_tingkat == '1') {

        $('#kab').select2({
            placeholder: "-- Pilih Kabupaten / Prov --",
            allowClear: true,
        });

        $('#kab').trigger('change');
        $('body').on('change', '#kab', function () {
            var id = $(this).val();
            $table.bootstrapTable('refresh', {
                url: '/dashboard/json_wilayah?kab=' + id
            });
        });
    }
});
