$(document).bind('ready', function () {
	// start with a placeholder at the end; later it should float...
	function render_all () {
	    total_raw_cost = 0.0;
	    $("tr > td:last-child").each(function(idx) {
		    if ( $(this).attr("count") ) {
			count = Number($(this).attr("count")); 
			cost = count * Number($(this).text().replace("$",""));
			// alert("this " + cost);
			total_raw_cost += cost;
			// consider *100 to avoid float issues later
		    }
		});

	    $("#raw").text("$" + total_raw_cost.toFixed(2));
	    // TODO: extract this from the input table
	    tax_rate = 0.05;
	    tax_value = tax_rate * total_raw_cost;
	    $("#tax").text("$" + tax_value.toFixed(2));
	    tip_rate = 0.18;
	    tip_value = tip_rate * total_raw_cost;
	    $("#tip").text("$" + tip_value.toFixed(2));
	    total = total_raw_cost + tax_value + tip_value;
	    $("#total").text("$" + total.toFixed(2));
	};

	// make all prices into buttons:
	$("tr > td:last-child").wrapInner(document.createElement("button"));

	// clock on row -> increment count
	$("tr > td:last-child > button").click(function () {
		// alert("clicked " + this);
		if ($(this).parent().attr("count")) {
		    old_count = Number($(this).parent().attr("count"));
		    old_count += 1;
		} else {
		    old_count = 1;
		}
		$(this).parent().attr("count", old_count);
		render_all();
	    });

	// put the total block at the end
	totaldiv = document.createElement("div");
	totaldiv.setAttribute("class", "total");
	$("table:last").after(totaldiv);
	$("div.total").append(document.createElement("dl"));
	jQuery.each(["raw", "tax", "tip", "total"], function () {
		$("div.total dl").append("<dt>" + this + '</dt><dd id="' + this + '"></dd>');
	    });

	$("div.total").after('<button id="justme">Order Only</button>');
	$("button#justme").click(function () {
		// this relies on clear_all initializing the '0' values,
		// there isn't a matcher for "attribute not present"
		// (and it would be harder to use anyway)
		$("td[count]").parent().show();
		$("td[count='0']").parent().hide();
	    });

	function clear_all() {
	    $("tr > td:last-child").attr("count", "0");
	}
	$("div.total").after('<button id="clear">Clear</button>');
	$("button#clear").click(function () {
		clear_all();
		render_all();
	    });

	// make each th (header) clickable to hide
	$("th").toggle(
		       function () {
			   $(this).parent().parent().children().not($(this).parent()).hide();
		       },
		       function () {
			   $(this).parent().parent().children().not($(this).parent()).show();
		       }
		       );
	// also default to hiding them
	$("th").each(
		       function () {
			   $(this).parent().parent().children().not($(this).parent()).hide();
		       }
		     );

	clear_all();
	render_all();
})
