var sections = [];
var open = [];

function open_toggle(name) {
	
	// build a new open array which doesn't contain 'name',
	// if 'open' doesn't contain 'name', add it at the end
	var newOpen = [];
	var hasName = false;
	for (i = 0; i < open.length; i ++) {
		if (open[i] == name) {
			hasName = true;
		}
		else {
			newOpen.push(open[i]);
		}
	}
	if (!hasName) {
		newOpen.push(name);
	}
	open = newOpen;
}

function in_array(n, h) {
	for (i = 0; i < h.length; i ++) {
		if (h[i] == n) {
			return true;
		}
	}
	return false;
}

function toggle_tbody(t) {
	var c = $('th:eq(0)', t).attr('class');
	if (in_array(c, open)) {
		$('tr:gt(0)', t).show();
		$('tr:eq(0)', t).removeClass('contracted');
	}
	else {
		$('tr:gt(0)', t).hide();
		$('tr:eq(0)', t).addClass('contracted');
	}
}

function _hideAll() {
	var i = 0;
	$('tbody').each(function () {
		$('tr:gt(0)', this).hide();
		$('tr:eq(0)', this).addClass('contracted');
		i++;
	});
}

function _showAll() {
	var i = 0;
	$('tbody').each(function () {
		$('tr:gt(0)', this).show();
		$('tr:eq(0)', this).removeClass('contracted');
		i++;
	});
}

$(function () {
	var i = 0;
	$('tbody').each(function () {
		if (i > 0) {
			$('tr:gt(0)', this).hide();
			$('tr:eq(0)', this).addClass('contracted');
		}
		i ++;
	});

	// determine which is the first row in the concertina
	open.push($('tbody:eq(0) th:eq(0)').attr('class'));

	// handle concertina
	$('tbody tr.section').click(function () {
		var p = this.parentNode;
		$(this).toggleClass('contracted');
		$('tr:gt(0)', p).toggle();
		open_toggle($('th', this).eq(0).attr('class'));
	});

	// page selector
	$('#specs_pagination a').click(function (e) {
		e.preventDefault();

		// handle 'on' class
		$('#specs_pagination a').removeClass('on');
		$(this).addClass('on');

		// show/hide the correct tables
		var parts = this.href.split('#');
		var href = parts[parts.length - 1];
		$('table:visible').hide();
		$('#' + href).show();

		// we now need to look at which items are open, and expand/contract
		// the rows that are/aren't
		//$('#' + href + ' tbody tr:gt(0)').hide();
		$('tbody').each(function () { toggle_tbody(this) });
	});
});
