$(function() {
    var thanksMessage =
        'Thanks, we have received your question and will have an answer for you '+
        'soon. Please sign up for our <a href="/newsletters">weekly '+
        'newsletter</a> to find out which questions were answered this week.';

    if ($.cookie('asked')) {
        $('#qform form').hide();
        $('#qform .errors').html(thanksMessage);
        $('#qform .errors').show();
    }

    $('#qform input[type=submit]').click(function(event) {
        event.preventDefault();
        var $form = $('#qform form');
        var action = $form.attr('action') + '/ask';
        var data = {};
        data.name = $('input[name=name]', $form).val();
        data.email = $('input[name=email]', $form).val();
        data.location = $('input[name=location]', $form).val();
        data.question = $('textarea[name=question]', $form).val();
        $('#qform .errors').slideUp('fast');

        $.post(action, data, function(json) {
            var data;
            eval("data = " + json);
            if (data.success) {
                $.cookie('asked', 1, { expires: 3 });
                $('#qform form').slideUp('slow');
                $('#qform .errors').html(thanksMessage);
                $('#qform .errors').slideDown('slow');
            }
            else {
                var errors = $.map(data.errors, function(k) {
                    return '<div class="error">' + k + '</div>';
                }).join("\n");
                $('#qform .errors').html("Errors:\n" + errors);
                $('#qform .errors').slideDown('slow');
            }
        });
    });
});
