/* edit */
function openEdit(id){
	var obj = $("#comment_"+id);
	$.ajax({
	  type:"GET", 
	  url:"?blog/form/&"+id, 
	  success:function(data){obj.html(data); doOpenEdit(id);},
	  complete: function(){obj.find(".loader").fadeOut("slow");},
	  beforeSend: function(){obj.find(".loader").fadeIn("slow");}
	});
}

function doOpenEdit(id){
	var obj = $("#comment_"+id);
	obj.find(".loader").hide();
	obj.find(".formEdit").submit(function(){
		update(id);
		return false;
	});
	obj.find(".cancel").click(function(){
		openComment(id);
		return false;
	});
}

/* Comment */

function openComment(id){
	var obj = $("#comment_"+id);
	$.ajax({
	  type:"GET", 
	  url:"?blog/detailscomment/&"+id, 
	  success:function(data){obj.html(data); doOpenComment(id);},
	  complete: function(){obj.find(".loader").fadeOut("slow");},
	  beforeSend: function(){obj.find(".loader").fadeIn("slow");}
	});
}

function doOpenComment(id){
	var obj = $("#comment_"+id);
	obj.find(".loader").hide();
	obj.find(".edit").click(function(){
		openEdit(id);
		return false;
	});
	obj.find(".remove").click(function(){
		$(this).parent().find(".delete").fadeIn("slow");
		return false;
	});
	obj.find(".no").click(function(){
		$(this).parent().fadeOut("slow");
		return false;
	});
	obj.find(".yes").click(function(){
		remove(id);
		return false;
	});
}

/* Update */

function update(id){
	var obj = $("#comment_"+id);
	obj.find(".formEdit").ajaxSubmit({
		url:$(this).attr("action"),
		type:$(this).attr("method"),
	  success:function(data){obj.html(data); doOpenComment(id);},
	  beforeSend: function(){obj.find(".loader").fadeIn("slow");}
	});
}

/* Remove */

function remove(id){
	var obj = $("#comment_"+id);
	obj.find(".loader").fadeIn("slow");
	$.ajax({
		type:"POST",
		url:"?blog/deletecomment/",
		data:"cmt_id="+id,
	  success:function(data){obj.slideUp("slow");},
	  complete: function(){obj.find(".loader").fadeOut("slow");},
	  beforeSend: function(){obj.find(".loader").fadeIn("slow");}
	});
}

function doInsert(){
	$("#formComments .loader").fadeOut("slow");
	var id = $(".blog_comments").find("div:first").attr("id"); 
	if(id) id = id.replace("comment_", "");
	doOpenComment(id);
	$("#formComments").slideUp("slow");
}

$(document).ready(function(){
	$("#formComments").hide();
	$(".loader").hide();

	$("a[@href='#sendComment']").click(function(){
		$("#formComments").slideDown("slow");
		$(this).parent().remove();
		return false;
	});

	$(".comment").each(function(){
		var id = $(this).attr("id").replace("comment_", ""); 
		doOpenComment(id);
		return;
	});
	
	$("#insertForm").submit(function(){
		var obj = $(this);  
		obj.ajaxSubmit({
			url:$(this).attr("action"),
			type:$(this).attr("method"),
		  success:function(data){$(".blog_comments").prepend(data); doInsert();},
		  beforeSend: function(){obj.find(".loader").fadeIn("slow");}
		});
		return false;
	});
	
});

