function do_signup(f) {

    $.post(
        '/survey/process.pl',
        f.serialize(),
        function(response) {

            if ( response.success == 1 ) {

                var redirect = f.find('input[name="ajax_redirect_url"]');
                if ( redirect.length ) {
                    window.location = 
                        redirect.attr('value') 
                        + '?id=' + response.id 
                        + '&signup=1'
                }

                f.find('.signup-errors').hide()
                f.find('fieldset').hide()
                f.find('.thanks').show()
            }
            else {
                show_errors(f,'.signup-errors',response);
            }

        },
        'json'
    );
    
}



function show_errors(el, id, data) {
    var errors = [].concat(data.invalid, data.missing); // data.invalid.concat(data.missing);
    var error_text = '';
    for ( var i=0; i<errors.length;i++) {
        var e = errors[i];
        el.find('label[for="' + e + '"]').addClass('error');
    }
    el.find(id).html('Whoooooops!');
    el.find(id).show();
}


jQuery(function($) {
    // XXX: Need one for clicks one for submits via Enter. Hard to believe,
    // must be a bug somewhere.

    $('.signup-form .submit').click(function(e) {
        e.preventDefault();
        do_signup($(e.target.form));
    });

    $('.signup-form').submit(function(e) {
        e.preventDefault();
        do_signup( $(e.target) );
    });
});


