$(function() {
  $('#comment_link').click(function(e) {
    e.preventDefault();
    $(this).hide();
    $('#comment_form').slideDown();
    $('form#new_comment input:not(:hidden):first').focus();
  });
  function validate(elem) {
    var valid = true;
    if(elem.attr('id') == 'comment_name' && elem.val() == '') {
      elem.addClass('error');
      valid = false;      
    }
    if(elem.attr('id') == 'comment_email' && elem.val().search(/^[A-Z0-9._%-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i) == -1) {
      elem.addClass('error');
      valid = false;
    }
    if(elem.attr('id') == 'comment_body' && elem.val() == '') {
      elem.addClass('error');
      valid = false;
    }
    if(valid && elem.hasClass('error')) {
      elem.removeClass('error');
    }
    return valid;
  };
  $('#new_comment :input').blur(function() {
    validate($(this));
  });
  $('form#new_comment').submit(function(e) {
    e.preventDefault();
    $('.progress').show();
    var form = $(this);
    validate(form.find('#comment_name'));
    validate(form.find('#comment_email'));
    validate(form.find('#comment_body'));
    $.ajax({
      type: 'POST',
      url: form.attr('action'),
      data: form.serialize(),
      dataType: 'json',
      success: function(data) {
        window.scrollBy(0,-200);
        $('.progress').hide();
        var comment = data.comment;
        var name = (comment.url == '') ? comment.name : '<a href="'+comment.url+'">'+comment.name+'</a>';
        var comment_html = "<div class='avatar'><img src='"+comment.gravatar_url+"'/>"+
                           "</div><div class='meta'>"+name+" wrote "+comment.timestamp+" ago</div>"+
                           "<div class='body'>"+comment.body+"</div>";
        $('<li />').html(comment_html).appendTo('#comment_list');
        $('form#new_comment').slideUp(function() {
          $('<div />').addClass('notice').text("Thanks for the comment!").insertBefore('#comment_form');
        });
      },
      error: function(xhr, ajaxOptions, thrownError) {
        alert(xhr.responseText);
      }
    });      
  });
});