$(document).ready(function(){
   $("form#add_comment button").click(function(){
     $("#postcmt form").css({height:"144px"});
      $("#comment_txt").show().focus();
      if ($("#comment_txt").val()) {
        $.post("/ajax/addcomment.php",{
           comment_txt: $("#comment_txt").val(),
           cTO: $("#cTO").val(),
           action: CommentAction
           }, function(xml) {
         $("#comment_txt").empty();
         addComment(xml);
         });
        
        $("#comment_txt").val('');
        $("#comment_txt").hide();
        $("#postcmt form").css({height:"40px"});
      }
      
   
   return false;
     });

   $("#pcomment").click(function(){
     $("#postcmt form").css({height:"144px"});
     $("#comment_txt").show().focus();
  return false;  
   });

   // Edit comment
   $("a[ref=comment-edit]").bind('click', function() {
     var container = $(this).parents('.cmtdesc').find('.cmttxt');
     var comment_body = container.html();
     
     var edit_container = $("<div>").attr('id', '#editcmt').html($("#editcmt").html());
     var edit_form = edit_container.find('form');
     edit_container.find('#comment_txt').val(comment_body);
     edit_container.find('#cID').val(container.attr('ref'));
     edit_container.find('button').bind('click', function() {
       var new_text = edit_form.find('#comment_txt').val();
       
       $.post("/ajax/editcomment.php", {
         comment_txt: new_text,
         cID: edit_form.find('#cID').val(),
         action: CommentAction
       }, function(xml) {
         container.html(new_text);
         edit_container.replaceWith(container);
       });
     });

     container.replaceWith(edit_container);
     return false;
   });
   
   // Delete comment
   $("a[class='c_delete']").bind('click', function() {
     var container = $(this).parents('li');
     var comment_id = $(this).attr('rel');

     $.post("/ajax/delcomment.php", {
       type: CommentAction,
       comment: comment_id
     }, function(xml) {
       container.fadeOut(1000);
     });

     return false;
   });

   function addComment(xml) {
    if($("status",xml).text() == "1") {
      r_comment = $("comment",xml).text();
      r_photo = $("photo",xml).text();
      r_link = $("link",xml).text();
      r_name = $("name",xml).text();
      r_date = $("date",xml).text();
      $("#comments_list").prepend('<li id="added"><div class="avatar"><a href="'+r_link+'"><img src="'+r_photo+'" alt="" /></a></div><div class="cmtdesc"><div><b><a href="'+r_link+'">'+r_name+'</a></b> <em>('+r_date+')</em></div><p>'+r_comment+'</p></div></li>');
      $("#errorbox").remove();
      $("#added:first").hide();
      $("#added:first").fadeIn(1000);
    } else {
    r_error = $("error",xml).text();
    $("#comments").before('<div id="errorbox">'+r_error+'</div>');
    }
    
   }
});
   