﻿$(function(){
	var postpage = (location.href.indexOf("sample") > -1 ? "sample" : "space");
	$("#comments a.edit").click(function(){
		var cancel = $(this).parent().parent().next().find("img");
		if (cancel.length > 0) {
			cancel.click();
		} else {
			var cid = $(this).parents(".comment").attr("id").substring(1);
			$("<div><form method='post' action=''><textarea name='edit' class='textinput'>" + $(this).parent().siblings("div").html().replace(/<br\s*\/?>/gi, "\n") + "</textarea><br /><img src='images/buttons/new/cancel.png' /> <input type='image' src='images/buttons/new/post.png' /></form></div>").hide().insertAfter($(this).parent().parent()).slideDown(function() {
				var me = this;
				setTimeout(function(){
					$("textarea", me)[0].focus();
				}, 100);
			}).children().submit(function(){
				var me = $(this).parent().slideUp();
				var text = $("textarea", me).val();
				if ($.trim(text).length > 0 ) {
					$.ajax({type: "POST", url: postpage + ".aspx?id=" + cid + "&a=editcomment", data: {edit: text}, dataType: "json", success: function(data){
						if (data.success) {
							me.prev().find("div").html(data.edit);
							var dates = me.prev().find("span");
							var i = dates.html().indexOf("Updated");
							if (i > -1)
								dates.html(dates.html().substring(0, i + 8) + data.updated);
							else
								dates.append(" - Updated " + data.updated);
							me.remove();
						} else {
							alert(data.error);
							me.slideDown();
						}
					}});
				} else
					alert("The update may not be empty.");
				return false;
			}).find("img").click(function(){
				$(this).parent().parent().slideUp(function(){
					$(this).remove();
				});
			});
		}
		return false;
	});
	$("#comments a.delete").click(function(){
		if (confirm("Are you sure you want to delete this comment?")) {
			var me = $(this).parent().slideUp();
			var cid = me.attr("id").substring(1);
			$.getJSON(postpage + ".aspx", {id: cid, a: "deletecomment"}, function(data){
				if (data.success) {
					if (me.siblings(".comment").length == 0)
						me.parent().after("<p id='nonefound'>No comments yet...</p>").remove();
					else
						me.remove();
				} else {
					alert(data.error);
					me.slideDown();
				}
			});
		}
		return false;
	});
	$("#htmlok a").click(function(){
		openWindow(this.href, {width: 300, height: 350});
		return false;
	});
	$("form").submit(function(){
		if ($.trim($("form textarea").val()).length == 0) {
			alert("The comment may not be empty.");
			return false;
		}
	});
});