var save_method; //for save method string
    
    var table_village;
    //Initialize Select2 Elements
    $(document).ready( function () {
        start_load()
        table_village = $('#village-list').DataTable( {
        "ajax": base_url+"/admin-units/village/list",
        "rowId" : function(a) {
            return 'village-' + a.id;
        },
        "columns": [
            { "data": "village_id" },
            { "data": "village_name" },
            { "data": "parish_name" },
            { "data": "subcounty_name" },
            { "data": "county_name" },
            { "data": "district_name" },
             {
                 "orderable":      false,
                 "data":           null,
                 render:function(data, type, row)
                 {
                     var btn='<button onclick="edit_village('+data['parish_id']+')" class="btn btn-default p-0"><i class="bi bi-pencil align-middle "></i></button> <button onclick="delete_village('+data['parish_id']+')" class="btn btn-default p-0" ><i class="bi bi-trash align-middle"></i></button>';
                     return btn;
                 }
             }
        ],
        "order": [[0, 'asc']],
        "paging":   true,
        "ordering": true,
        "info":     false,
        "filter": false,
        "searching": true,
        });
        setTimeout(function(){
         end_load()
         
     },500)
    });

      $(document).ready(function(){
 
            $('#district-select').change(function(){ 
                var id=$(this).val();
                    $.ajax({
                        url : base_url+"/admin-units/district/counties/"+id,
                        method : "POST",
                        data : {id: id},
                        async : true,
                        dataType : 'json',
                        success: function(data){
                            
                            var html = '<option>Select a county</option>';
                            var i;
                            for(i=0; i<data.length; i++){
                                html += '<option value='+data[i].county_id+'>'+data[i].county_name+'</option>';
                            }
                            $('#county-select').html(html);

                        }
                    });
                    return false;
                }); 
        });

    $(document).ready(function(){
        $('#county-select').change(function(){ 
        var id=$(this).val();
            $.ajax({
                url : base_url+"/admin-units/county/subcounties/"+id,
                method : "POST",
                data : {id: id},
                async : true,
                dataType : 'json',
                success: function(data){
                    
                    var html = '<option>Select a Subcounty</option>';
                    var i;
                    for(i=0; i<data.length; i++){
                        html += '<option value='+data[i].subcounty_id+'>'+data[i].subcounty_name+'</option>';
                    }
                    $('#subcounty-select').html(html);

                }
            });
            return false;
        }); 
    
    });

    $(document).ready(function(){
        $('#subcounty-select').change(function(){ 
        var id=$(this).val();
            $.ajax({
                url : base_url+"/admin-units/subcounty/parishes/"+id,
                method : "POST",
                data : {id: id},
                async : true,
                dataType : 'json',
                success: function(data){
                    
                    var html = '<option>Select a Parish</option>';
                    var i;
                    for(i=0; i<data.length; i++){
                        html += '<option value='+data[i].parish_id+'>'+data[i].parish_name+'</option>';
                    }
                    $('#parish-select').html(html);
                }
            });
            return false;
        }); 
    
    });

      $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    function add_village()
    {
        
        save_method = 'add';
        $('#form-village')[0].reset(); // reset form on modals

        $('#modal-village').modal('show'); // show bootstrap modal
        $('.modal-title').text('Add Village'); // Set Title to Bootstrap modal title
    }

    function save_village()
    {
      var url;
      if(save_method == 'add')
      {
          url = base_url+"village/";
      }
      else
      {
        url = base_url+"village/edit";
      }
      
       // ajax adding data to database
       var county = $('#form-village').serializeObject();
        $.ajax({
        url : url,
        type: "POST",
        data: $('#form-village').serialize(),
        dataType: "JSON",
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        success: function(data)
        {
            
            if(data.success == true)
            {
                //if success close modal and reload ajax table
                $('#modal-village').modal('hide');
                var btnHtml = '<button onclick="edit_village('+ data.village_id +')" class="btn btn-default" style="margin-right:5px;"><i class="fa fa-edit align-middle"></i></button>';
               btnHtml +=    '<button onclick="delete_village('+ data.village_id +')" class="btn btn-default" ><i class="fa fa-trash-alt align-middle"></i></button>';
               
               var rowData = [
                        data.village_id, 
                        county.village_name,
                        county.parish_name,
                        county.subcounty_name, 
                        county.county_name, 
                        county.district_id,
                        btnHtml
                        ]
               if(save_method == 'add')
                {
                    console.log(data);
                    var rowNode = table_village.row.add(rowData).draw(false).node();
                    $(rowNode).attr("id",'village-data-'+data.village_id);
                    table_village.order([0, 'asc']).draw();
                    table_village.page('last').draw(false);
               }
               else
               {
                    var tableRow = table_village.row($('#village-data-'+data.village_id).closest('tr'));
                    table_village
                            .row( tableRow )
                            .data(rowData)
                            .draw();
               }

            }
            else
            {
                var html = '<div class="alert alert-danger alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>  <h5>Error</h5>'+data.msg+'</div>';
                document.getElementById('village-ajax-result').innerHTML = html;
            }
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            var err =JSON.parse(jqXHR.responseText);
            alert('Error :'+ err.message);
        }
    });
    }

    function edit_village(id)
    {
      save_method = 'update';
      $('#form-village')[0].reset(); // reset form on modals
      
      //Ajax Load data from ajax
      $.ajax({
        url : base_url+"village/edit/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            console.log(data);
            //$('[name="district_id"]').val(data.district_id);
            $('[name="village_id"]').val(data.village_id);
            $('[name="village_name"]').val(data.village_name);
           
 
            $('#modal-village').modal('show'); // show bootstrap modal when complete loaded
            $('.modal-title').text('Edit Village'); // Set title to Bootstrap modal title
 
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });
    }

    function delete_village(id)
    {
      if(confirm('Are you sure delete this village?'))
      {
        // ajax delete data from database
          $.ajax({
            url : base_url+"village/delete/"+id,
            type: "POST",
            dataType: "JSON",
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            success: function(data)
            {
                $('#village-data-' + id).closest('tr').remove();
               
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error deleting data');
            }
        });
 
      }
    }