$(document).ready(function(){

    $('#administrator').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": $('#administrator').data('ajax-url')
    } );

    $(document).on('click', '.remove-administrator', remove);
    $(document).on('click', '#add', add);
    $(document).on('click', '#update', update);
});

var add = function(){
    var $submitButton = $(this);
    var url = $submitButton.parents('form').attr('action');

    $submitButton.ajaxHandler(url, {
        data : $submitButton.parents('form').serialize(),
        success : function(response){
            if(response.status){
                $submitButton.parents('form')[0].reset();
                swal("Added!", response.message, "success");
            }else{
                swal("Warning!", response.message.join("\r\n"), "error");
            }
        }
    })
    return false;
};

var update = function(){

    var url = $(this).parents('form').attr('action');

    $(this).ajaxHandler(url, {
        data : $(this).parents('form').serialize(),
        success : function(response){
            if(response.status){
                swal("Updated!", response.message, "success");
            }else{
                swal("Warning!", response.message.join("\r\n"), "error");
            }
        }
    })
    return false;
};

var remove = function(){

    var $removeBtn = $(this);

    swal({
        title: "Warning",
        text: "Are you sure?",
        type: "warning",
        showCancelButton: true,
        cancelButtonText: "Cancel",
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false }, function(){

        var url = $removeBtn.attr('href');

        $removeBtn.ajaxHandler(url, {
            success : function(response){
                if(response.status){
                    $removeBtn.parents('tr').fadeOut(function(){
                        $(this).remove();
                    });
                    swal("OK!", response.message, "success");
                }else{
                    swal("Warning!", response.message, "error");
                }
            }
        })
    });

    return false;
};