(function(){
    var NewsIndex = function() {

        return {

            init: function() {
                var grid = new Datatable();

                grid.init({
                    src: $("#datatable-news"),
                    onSuccess: function (grid) {
                        // execute some code after table records loaded
                    },
                    onError: function (grid) {
                        // execute some code on network or other general error
                    },
                    loadingMessage: 'Loading...',
                    dataTable: {
                        "columns": [
                            { "title": "ID", "data": "id", "sortable": true },
                            { "title": "Title", "data": "title", "sortable": true },
                            { "title": "Views", "data": "views", "sortable": true },
                            { "title": "Created", "data": "created_at", "sortable": true },
                            { "title": "Actions", "data": null, "sortable": false }
                        ],
                        "columnDefs": [
                            {
                                "targets": [4],
                                "render": function ( data, type, full, meta ) {
                                    return '<a href="' + url_admin_news_edit + '/' + full.id + '" class="btn btn-sm yellow" id="edit"><i class="fa fa-pencil"></i> Edit</a><button class="btn btn-sm red" id="remove" data-id="' + full.id + '"><i class="fa fa-close"></i> Delete</button>';
                                }
                            }
                        ],
                        "pageLength": 25, // default record count per page
                        "ajax": {
                            "url": ajax_news_dt // ajax source,
                        } ,
                        "order": [
                            [0, "asc"]
                        ] // set first column as a default sort by asc
                    }
                });

                $('#datatable-news').on('click', 'tbody td:last-child button#remove', function(e){
                    e.preventDefault();

                    var self = $(this);

                    App.ajax({
                        url: ajax_news_delete,
                        type: 'POST',
                        data: {
                            id: self.data('id')
                        }
                    }, function( data ){
                        grid.getDataTable().ajax.reload();
                    });

                });
            }
        }

    }();

    $(document).ready(function() {
        NewsIndex.init();
    });

})();