~[if#bus.pref.busnotes_teacher~(curschoolid)=hide][else#bus]
<!-- The label is rendered as real markup and read back with .text(), never written into a
     JS string literal. A translation containing an apostrophe (French renders this as
     "Notes d'autobus") would terminate the literal and take the whole script down. -->
<span id="ntBusNotesLabel" style="display:none;">~[text:nicktech.busnotes.teachers.teacherhome.Bus_Notes]</span>
<script>
(function () {
	var ADDED_FLAG = "ntBusNotesColumnAdded";

	function addBusNotesColumn() {
		var table = $j("table#teacherSectionTable");
		if (!table.length || table.data(ADDED_FLAG)) {
			return;
		}

		var headerRow = table.find("thead tr").first();
		if (!headerRow.length) {
			headerRow = table.find("tr").has("th").first();
		}
		var headerCells = headerRow.children("th");
		if (!headerCells.length) {
			return;
		}

		// ONE absolute index drives both the header cell and every body cell.
		// Computing the position separately per row - eq(-2) on the header and eq(-2)
		// on each row - drifts apart as soon as another customization adds a trailing
		// column to the rows but not the header, putting the bus icon one column to
		// the right of its own heading.
		var insertAt = headerCells.length - 1;
		var label = $j("#ntBusNotesLabel").text();

		$j("<th></th>")
			.attr({ tabindex: "0", scope: "col" })
			.addClass("center")
			.text(label)
			.insertBefore(headerCells.eq(insertAt));

		table.find("tr[sectionid]").each(function () {
			var row = $j(this);
			var icon = $j("<img>")
				.attr({ src: "/images/school_bus_icon.png", alt: label })
				.css({ width: "32px", height: "32px", border: "0" });
			var link = $j("<a></a>")
				.attr({ href: "/teachers/busnotes.html?sectionid=" + row.attr("sectionid"), title: label })
				.append(icon);
			var cell = $j("<td></td>")
				.css({ "max-width": "100px", width: "7%", "text-align": "center" })
				.append(link);

			// Same index as the header. If this row is shorter than the header for any
			// reason, append rather than silently dropping the cell.
			var anchor = row.children("td").eq(insertAt);
			if (anchor.length) {
				cell.insertBefore(anchor);
			} else {
				row.append(cell);
			}
		});

		// Spacer / message rows: widen only cells that actually carry a colspan.
		// parseInt(undefined) is NaN, and the old code wrote colspan="NaN" onto every
		// plain cell in those rows.
		table.find("tr:not([sectionid])").children("td[colspan], th[colspan]").each(function () {
			var span = parseInt($j(this).attr("colspan"), 10);
			if (!isNaN(span)) {
				$j(this).attr("colspan", span + 1);
			}
		});

		table.data(ADDED_FLAG, true);
	}

	// Deferred one tick past document-ready so other plugins that add their own columns
	// have already run - insertAt is then measured against the table's final shape.
	$j(function () {
		setTimeout(addBusNotesColumn, 0);
	});
})();
</script>
[/if#bus]
