jQuery(document).ready(function () {
    $('.btn-edit-user-address, .btn-add-user-address').on('click', function () {
        var url = $(this).data('url');
        var btn = this;

        $.ajax({
            url: url,
            method: "POST",
            dataType: "json",
            success: function (response) {
                setFlashMessages(response.flashMessages);
                $('body').append(response.data);
                $('#modal-user-address').modal('show');
                $('#modal-user-address').on('hidden.bs.modal', function (e) {
                    $('#modal-user-address').remove();
                });

                initUserAddressForm($('#modal-user-address').find('form'), btn);
            }
        });
    });
});

appUserAddress = null;
function initUserAddressForm(form, btn) {
    appUserAddress = null;

    $(form).find('button').off('click');
    $(form).find('button').on('click', function () {
        if(checkFormValidity('#'+$(form).prop('id'))) {

            $.ajax({
                url: $(form).prop('action'),
                method: "POST",
                data: $(form).serialize(),
                dataType: "json",
                success: function (response) {
                    $('#modal-user-address').modal('hide');

                    setFlashMessages(response.flashMessages);
                    if (response.status == 'error') {
                        $('body').append(response.data);
                        $('#modal-user-address').modal('show');
                        initUserAddressForm($('#modal-user-address').find('form'));
                    } else {
                        if($(btn).hasClass('btn-edit-user-address')){
                            $(btn).parents('.user-address-item').replaceWith(response.data);
                        }else{
                            $('#user-addresses').append(response.data);
                        }
                    }
                }
            });
        }
    });

    appUserAddress = new Vue({
        el: '#lc-user-address',
        delimiters: ['${', '}'],
        data() {
            return Object.assign(
                {
                    addressType:null
                }, window.addressValues);
        },
        mounted: function () {
            $(this.$el).find('select.form-control').each(function(i,select){
                setSelect2($(select));
            });
        },
        methods: {

        }
    });

}
