/* ------------------------------ */
/* AJAX processing for forms      */
/* ------------------------------ */

function processForm(form) {
    "use strict";

    $(document).on('submit', form, function (e) {
        e.preventDefault();

        var formCache = $(this),
            formData = formCache.serialize(),
            action = formCache.attr('action');

        formData += '&ajax=true';

        $.ajax({
            type: 'post',
            url: action,
            data: formData,
            context: formCache,
            success: function (response) {
                response = $.parseJSON(response);
                // cache form within success
                formCache = $(this);

                // remove traces of errors so form can be updated on a subsequent submit
                formCache.find('.inputError').removeClass('inputError showError');
                formCache.find('.errorWrap').remove();
                formCache.prev('.error').remove();
                formCache.prev('.success').remove();

                // if errors add these to the dom
                if (response && response.status === 'Failed') {
                    $('#formBuilder' + response.id).html(response.html);
                } else {
                    if (response && response.status === 'bmi') {
                        formCache.find('input[type="text"]:last').val(response.bmi);
                    }

                    if (response && response.status === 'OK') {
                        if (response.redirect !== '') {
                            $(location).attr('href', response.redirect);
                        } else {
                            $('#formBuilder' + response.id).html(response.html);
                        }
                    }

                }
            }
        }); // ajax
    }); // form submit
}

$(document).ready(function() {
    // contact form
    if ($('.formBuilder').length) {
        processForm('.formBuilder');
    }
});