/**
 * A script to create a tree-table based on a normal html table.
 *
 * ------------------------------
 * Parent - child relations
 * ------------------------------
 * Any row in a table can be a node with children attached. The link
 * between a child and a parent can be made by adding the id of the parent
 * as a class to the child.
 * 
 * ------------------------------
 * Toggling row visibility
 * ------------------------------
 * To toggle the visibility of children rows add a link to the parent row. 
 * Set the onclick property to ToggleGroupDisplay(). The id of the row the link
 * is in will be used to find children rows.
 *
 * ------------------------------
 * Classes
 * ------------------------------
 * These four classed need to be added to the stylesheet assuming the table
 * has an id named ShopOverview:
 *
 * #ShopOverview .GroupOpen {}
 * #ShopOverview .GroupClosed {}
 * #ShopOverview .RowHidden {display: none;} 
 * #ShopOverview .RowVisible {display: table-row; _display: block;}
 *
 * .GroupOpen, .GroupClosed -- used as flags in the javascript
 * .RowHidden, .RowVisible -- used to hide/show the rows
 *
 * ------------------------------
 * Table ID
 * ------------------------------
 * Currently the table id is hard-coded to ShopOverview
 */

function rowIDFor(obj) {
	while (obj.nodeType != 1) {
		obj = obj.parentNode;
	}
	if (obj.tagName != "TR") {
		while (obj.nodeName != "TR" && obj.nodeName != "HTML") {
			obj = obj.parentNode;
		}
	} 
	
	if (obj.nodeName == "HTML") { return; }
	
	return obj.id;
}

function toggleRowsWithClass(rowClassName, shouldDisplay) {
	var t = $("ShopOverview");
	alert("here");
	var rows = document.getElementsByClassName(rowClassName, t);
	if (rows.length > 0) {
		for (i=0; i<rows.length; i++) {
			var childId = rows[i].id;
			
			// hide row
			if (!shouldDisplay) {
				Element.removeClassName($(childId), "RowVisible");
				Element.addClassName($(childId), "RowHidden");
				
				toggleRowsWithClass(childId, false);
			} else {
				Element.removeClassName($(childId), "RowHidden");
				Element.addClassName($(childId), "RowVisible");
				
				if (Element.hasClassName($(childId), "GroupOpened")) {
					toggleRowsWithClass(childId, true);
				}
			}
		}
	}
	
}

function ToggleGroupDisplay(e) {
	
	if (window.event) var obj = window.event.srcElement;
	else 
	var obj = e.target;
	
	var rowID = rowIDFor(obj);
	
	if (Element.hasClassName($(rowID), "GroupClosed")) {
		
		Element.removeClassName($(rowID), "GroupClosed");
		Element.addClassName($(rowID), "GroupOpened");
		toggleRowsWithClass(rowID, true);
	} else if (Element.hasClassName($(rowID), "GroupOpened")) {
		Element.removeClassName($(rowID), "GroupOpened");
		Element.addClassName($(rowID), "GroupClosed");
		toggleRowsWithClass(rowID, false);
	}
}
