$(function () {
    var $list = $('#shopping-list-items');

    function showError(xhr) {
        var message = (xhr.responseJSON && xhr.responseJSON.detail)
            || 'This item could not be updated. Please refresh and try again.';
        alert(message);
    }

    $list.on('submit', '.js-item-action-form', function (event) {
        event.preventDefault();
        var $form = $(this);

        $.post($form.attr('action'), $form.serialize())
            .done(function (html) {
                $form.closest('li').replaceWith(html);
            })
            .fail(showError);
    });

    $list.on('submit', '.js-item-delete-form', function (event) {
        event.preventDefault();
        var $form = $(this);
        var $item = $form.closest('li');

        $.post($form.attr('action'), $form.serialize())
            .done(function () {
                $item.remove();
            })
            .fail(showError);
    });
});
