/**
 * @author Brandon Konkle
 */

$(document).ready(function() {
    previewed = false;
    
    $('input.submit-post').attr('disabled', '');
    
    $('div.comment-form form').submit(function() {
        $('div.comment-error').remove();
        
        name = $('#id_name').val();
        email = $('#id_email').val();
        url = $('#id_url').val();
        comment = $('#id_comment').val();
        content_type = $('#id_content_type').val();
        object_pk = $('#id_object_pk').val();
        timestamp = $('#id_timestamp').val();
        security_hash = $('#id_security_hash').val();
        honeypot = $('#id_honeypot').val();
        
        // Create an MD5 hash from the email address to use with Gravatar
        gravatar = "http://www.gravatar.com/avatar.php?default=&size=48&gravatar_id=" + $.md5(email);
        
        // Use AJAX to post the comment.
        $.post('/ajax/comment/post/', {
            name: name,
            email: email,
            url: url,
            comment: comment,
            content_type: content_type,
            object_pk: object_pk,
            timestamp: timestamp,
            security_hash: security_hash,
            honeypot: honeypot,
        }, function(data) {
            if (data.status == "success") {
                $('input.submit-post').attr('disabled', 'disabled');
                
                if ($('div#comments').children().length == 0) {
                    $('div#comments').prepend(
                        '<h2 class="comment-hd">1 comment so far:</h2>'
                    )
                }
                
                comment_html = '<div class="comment" style="display: none;">' +
                    '<div class="comment-body">' +
                    '<a href="http://www.gravatar.com"><img src="' + gravatar +
                    '" /></a><p>' + comment + '</p></div><div class="clear">' +
                    '</div><p class="posted-by">Posted by <a href="' + url +
                    '">' + name + '</a> 0 minutes ago.</p></div>'
                
                $('#comments').append(comment_html);
                $('div.comment:last').show('slow');
                
                $('.comment-form').hide()
                    .html('<p class="comment-thanks">Comment successfully' +
                          ' posted. Thank you!</p>')
                    .show(2000);
            } else {
                $('div.comment-form').before('<div class="comment-error">' +
                    data.error + '</div>');
            }
        }, "json");
        
        return false;
    });
});