$(document).ready(function() {
        $('#postlink').click(function(event) {
                $('#postform').show();
            });
        
        $('#postformCancel').click(function(event) {
                resetForm();
            });
        
        $('#postformSubmit').click(function(event) {
                submitForm();
            });
});

resetForm = function() {
    $('#postform').hide();
    $('#postformForm').clearForm();
    clearErrors();
    endProgress();
}

clearErrors = function() {
    $('#posterrors li').remove();
    $('#posterrors').hide();
}

    startProgress = function() {
        $('#postshroud').show();
        $('#postshroud_image').show();
    }

    endProgress = function() {
        $('#postshroud').hide();
        $('#postshroud_image').hide();
    }

        
submitForm = function() {
    $.ajax({
            url: $('#postformForm').attr('action'),
            type: $('#postformForm').attr('method'),
            dataType: 'xml',
            timeout: 1000,
            data: "form[from]=" + $('#postformfield_from').val() + "&form[body]=" + $('#postformfield_body').val(),
            beforeSend: function() {
                clearErrors();
                startProgress();
            },
            error: function(request, status) {
                $('ul#posterrors').append("<li>Woops. Couldn't post your message!</li>");
            },
            success: function(xml){
                var status = $(xml).find("response").attr("status");
                if (status == 'error') {
                    $(xml).find('message').each(function(){
                            $('ul#posterrors').append('<li>' + $(this).text() + '</li>');
                        });
                    $('ul#posterrors').fadeIn();
                } else if (status == 'ok') {
                    var $newLi = $('<li class="postitem"><ul class="postmeta"><li class="author">Posted by ' + $(xml).find('from').text() + '</li><li class="date">' + $(xml).find('date').text() + '</li></ul><div>' + $(xml).find('body').text() + '</div></li>');
                    $('ul#postlist').prepend($newLi);
                    resetForm();
                }
            },
            complete: function() {
                endProgress();
            }
        });
}
    
$.fn.clearForm = function() {
    return this.each(function() {
            var type = this.type, tag = this.tagName.toLowerCase();
            if (tag == 'form')
                return $(':input',this).clearForm();
            if (type == 'text' || type == 'password' || tag == 'textarea')
                this.value = '';
            else if (type == 'checkbox' || type == 'radio')
                this.checked = false;
            else if (tag == 'select')
                this.selectedIndex = -1;
        });
};

