//compose name with a possible link for comments
function compose_name_site(name, site) {
    if(site.length && site.substring(0,7) != "http://") {
        site = "http://" + site;
    }
    if(!name.length) {
        name = 'Anonymous';
    }
    if(site.length) {
        var composed = '<a href="' + site + '">' + name + '</a>';
    }
    else {
        var composed = name;
    }
    return composed;
}

//sets name and link for the comment preview
function update_name_site() {
    if(!$("#commentform").find("#name").length) return;
    
    if(!$("#commentform").find("#site").length) {
        var site = "";
    } else {
        var site = $("#commentform").find("#site").val();
    }
    var name = $("#commentform").find("#name").val();
    var composed = compose_name_site(name, site);
    $("#commentbody:first").find(".commentboxnew").find("#name").html(composed);
}

//updates preview comments content
function update_content() {
    if(!$("#commentform .together textarea.comment").length) return;
    
    var textarea = $("#commentform .together textarea.comment");
    
    var text = textarea.val();
    text = comment_markdown(text);
    if(!text.length) {
        text = '-content-';
        textarea.addClass("badcomment");
    }
    else {
        textarea.removeClass("badcomment");
    }
    $("#commentbody:first").find(".commentboxnew").find("#text").html(text);
}

function validate_form() {
    var content = $("#commentform .together textarea.comment").val();
    if(!content.length) {
        return false;
    }
    else {
        return true;
    }
}

//comment header is the header on the far top of all the comments showing how many comments there are
function incr_comments_header() {
    var header = $(".commentstitle a").html();
    if(header === null) return;
    if(header.substr(0,2) == "No") {
        $("#.commentstitle a").html("One comment");
    }
    else if(header.substr(0,3) == "One") {
        $("#.commentstitle a").html("2 comments");
    }
    else {
        var num = parseInt(header.match(/[0-9]+/));
        ++num;
        $("#.commentstitle a").html(num + " comments");
    }
}

function decr_comments_header() {
    var header = $(".commentstitle a").html();
    if(header === null) return;
    
    if(header.substr(0,3) == "One") {
        $("#.commentstitle a").html("No comments yet :(");
    }
    else if(header.substr(0,2) != "No") {
        var num = parseInt(header.match(/[0-9]+/));
        --num;
        if(num > 1) {
            $("#.commentstitle a").html(num + " comments");
        }
        else {
            $("#.commentstitle a").html("One comment");
        }
    }
}

//edit functions
function update_editcomment_content() {
    var text = $(this).val();
    text = comment_markdown(text);
    if(!text.length) {
        text = '-content-';
        $(this).addClass("badcomment");
    }
    else {
        $(this).removeClass("badcomment");
    }
    $(this).parent().prev().find("#text").html(text);
}

function update_editcomment_name_site() {
    var name = $(this).parent().find("#name").val();
    var site = $(this).parent().find("#site").val();
    var composed = compose_name_site(name, site);
    $(this).parent().prev().find("#name").html(composed);
}

