// Hides all but the first line of an answer until the user clicks to show it.

var lineHeight = "";
function toggleVisible(element, animate) {
	if(!element.data("shrunk")) {
		element.data("originalHtml", element.html());
		element.animate({height: lineHeight}, animate ? "slow" : 0, function () {
			element.html( getPreviewLine(element.text()) );
			element.data("shrunk", "yes");
		});

	} else {
		element.html(element.data("originalHtml"));
		element.removeData("shrunk");

		// get the expanded height
		element.css("height", "auto");
		var newHeight = element.height();
		element.css("height", lineHeight);
		// animate to that height
		element.animate({height: newHeight}, animate ? "slow" : 0);
	}
}
var dd = null;
var span = null;
// gets the line used for a collapsed answer
// str is the entire answer
// returns the longest substring (broken at words) from the beginning of str that will fit on a line
// if it isn't the whole str, an ellipsis is added to the end
function getPreviewLine(str) {
	// stupid browsers...
	// can't only add this in document ready; somehow, after document ready, the span disappears
	if($(span).parent().length == 0)
		$(dd).append(span);

	var line = str;
	for(var i = 0; i <= str.length; i++) {
		if(i == str.length || str.charAt(i) == " ") { // str[i] doesn't work in IE 7!
			var newLine = str.substring(0, i) + (i != str.length ? "&hellip;" : "");
			span.innerHTML = newLine;
			if(getLineCount(span) > 1)
				break;
			line = newLine;
		}
	}
	span.innerHTML = "";
	return line;
}
function getLineCount(inlineElement) {
	if(inlineElement.getClientRects) {
		//return inlineElement.getClientRects().length;
		// workaround for IE 6 & 7
		// see http://www.quirksmode.org/dom/tests/rectangles.html
		var rects = inlineElement.getClientRects();
		var count = 1;
		for(var i = 1; i < rects.length; i++) {
			if(rects[i].top != rects[i-1].top)
				count++;
		}
		return count;
	} else {
		var lineHeight = parseInt($(".collapsed dd").first().css("line-height"));
		return $(inlineElement).height() / lineHeight;
	}
}

$(document).ready(function() {
	if($.browser.msie && parseInt($.browser.version) < 7)
		return;

	dd = document.createElement("dd");
	span = document.createElement("span");
	$(".collapsed:last").append(dd);

	lineHeight = $(".collapsed dd").css("line-height");
	// Opera (10.5) returns 'normal' here because it calls document ready before it loads the CSS
	if(lineHeight == "normal")
		lineHeight = "1.5em";

	$(".collapsed dt").wrapInner("<a href='#'></a>");

	$(".collapsed dd").css("overflow", "hidden");
	$(".collapsed dd").each(function() { toggleVisible( $(this), false ); });

	$(".collapsed dt").click(function(){
		toggleVisible( $(this).next("dd"), true );
		return false;
	});
});

function showAll() {
	if($.browser.msie && parseInt($.browser.version) < 7)
		return;

	$(".collapsed dd").each(function() {
		if($(this).data("shrunk"))
			toggleVisible( $(this), false );
	});
}


