/*
Send an HTTP DELETE request
<a data-href="posts/2"
data-method="delete"
data-token="{{csrf_token()}}"
data-confirm=0
data-submit-confirm-text="{{ __('Vuoi eliminare ?') }}"
data-submit-confirm-button="{{ __('Ok') }}"
>
Or, request confirmation in the process
data-confirm=1
*/

$(document).ready(function() {

    var laravel = {
        initialize: function() {
            this.methodLinks = $('a[data-method]');
            this.registerEvents();
        },

        registerEvents: function() {
            this.methodLinks.on('click', this.handleMethod);
        },

        handleMethod: function(e) {
            // e.preventDefault();

            var link = $(this);
            var httpMethod = link.data('method').toUpperCase();
            var form;

            // If the data-method attribute is not PUT or DELETE,
            // then we don't know what to do. Just ignore.
            if ( $.inArray(httpMethod, ['PUT', 'DELETE']) === - 1 ) {
                return;
            }

            form = laravel.createForm(link);
            form.submit();
        },

        createForm: function(link) {
            var form =
                $('<form>', {
                    'id'    : 'frmDelete',
                    'method': 'POST',
                    'action': link.data('href'),
                    'onsubmit':link.data('confirm')===1?'bbConfirmOnSubmit(event)':''
                });

            var token =
                $('<input>', {
                    'type': 'hidden',
                    'name': '_token',
                    'value': link.data('token')
                });

            var hiddenInput =
                $('<input>', {
                    'name': '_method',
                    'type': 'hidden',
                    'value': link.data('method')
                });

            var submitButton =
                $('<button>', {
                    'type': 'submit',
                    'data-submit-confirm-text':link.data('submitConfirmText'),
                    'data-submit-confirm-button':link.data('submitConfirmButton')
                });

            return form.append(token, hiddenInput, submitButton)
                .appendTo('body');
        }
    };

    laravel.initialize();

});