$(document).ready(
    function()
    {
        //$("input#fd\\:format").val('xml');
        /** Override the submit action of the form **/
        $("form#gfh-form").bind("submit",
            function()
            {
                $("div#response").css('text-align', 'center');
                $("div#response").html("<p><img src=\"../image/loading.gif\" width=\"24\" height=\"24\" alt=\"loading\" /> Processing...</p>");
                /** Post the serialised form data to the form handler **/
                $.post('/form/handle', $("form#gfh-form").formSerialize(),
                    function(xml)
                    {
                        $("div#response").css('text-align', 'left');                        
                        /** Display the errors and highlight the affected inputs **/
                        if($("response", xml).attr("type") == 'failure'){
                            $(".error").removeClass("error");
                            
                            $("div#response").html('<h4>' + $("title", xml).text() + ':</h4><ul id="messages"></ul>');
                            $("field", xml).each(
                                function()
                                {   
                                    $('#' + $(this).attr("id")).addClass("error");
                                    $("ul#messages").html($("ul#messages").html() +  "<li>" + $(this).attr("message") + "</li>");
                                }
                            )
                            $("div#response").fadeIn("slow");
                        } else {
                            if($("redirect", xml).text() != ''){
                                document.location.href = $("redirect", xml).text();
                            } else if($("message", xml).text() != '') {
                                $("form#gfh-form").fadeOut("medium");
                                $("div#response").html("<h4>" + $("message", xml).text() + "</h4>");
                            } else {
                                $("div#response").html("<h4>There was a problem processing the form. Please try again</h4>");
                            }
                        }
                    });
                return false;
            }
        )
    }
);