$(document).ready(function(){

  // Submit step redirection form and add to the listing
  $("#add-comment div.submit input[type=submit]").live("click", function() {
    var button = $(this);
    var form = $(this).parents("form");
    var ajax_url = form.attr("action");
    
    var comments_section = $("div#comments-section");
    var comments_container = $("div#comments", comments_section);
   
    button.attr("value", "One moment please ...");
    button.attr("disabled", "disabled");
   
    function reset_form(){
      form.clear_form();
      button.attr("value", "Add comment");
      button.attr("disabled", "");            
    }
   
    $.jsonRequest({
      url: ajax_url,
      data: form.serialize(),
      success: function(jsonResponse){
        if(comments_container.size() > 0) {
          $(jsonResponse.html).hide().appendTo(comments_container).slideDown("slow", reset_form);
        }
        else {
          comments_section.prepend(jsonResponse.html);
          reset_form();
        }
      },
      error: function(jsonResponse){
        alert("Oops! You forgot to type something into the comment field. Please type your comment and try again");
        reset_form();
      }
    });


    return false; // Stop the form from submitting
  });
  
});
