/**
 *  Hijax a form. Relies on the presents of a 'messages' div in layout
 */
$.fn.ded_hijax = function(extra_callback) {
    this.submit(function(e) {
        e.preventDefault();
        // Don't know why, but this works here and not in ded_form_errors
        $('img.error_icon').remove();
        var frm = this;
        $('#messages').empty();
        $.ajax({
            url: this.action + '.js',
            dataType: 'json',
            data: $(this).serialize(),
            type: 'POST',
            success: function(json) {
                var msg_class = 'error';
                if(json.success) {
                    msg_class = 'message';
                    if(extra_callback) extra_callback(json);
                } else {
                    $.each(json.errors, function(i, e) {
                        $(frm.elements[i]).after('<span class="error">' + e + '</span>');
                    });
                    $(frm).ded_form_errors();
                }
                $('#messages').html('<div class="flashdata ' + msg_class + '">' + json.message + '</div>');                    
            }
        });
    });    
};

/**
 *  Automatically tweak display of form errors
 *  Looks for <span class="error">'s and neatens them up a bit!
 */
$.fn.ded_form_errors = function() {
    $('img.error_icon').remove();
    this.find('span.error').each(function(){
        $(this).hide().after(jQuery('<img>', {
            src: '/img/icons/error.png',
            'class': 'error_icon',
            title: $(this).text(),
            style: 'padding-left: 5px;'
        })).remove();
    });
};
