$(document).ready(function() {
    previewed = false;
    
    commentBusy = false;
});

function ajaxComment(args) {
    // TODO: if the media variable ends in a forward slash, remove it.
    var media = args.media;
    
    $('div.comment-error').remove();
    
    if (commentBusy) {
        $('#comment-form').before('\
            <div class="comment-error">\
                Your comment is currently in the process of posting.\
            </div>\
        ');
        $('div.comment-error').fadeOut(2000);
        
        return false;
    }
    
    comment = $('#comment-form').serialize();
   
    // Indicate that the comment is being posted
    $('.submit-post').after('\
        <div class="comment-waiting" style="display: none;">\
            <img src="' + media + '/images/ajax-wait.gif" alt="Please wait..."\
            class="ajax-loader" />\
            One moment while the comment is posted. . .\
        </div>\
    ');
    $('div.comment-waiting').fadeIn(1000);
    
    commentBusy = true;
    
    url = $('#comment-form').attr('action');
    
    // Use AJAX to post the comment.
    $.ajax({
        type: 'POST',
        url: url,
        data: comment,
        success: function(data) {
            commentBusy = false;
        
            removeWaitAnimation()
        
            if (data.success == true) {
                commentSuccess(data);
            } else {
                commentFailure(data);
            }
        },
        error: function(data) {
            commentBusy = false;
            
            removeWaitAnimation()
            
            $('#comment-form').unbind('submit');
            $('#comment-form').submit();
        },
        dataType: 'json'
    });
    
    return false;
}

function commentSuccess(data) {
    email = $('#id_email').val();
    comment = $('#id_comment').val();
    name = $('#id_name').val();
    url = $('#id_url').val();
    
    if ($('div#comments').children().length == 0) {
        $('div#comments').prepend(
            '<h2 class="comment-hd">1 comment so far:</h2>'
        )
    }
    
   $('#comment-form textarea')[0].value = "";

    $('input, textarea').not('input:hidden, input.submit-post').val('');
    
    //$('#comments h2').before(data['html']);
    //$('#comments article:last').show('slow');
    
    $('#comments h2').after('\
        <h3 class="comment-thanks">\
            Thank you for your comment. It is awaiting moderation.\
        </h3>\
    ');
    $('form, #comments h2').hide();
//    $('div.comment-thanks').fadeOut(4000);
}

function commentFailure(data) {
    $('#comment-form ul.errorlist').each(function() {
	    this.parentNode.removeChild(this);
        });

    for (var error in data.errors) {
        $('label[for=id_' + error +']').after(data.errors[error])
    }
}

function removeWaitAnimation() {
    // Remove the wait animation and message
    $('.ajax-loader').remove();
    $('div.comment-waiting').stop().remove();
}
