(function($) {

    "use strict";

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    // Contact form
    let contactForm = $('#contactForm'),
        sendMessageBtn = $('#sendMessage');

    if (contactForm.length) {
        sendMessageBtn.on('click', function(e) {
            e.preventDefault();
            let formData = contactForm.serializeArray(),
                sendUrl = getConfig.baseURL + '/contact-us/send';
            sendMessageBtn.prop('disabled', true);
            $.ajax({
                url: sendUrl,
                type: "POST",
                data: formData,
                dataType: 'json',
                beforeSend: function() {
                    JsLoadingOverlay.show();
                },
            }).done(function(response) {
                JsLoadingOverlay.hide();
                sendMessageBtn.prop('disabled', false);
                if ($.isEmptyObject(response.error)) {
                    contactForm.trigger("reset");
                    if (window.grecaptcha) {
                        grecaptcha.reset();
                    }
                    toastr.success(response.success);
                } else {
                    toastr.error(response.error);
                }
            }).fail(function(jqXHR, ajaxOptions, thrownError) {
                JsLoadingOverlay.hide();
                toastr.error(thrownError);
            });
        });
    }

    let downloadLink = $('.download-file');
    if (downloadLink.length) {
        downloadLink.on('click', function(e) {
            e.preventDefault();
            let id = $(this).data('id'),
                requestDownloadLink = getConfig.baseURL + '/' + id + '/download/create';
            $.ajax({
                url: requestDownloadLink,
                type: "POST",
                dataType: 'json',
                success: function(response) {
                    if ($.isEmptyObject(response.error)) {
                        window.location = response.download_link;
                    } else {
                        toastr.error(response.error);
                    }
                }
            });
        });
    }

})(jQuery);