(function(context, $) {

    var api = context.JK.Rest();

    function clearIfNeeded(input) {
        var cleared = input.data("cleared");

        if(!cleared) {
            input.val("");
            input.data("cleared", true);
        }
    }

    function postFeedbackFailure(xhr, textStatus, errorMessage) {

        var errors = JSON.parse(xhr.responseText);

        if(xhr.status == 422) {

            var $feedback = $('#feedback');

            var email = context.JK.format_errors("email", errors);
            var body = context.JK.format_errors("body", errors);

            if(email != null) {
                $('input[name=email]', $feedback).closest('div.field').addClass('error').end().after(email);
            }

            if(body != null) {
                $('textarea[name=body]', $feedback).closest('div.field').addClass('error').end().after(body);
            }
        }
        else {app.ajaxError(xhr, textStatus, errorMessage);
        }
    }

    function events() {

        var $submit = $('#contact-submit');
        var $feedback = $('#feedback');

        $feedback.submit(function(e) {

            $submit.val("SENDING...");

            var $email = $('input[name=email]', $feedback);
            var $body = $('textarea[name=body]', $feedback);

            api.postFeedback($email.val(), $body.val())
                .done(function() {
                    // remove any error fields still present
                    $('div.field', $feedback).removeClass('error');

                    $submit.val("THANKS!");
                }).
                fail(function(xhr, textStatus, errorMessage) {
                    $submit.val("SEND");
                    postFeedbackFailure(xhr, textStatus, errorMessage);
                });

            e.stopPropagation();
            return false;
        });

        $('input[name=email]', $feedback).focus(function() {
            clearIfNeeded($(this));
        });

        $('textarea[name=body]', $feedback).focus(function() {
            clearIfNeeded($(this));
        });
    }

    function initialize() {
        events();
    }

    context.JK.Corporate.contact = {};
    context.JK.Corporate.contact.initialize = initialize;

})(window, jQuery);