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

function ajaxComment(args) {
    var media = args.media;
    
    $('div.comment-error').remove();
    
    if (commentBusy) {
        $('#commentForm').before('\
            <div class="comment-error">\
                Your comment is currently in the process of posting.\
            </div>\
        ');
        $('div.comment-error').fadeOut(2000);
        
        return false;
    }
    
    comment = $('#commentForm').serialize();
   
    // Add a wait animation and note
    $('#commentForm button').after('\
        <img src="' + media + '/images/ajax-loader.gif" alt="Please wait..." class="ajaxLoader" />\
        <span id="commentWaiting" >Posting&hellip;</span>\
    ');
    
    commentBusy = true;
        
    // Use AJAX to post the comment.
    $.ajax({
        type: 'POST',
        url: $('#commentForm').attr('action'),
        data: comment,
        success: function(data) {
            commentBusy = false;
            removeWaitAnimation()
            if (data.success) {
                commentSuccess(data)
            } else {
                commentFailure(data)
            };
        },
        error: function(data) {
            commentBusy = false;
            removeWaitAnimation()
            $('#commentForm').unbind('submit');
            $('#commentForm').submit();
        },
        dataType: 'json'
    });
    
    return false;
}

// ===========================================================================
// Runs if the commment is successfully validated
// ===========================================================================

function commentSuccess(data) {
    
    // Remove all errors
    $('#commentForm .errorlist').each(function() {
        $(this).parent().prev().removeClass('error');        
        $(this).remove();
    });
    
    // Clear out form
    $('#id_name, #id_email, #id_url, #id_comment').val('');

    // Add comment to page
    $('#comments')
        .append(data['html'])
        .find('.commentContainer:last')
        .hide()
        .fadeIn('slow');

    // Increment comment count
    commentCount = $('#comments').children().length;
    if (commentCount == 1) {
        $('#comments').prev().html('<h2 class="comment-hd">1 Comment</h2>');
    } else {
        $('#comments').prev().html(commentCount + ' Comments');
    }
}

// ===========================================================================
// Process and show validation errors
// ===========================================================================

function commentFailure(data) {

    // Remove all errors
    $('#commentForm .errorlist').each(function() {
        $(this).parent().prev().removeClass('error');        
        $(this).remove();
    });

    // Add errors
    for (var error in data.errors) {
        $('#id_' + error)
            .after(data.errors[error])
            .parent()
            .prev()
            .addClass('error');
        
        // Only show errors on field focus
        $('.errorlist').hide();
        $('input, textarea').focus(function(){
            $(this).parent().find('.errorlist').show();
        }).blur(function(){
            $(this).parent().find('.errorlist').hide();
        });
    }
}

function removeWaitAnimation() {
    $('#commentForm .ajaxLoader').remove();
    $('#commentWaiting').stop().remove();
}