var COMMENT_BUSY = false;

$(document).ready(function() {
    previewed = false;
    COMMENT_BUSY = false;
    $('.comment-form').submit(function() {
        ajaxComment();
        return false;
    });
});

function ajaxComment() {

    var fields = '#id_name, #id_email, #id_url, #id_comment';
    $(fields).removeClass('error');

    $('div.comment-error').remove();
    
    if (COMMENT_BUSY) {
        $('div.comment-form form').before('\
            <div class="comment-error">\
                Your comment is currently in the process of posting.\
            </div>\
        ');
        $('div.comment-error').fadeOut(2000);
        
        return false;
    }
    
    var comment = $('.comment-form').serialize();
   
    COMMENT_BUSY = true;
    
    var url = $('.comment-form').attr('action');

    // Use AJAX to post the comment.
    $.ajax({
        type: 'POST',
        url: url,
        data: comment,
        success: function(data) {
            COMMENT_BUSY = false;
            if (data.success == true) {
                commentSuccess(data);
            } else {
                commentFailure(data);
            }
        },
        error: function(data) {
            COMMENT_BUSY = false;
            
            $('div.comment-form form').unbind('submit');
            $('div.comment-form 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();
    
    $('#id_comment').val('');
    $(data['html']).hide().prependTo('#comments').slideToggle();
    $('.comment-input .thankyou').fadeIn(500);
    $('.comment-input .thankyou').fadeOut(4000);
}

function commentFailure(data) {
    for (var error in data.errors) {
        var sel = $('#id_' + error);
        sel.addClass('error');
    }
}