//badass jquery call function
function jquery_comments() {

    var date = new Date();
    var my_month = month[date.getUTCMonth()];
    var my_day = date.getDate();
    var my_year = date.getFullYear();
    var my_hours = date.getHours();
    var my_min = date.getMinutes();
    if(my_min < 10) {
        my_min = "0" + my_min.toString();
    }
    
    //append comment preview
    $("#commentbody:first").append(
		'<div class="commentboxnew" id="comment">' +
			'<span id="text">content?</span>' +
			'<div class="commentinfo">' +
				'<span id="name">:o</span> on <span id="date">' + 
					my_month + ' ' + my_day + ', ' +
					my_year + ' ' + my_hours + ':' + my_min +
					'</span>' +
			'</div>' +
		'</div>'
	);
	
    //register events for comment preview
	$("#commentform #name").change(update_name_site);
	$("#commentform #name").keydown(update_name_site);
	$("#commentform #name").keyup(update_name_site);
	
	$("#commentform #site").change(update_name_site);
	$("#commentform #site").keydown(update_name_site);
	$("#commentform #site").keyup(update_name_site);
    
    $("#commentform .together textarea.comment").change(update_content);
	$("#commentform .together textarea.comment").keydown(update_content);
	$("#commentform .together textarea.comment").keyup(update_content);
	
    //start values for comment preview
    update_name_site();
	update_content();
    
    //set reset button to use default values
    $("#commentform").find(":reset").click(function(e) {
		e.preventDefault();
		
		if($("#commentform").find("#site").length) {
			$("#commentform #site").val("");
			$("#commentform #name").val("");
			update_name_site();
		}
		
		$("#commentform .together textarea.comment").val("");
		update_content();
	});
	
    //hide the form, preview comment
	$("#commentform").hide();
	$("#commentbody:first").find(".commentboxnew").hide();
	
    //add click handler to show form and preview
	$(".addcomment a").click(function(e) {
		e.preventDefault();
		
		$("#commentform").show();
		$("#commentbody:first").find(".commentboxnew").show();
		$(".addcomment").hide();
	});
    
    //add a comment validator
    $("#commentform").find(":submit").livequery('click', function(e) {
		if(!validate_form()) {
			$("#commentform").find(".content_shouter").html(
				' You must enter a message'
			);
			
			e.preventDefault();
		}
	});
    
    //register Delete for all comments
    $("#comment .commentinfo").find("a:contains('Delete')").livequery('click', function(e) {
		e.preventDefault();
		
		$(this).parent().append(
			'<span id="loader">' +
				'<img src="'+ url_base() +'media/images/ajax-loader.gif" />' +
			'</span>'
		);
		
		var comment = $(this).parents("#comment");
		$.post(url_base() +"blog/delete_comment/" + $(this).attr("id"),
			function() {
				comment.prepend('<span id="removed">Removed comment&nbsp;&nbsp;<a href="" id="toggle">Show</a></span>');
				comment.attr("id", "removed_comment");
				
				comment.find("a:contains('Edit')").remove();
				var del = comment.find("a:contains('Delete')");
				var href = del.attr('href');
                //make the delete href point to undelete ;)
				href = href.replace(/^(.*)(delete_comment\/[0-9]+)$/g, "$1un$2");
				del.attr('href', href);
                //rename it to reflect tha subtle change
				del.html('Undelete');
				
				comment.find("#text").hide();
				comment.find(".commentinfo").hide();
				
				comment.find("#loader").remove();
			}
		);
	});
	
    //register Erase for all comments
	$(".commentinfo").find("a:contains('Erase')").livequery('click', function(e) {
		e.preventDefault();
		
		if(confirm_remove()) {
			
			$(this).parent().append(
				'<span id="loader">' +
					'<img src="'+ url_base() +'media/images/ajax-loader.gif" />' +
				'</span>'
			);
			
			var comment = $(this).parents("#comment");
			if(!comment.length) {
				comment = $(this).parents("#removed_comment");
			}
			$.post(url_base() + "admin/erase_comment/" + $(this).attr("id"),
				function() {
					comment.remove();
					decr_comments_header();
				}
			);
		}
	});
    
    //add edit button to all comments who have Delete
    //if they have they're the owner :o
    $("#comment .commentinfo").each(function() {
		var id = $(this).find("a:contains('Delete')").attr("id");
		$(this).find("a:contains('Delete')").before(
			'<a href="javascript:return false;">Edit</a> '
		);
	});
    
    //register edit event
    //show a small preview of the edit, hide the 'real' comment
    $("#comment .commentinfo").find("a:contains('Edit')").livequery('click',function(e) {
		e.preventDefault();
		var real_comment = $(this).parent().parent();
		var content = real_comment.find("#text").html();
		var form_content = reverse_comment_markdown(content);
		var composed = real_comment.find("#name");
		var name = $(composed).find("a");
		var date = real_comment.find("#date").html();
		if(name.html() == null) {
			name = composed.html();
			site = "";
		}
		else {
			name = name.html();
			site = $(composed).find("a").attr("href");
		}
		composed = composed.html();
		real_comment.after(
			'<div class="commentboxedit" id="comment">' +
				'<span id="text">' + content +
				'</span>' +
				'<div class="commentinfo">' +
					'<span id="name">' + composed + '</span> on <span id="date">' + date + '</span>' +
				'</div>' +
			'</div>' +
			'<form action="" method="post" id="editcommentform" class="commentbox">' +
				'<textarea id="text" rows="4" name="comment "class="comment">' +
				form_content.trim() + '</textarea><br /><br />' +
				'<input type="text" id="name" class="name" value="' + name.trim() + '"/>' +
				'<input type="text" id="site" class="site" value="' + site.trim() + '"/>' +
				'<a href="">Confirm</a> <a href="">Reset</a> <a href="">Cancel</a>' +
			'</form>'
		);
		real_comment.hide();
	});
    
    //register events for comment preview inside an edit
    $("#editcommentform textarea.comment").livequery('change',update_editcomment_content);
	$("#editcommentform textarea.comment").livequery('keydown',update_editcomment_content);
	$("#editcommentform textarea.comment").livequery('keyup',update_editcomment_content);
	
	$("#editcommentform #name").livequery('change',update_editcomment_name_site);
	$("#editcommentform #name").livequery('keydown',update_editcomment_name_site);
	$("#editcommentform #name").livequery('keyup',update_editcomment_name_site);
	
	$("#editcommentform #site").livequery('change',update_editcomment_name_site);
	$("#editcommentform #site").livequery('keydown',update_editcomment_name_site);
	$("#editcommentform #site").livequery('keyup',update_editcomment_name_site);
    
    //cancel the edit, remove preview and restore the original
    $("#editcommentform").find("a:contains('Cancel')").livequery('click',function(e) {
		e.preventDefault();
		var form = $(this).parent();
		var edit = form.prev();
		var real = edit.prev();
		
		form.remove();
		edit.remove();
		real.show();
	});
	
    //reset the edit - clear it
	$("#editcommentform").find("a:contains('Reset')").livequery('click',function(e) {
		e.preventDefault();
		var form = $(this).parent();
		var edit = form.prev();
		
		form.find("textarea.comment").val("");
		form.find("textarea.comment").addClass("badcomment");
		form.find("#name").val("");
		form.find("#site").val("");
		
		edit.find("#text").html("-content-");
		edit.find("#name").html("Anonymous");
	});
	
    //add confirm handler for edit, send comment, recieve and restore original with the edits
	$("#editcommentform").find("a:contains('Confirm')").livequery('click',function(e) {
		e.preventDefault();
		var form = $(this).parent();
		var edit = form.prev();
		var real = edit.prev();
		
		var content = form.find("textarea.comment").val();
		var name = form.find("#name").val();
		if(name == "") {
			name = "Anonymous";
		}
		var site = form.find("#site").val();
		
		if(!content.length) return;
		
		form.html(
			'<span id="loader">' +
				'<img src="'+ url_base() +'media/images/ajax-loader.gif" />' +
			'</span>'
		);
		
		$.post(url_base() + "blog/edit_comment/" + real.find("a:contains('Delete')").attr('id'), 
			{ 
				name: name,
				site: site,
				content: content
			},
			function(xml) {
				var composed = compose_name_site($("name",xml).text(), $("site",xml).text());
				var content = $("content",xml).text();
				
				real.find("#text").html(comment_markdown(content));
				real.find("#name").html(composed);
				
				edit.remove();
				form.remove();
				real.show();
				
			}, 'xml'
		);
	});
    
    //add Show link for deleted comments
    //hide the real comment
    $("#removed_comment #text").each(function() {
		var comment = $(this).parent();
		var removed = comment.find("#removed");
		removed.append(
			'&nbsp;&nbsp;<a href="" id="toggle">Show</a>'
		);
		
		$(this).hide();
		comment.find(".commentinfo").hide();
	});
    
    //register hide/show for deleted comments
    $("#removed_comment #removed").find("a").livequery('click', function(e) {
		e.preventDefault();
		
		var action = $(this).html();
		var comment = $(this).parent().parent();
		if(action == "Show") {
			var text = comment.find("#text");
			var info = comment.find(".commentinfo");
			
			text.show();
			info.show();
			
			$(this).html("Hide");
		}
		else if(action == "Hide") {
			var text = comment.find("#text");
			var info = comment.find(".commentinfo");
			
			text.hide();
			info.hide();
			
			$(this).html("Show");
		}
	});
	
    //register undelete action
	$("#removed_comment .commentinfo").find("a:contains('Undelete')").livequery('click',function(e) {
		e.preventDefault();
		
		$(this).parent().append(
			'<span id="loader">' +
				'<img src="'+ url_base() +'media/images/ajax-loader.gif" />' +
			'</span>'
		);
		
		var comment = $(this).parents("#removed_comment");
		$.post(url_base() + "blog/undelete_comment/" + $(this).attr("id"),
			function() {
				comment.find("#removed").remove();
				comment.attr("id", "comment");
				
				var del = comment.find("a:contains('Undelete')");
				var href = del.attr('href');
                //change undelete href to delete
				href = href.replace(/^(.*)(un)(delete_comment\/[0-9]+)$/g, "$1$3");
				del.attr('href', href);
                //set link name to reflect small change
				del.html('Delete');
				
				var id = del.attr("id");
				del.before(
					'<a href="">Edit</a> '
				);
				
				comment.find("#loader").remove();
			}
		);
	});
}
