$(document).ready(function(){

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


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

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


    for (var add in CKEDITOR.instances){
        CKEDITOR.instances[add].updateElement();
    }

    $submitButton.ajaxHandler(url, {
        data : $submitButton.parents('form').serialize(),
        success : function(response){
            if(response.status){
                swal({  title: "Added!",   text: response.message,   timer: 2000,   showConfirmButton: false, type: "success" });
                setTimeout(function(){
                    location.href = response.redirect;
                }, 2000);
            }else{
                swal("Warning!", response.errors.join("\r\n"), "error");
            }
        }
    })
    return false;
};

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

    for (var add in CKEDITOR.instances){
        CKEDITOR.instances[add].updateElement();
    }

    $submitButton.ajaxHandler(url, {
        data : $submitButton.parents('form').serialize(),
        success : function(response){
            if(response.status){
                swal("Updated!", response.message, "success");
            }else{
                swal("Warning!", response.errors.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;
};