var text_lines = 0;
var allarga_actived = false;
var allarga_lock = false;

function resize_area(area){
	var totalScrollHeight = parseInt($(area).attr("scrollHeight"));
	if (totalScrollHeight > area.innerHeight()) {
		$(area).animate({"height": totalScrollHeight}, 50);
	}
}

function allarga(obj, active_blur){
	if ( active_blur === undefined )
		{ active_blur = true; }
	else 
		{ active_blur= false; }
	
	if (active_blur){
		allarga_actived = true;
	}

	$(obj).keyup(function () {
		resize_area(obj);
	});
	$(obj).css({'overflow': 'hidden', 'display': 'block', 'height': '50px'});

	$(obj).bind('paste', function(e) {
		setTimeout(function() {resize_area(obj)}, 50);
	});
	
		
	if (active_blur){
		$(obj).blur(function(e){
			if ($(obj).val() == "") {
				$(obj).attr("rows", 2);
				$(obj).parents("form").hide();
				if ($(obj).parents("form").parents("li.write-comment").prevAll().length > 0){	
					$(obj).parents("form").prevAll(".write-comment-action").show();
				}
				else{
					$(obj).parents("form").parents("li.write-comment").hide();
				}
			}
			allarga_actived = false;
			$(obj).unbind("keydown");
	 	});
	}
 	
}

function displayCommentFormAndFocus(container){
	container.show();
	container.find("a.write-comment-action").hide();
	container.find("form").show();
	if ($("#is_anonymous").val() == "1"){
		container.find("form").find('input[name="name"]').focus();
	}
	else{
		container.find("form").find("textarea").focus();
	}
	if (!allarga_actived){ 
		allarga(container.find("form").find("textarea"));
	}
}

function writeCommentActionHandler(event, obj){
	event.preventDefault();
	var container = null;
	if(obj.hasClass("internal")){
		container = obj.parents("li.write-comment");
	}
	else{
		container = obj.parents(".action-links").nextAll(".comment-list").find(".write-comment");
	}
	displayCommentFormAndFocus(container);
	return false;
}

function reloadCommentList(commentList, readAllComments, isModerated){
	
	// container_id is in the form "activity_xxx", where xxx is the id of the activity
	var container_id = commentList.attr("id");
	var activityId = container_id.substring("activity_".length)
	$.ajax({
        type: "POST",
        data: ({activity_id : activityId,  read_all_comments: readAllComments}),
        url: "/stream/activity/comments",
        cache: false,
        dataType: "html",
        success: function(html, textStatus) {
			
	 		if (isModerated){
	 			$("#"+container_id).find(".moderated-note").slideDown().delay(10000).slideUp();
	 			commentList.find("textarea").val("");
	 			commentList.find("textarea").blur();
	 		}
	 		else{
	 			commentList.replaceWith(html);
	 			$(".delete-comment-form").addClass("invisible");
		 		addCommentListener(container_id);
		 		liveReadMore();
	 		}
	 		$("#dialog_loading").dialog('close');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            commentList.find(".comment-error-message").show();
        }
    });

}

function removeCommentListener(id){
	$("#"+id+ " .write-comment-action").die();
	$("#"+id+" textareak").die();
	$("#"+id+" .comment-form").die();
	$("#"+id+" .read-all-comments a").die();
	$("#"+id+" li .delete-comment-form").die();
}

function addCommentListener(id){

	var commentList = $("#" + id);

	commentList.find(".write-comment-action").bind("click",function(e){
		return writeCommentActionHandler(e, $(this));
	});
	
	commentList.find(".read-all-comments a").bind("click",function(e){
		e.preventDefault();
		reloadCommentList(commentList, 1, false);
		return false;
	});
	
	commentList.find("li .delete-comment-form").bind("submit",function(e){
		e.preventDefault();
		$("#dialog_loading").dialog("open");
		var form =  $(this);
		
		$.ajax({
				type: "POST",
				data: form.serialize(),
				url: form.attr("action"),
				cache: false,
				dataType: "html",
				success: function(html, textStatus) {
					var readAllComments = commentList.children("li.first").hasClass("read-all-comments") ? 0:1;
					reloadCommentList(commentList, readAllComments, false)
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					
				}
			});
		 return false;
	});

	commentList.find("li").hover(function(){
		$(this).find(".delete-comment-form").removeClass("invisible");
	},function(){
		$(this).find(".delete-comment-form").addClass("invisible");
	});

	commentList.find("li .delete-comment-form button").click(function(e){
		e.preventDefault();
		
		var deleteForm = $(this).parent(".delete-comment-form");
		
		var banForm = deleteForm.next(".ban-form");
		
		var del = gettext("Delete comment");
		var ban = gettext("Delete comment and block user");
		var buttons = new Object();
		buttons[del] = function() {
			deleteForm.submit();
			$("#delete_stream_dialog").dialog("destroy"); 
		}
		if (banForm.length == 1) {
			buttons[ban] =  function() {
				deleteForm.ajaxComplete(function(){
					banForm.submit();
				});
				deleteForm.submit(); 
				$("#delete_stream_dialog").dialog("destroy");
			}
		}
		$("#delete_stream_dialog").dialog({
			dialogClass: "delete_stream_dialog",
			modal:true,
			buttons: buttons,
			closeOnEscape: true,
			resizable: false,
			draggable:false
		});	
		return false;
	});
}


$(document).ready(function(){
	$("ul.comment-list").each(function(){
		addCommentListener($(this).attr("id"));
	});
	$(".delete-comment-form").addClass("invisible");
	liveWriteCommentAction();
	
	$(".comment-form").live("submit",function(e){
		e.preventDefault();
		var form =  $(this);
		if (form.hasClass("preview")) {
			commentList = $("#activity_"+form.find("#id_object_pk").val())
		} else{ 
			commentList = form.parents(".write-comment").parents(".comment-list");
		}
	
		try {
			var isModerated = (form.hasClass("preview"))? commentList.find(".write-comment").find("#is_moderated").val() : form.find("#is_moderated").val();
		} catch(err) {
			var isModerated = false;
		}
		$("#dialog_loading").dialog('open');
		$.ajax({
				type: "POST",
				data: form.serialize(),
				url: form.attr("action"),
				cache: false,
				dataType: "html",
				success: function(html, textStatus) {
					
					$("#ajax-response").html(html);
					if ($("#ajax-response").find(".error").length > 0) {
						//$("#ajax-response").dialog({modal:true, draggable:false, width:400});
						form.find(".error-message").show();
						form.find(".error").removeClass("error");
						$("#ajax-response").find(".error").each(function() {
							var field = $(this).parents('.fieldWrapper').find('label').attr("for");
							form.find("#" + field).addClass("error");
						})
						$("#dialog_loading").dialog('close');
				 	} else {
						var readAllComments = commentList.children("li.first").hasClass("read-all-comments") ? 0:1;
						reloadCommentList(commentList, readAllComments, isModerated)
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					form.find(".comment-error-message").show();
				}
			});
		 return false;
	});
	$(".comment-content textarea").live("focus", function(){
		if (!allarga_actived){ 
			allarga($(this));
		}
	});
	
})

