$(function() {

    // Target all forms with IDs starting with "contact-form"
    var forms = $('[id^=contact-form]');

    // Get the messages div (shared response container)
    
    // Loop through each form
    forms.each(function() {
        var form = $(this);
        
        var formMessages = form.find('.ajax-response');
        // Set up an event listener for each contact form
        form.submit(function(e) {
            e.preventDefault();

            // Serialize the form data
            var formData = form.serialize();

            // Submit the form using AJAX
            $.ajax({
                type: 'POST',
                url: form.attr('action'),
                data: formData
            })
            .done(function(response) {
                // Success styling
                formMessages.removeClass('error').addClass('success');
                formMessages.text(response);

                // Clear only the current form
                form.find('input, textarea').val('');
            })
            .fail(function(data) {
                // Error styling
                formMessages.removeClass('success').addClass('error');

                // Error message
                if (data.responseText !== '') {
                    formMessages.text(data.responseText);
                } else {
                    formMessages.text('Oops! An error occurred and your message could not be sent.');
                }
            });
        });
    });

});
