// highlight and fade background on named anchors
// requires jquery.color.js http://plugins.jquery.com/project/color
function highlight(elemId) {
	var elem = $(elemId);
	elem.css("backgroundColor", "#ffffee"); // hack for Safari
	elem.animate( {
		backgroundColor : '#fff3c0'
	}, 0);
	setTimeout(function() {
		$(elemId).animate( {
			backgroundColor : "#ffffee"
		}, 4000);
	}, 1000);
}

function showVotes(node, self_votes) {
	var parent = node.parent().parent();
	if (self_votes == 0) {
		parent.children("span.vote-none").show();
		parent.children("span.vote-up").hide();
		parent.children("span.vote-down").hide();
	} else if (self_votes > 0) {
		parent.children("span.vote-none").hide();
		parent.children("span.vote-up").show();
		parent.children("span.vote-down").hide();
	} else if (self_votes < 0) {
		parent.children("span.vote-none").hide();
		parent.children("span.vote-up").hide();
		parent.children("span.vote-down").show();
	}
}

function vote(node, votes) {
	var type = node.parent().siblings("input[name=type]").val();
	var old_self_votes = parseInt(node.parent().siblings("input[name=self_votes]").val());
	showVotes(node, votes);
	$
			.ajax( {
				type : "POST",
				url : baseURL + "/post/vote/" + type,
				data : {
					id : node.parent().siblings("input[name=id]").val(),
					votes : votes,
					ajax : true
				},
				success : function(data) {
					var new_self_votes = parseInt(data);
					showVotes(node, new_self_votes);
				},
				error : function(req, status, error) {
					showVotes(node, old_self_votes);
					if (req.status == 403
							&& (req.statusText == "AUTH_REQUIRED" || req
									.getResponseHeader("FH-Error-Code") == "AUTH_REQUIRED")) {
						alert("Error: " + req.status + " " + req.statusText);
					} else {
						alert("Error: " + req.status + " " + req.statusText);
					}
				}
			});

}

$(document).ready(function() {
	$("a[rel~=external]").each(function() {
		this.target = "_blank";
	}).addClass("external");

	$("button.edit").click(function() {
		var div = $(this).parents("div.edit-buttons");
		div.hide();
		div.siblings("div.readonly").hide();
		div.siblings("div.editable").show();
	});

	$("button.cancel-edit").click(function() {
		var div = $(this).parents("div.editable");
		div.hide();
		div.siblings("div.edit-buttons").show();
		div.siblings("div.readonly").show();
	});

	if (document.location.hash) {
		highlight(document.location.hash);
	}

	$("button.vote-yes").click(function() {
		vote($(this), 1);
	});
	$("button.vote-no").click(function() {
		vote($(this), -1);
	});
	$("button.vote-undo").click(function() {
		vote($(this), 0);
	});

});

