$(document).ready(function(){

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

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

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

    /* CkEditor Update */
    for (var add in CKEDITOR.instances){
        CKEDITOR.instances[add].updateElement();
    }

    $submitButton.ajaxHandler(url, {
        data : $submitButton.parents('form').serialize(),
        success : function(response){
            if(response.status){
                $submitButton.parents('form')[0].reset();
                /* Ck Editor Clear */
                CKEDITOR.instances[add].setData('');
                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');

    /* CkEditor Update */
    for (var add in CKEDITOR.instances){
        CKEDITOR.instances[add].updateElement();
    }

    $(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;
};