// JavaScript Document
// <script language="JavaScript1.2" type="text/JavaScript">
// Copyright (c)2005 Rewritten Software.  http://www.rewrittensoftware.com
// This script is supplied "as is" witrhout any form of warranty. Rewritten Software 
// shall not be liable for any loss or damage to person or property as a result of using this script.
// Use this script at your own risk!
// You are licensed to use this script free of charge for commercial or non-commercial use providing you do not remove 
// the copyright notice or disclaimer.

// Define the array that will contain the mapping table for ids to images.
var treeViewIconMap = new Array();
var treeViewIconList = new Array( treeViewIconMap );

function treeViewToggle(item) {
	var startHeight = TREE_VIEW_CONTAINER.scrollHeight;
	var idx = -1;
	for( i = 0; i < treeViewIconList.length; i++ ) {
		if( treeViewIconList[i][0] == item ) {
			idx = i;
			break;
		}
	}
	
	if( idx < 0 )
		alert( "Could not find key in Icon List." );
		   
	var div=document.getElementById("treeView"+item);
	var visible=(div.style.display!="none");
	var key=document.getElementById("P"+item);

	TREE_VIEW_SELECTED = div;
	
	// Check if the item clicked has any children. If it does not then remove the plus/minus icon
	// and replace it with a transaparent gif.
	var removeIcon = div.hasChildNodes() == false;
	var hasContent = div.hasChildNodes() == true;
	
	if( key != null ) {
		if( !removeIcon ) {
			if (visible) {
		 		div.style.display="none";
		 		key.innerHTML="<img src='" + IMG_EMPTY_IMAGE + "' hspace='0' vspace='0' border='0'>";
			} else {
		  		div.style.display="block";
			}
		} else {
			if (! visible) {
				doAjaxCategoryTreePopulate(div.getAttribute("urlAjax"));
			}
		}
	}

	// treeViewToggle the icon for the tree item
	key=document.getElementById("I"+item);
	if( key != null ) {
		if (visible) {
	 		div.style.display="none";
	 		key.innerHTML="<img src='"+treeViewIconList[idx][1]+"' hspace='0' vspace='0' border='0'>";
		} else {
	  		div.style.display="block";
			key.innerHTML="<img src='"+treeViewIconList[idx][2]+"' hspace='0' vspace='0' border='0'>";
		}
	}
	
	var endHeight = TREE_VIEW_CONTAINER.scrollHeight;
}

function treeViewExpand() {
   divs=document.getElementsByTagName("DIV");
   for (i=0;i<divs.length;i++) {
	 divs[i].style.display="block";
	 key=document.getElementById("x" + divs[i].id);
	 key.innerHTML="<img src='img/textfolder.gif' hspace='0' vspace='0' border='0'>";
   }
}

function treeViewCollapse() {
   divs=document.getElementsByTagName("DIV");
   for (i=0;i<divs.length;i++) {
	 divs[i].style.display="none";
	 key=document.getElementById("x" + divs[i].id);
	 key.innerHTML="<img src='img/folder.gif' hspace='0' vspace='0' border='0'>";
   }
}

function treeViewAddImage( parent, imgFileName )
{
	img=document.createElement("IMG");
	img.setAttribute( "src", imgFileName );
	img.setAttribute( "hspace", 0 );
	img.setAttribute( "vspace", 0 );
	img.setAttribute( "border", 0 );
	parent.appendChild(img);
}

function treeViewCreateUniqueTagName( seed )
{
	var tagName = seed;
	var attempt = 0;
	
	if( tagName == "" || tagName == null )
		tagName = "x";

	while( document.getElementById(tagName) != null )
	{
		tagName = "x" + tagName;
		if( attempt++ > 50 )
		{
			alert( "Cannot create unique tag name. Giving up. \nTag = " + tagName );
			break;
		}
	}
	
	return tagName;
}

// Creates a new package under a parent. 
// Returns a TABLE tag to place child elements under.
function CreateTreeViewItem( parent, nodeId, nodeName, url, urlAjax, bolded, childsCount, itemsCount ) {
	var uniqueId = treeViewCreateUniqueTagName( nodeId );
	for( i=0; i < treeViewIconList.length; i++ )
		if( treeViewIconList[i][0] == uniqueId ) {
			alert( "Non unique ID in Element Map. '" + uniqueId + "'" );
			// return;
		}
	
	treeViewIconList[treeViewIconList.length] = new Array( uniqueId, TREE_VIEW_IMAGE_PLUS, TREE_VIEW_IMAGE_MINUS, TREE_VIEW_IMAGE_NEUTRAL );

	table = document.createElement("TABLE");
	if (parent != null) parent.appendChild( table );
	
	if (childsCount == null) childsCount = 0;
	if (itemsCount == "") itemsCount = null;

	table.setAttribute( "border", 0 );
	table.setAttribute( "cellpadding", 1 );
	table.setAttribute( "cellspacing", 1 );
		
	tablebody = document.createElement("TBODY");
	table.appendChild(tablebody);
		
   	row=document.createElement("TR");
	tablebody.appendChild( row );

	// Create the cell for the plus and minus.
	cell=document.createElement("TD");
	row.appendChild(cell);
	
		// Create the hyperlink for plus/minus the cell
	a=document.createElement("A");
	cell.appendChild( a );
	a.setAttribute( "id", "P"+uniqueId );
	a.setAttribute( "href", "javascript:treeViewToggle(\""+uniqueId+"\");" );
	treeViewAddImage( a, IMG_EMPTY_IMAGE );
	
	// Create the cell for the image.
	cell=document.createElement("TD");
	row.appendChild(cell);
		
	// Add the image to the cell
	if (childsCount == 0) {
		treeViewAddImage( cell, TREE_VIEW_IMAGE_NEUTRAL );
	} else {
		// all the event to call when the icon is clicked.
		a=document.createElement("A");
		a.setAttribute( "id", "I"+uniqueId );
		a.setAttribute( "href", "javascript:treeViewToggle(\""+uniqueId+"\");" );
		cell.appendChild(a);
		treeViewAddImage( a, TREE_VIEW_IMAGE_PLUS );
	}

	// Create the cell for the text
	cell=document.createElement("TD");
	cell.noWrap = true;
	a=document.createElement("A");
	a.setAttribute( "id", uniqueId );
	cell.appendChild( a );
	if( url != null ) {
		a.setAttribute( "href", url );
		
		//text=document.createTextNode( nodeName );
		if (itemsCount != null) nodeName += " [" + TREE_VIEW_LABEL_ITEMS + ": " + itemsCount + "]";
		if (bolded) {
			b=document.createElement("B");
			//b.appendChild(text);
			b.innerHTML = nodeName;
			a.appendChild(b);
		} else {
			//a.appendChild(text);
			a.innerHTML = nodeName;
		}
	} else {
		text=document.createTextNode( nodeName );
		cell.appendChild(text);
	}
	row.appendChild(cell);

	return treeViewCreateDiv( parent, uniqueId, urlAjax );;
}

// Creates a new DIV tag and appends it to parent if parent is not null.
// Returns the new DIV tag.
function treeViewCreateDiv( parent, id, urlAjax ) {
	div=document.createElement("DIV");
	if( parent != null ) parent.appendChild( div );
		
	div.setAttribute( "id", "treeView"+id );
	div.setAttribute( "urlAjax" , urlAjax);
	div.style.display  = "none";
 	div.style.marginLeft = "1em";
	
	return div;
}

// This is the root of the tree. It must be supplied as the parent for anything at the top level of the tree.
var treeViewRootCell = null;
var TREE_VIEW_CONTAINER		= null;
var TREE_VIEW_IMAGE_PLUS	= null;
var TREE_VIEW_IMAGE_MINUS	= null;
var TREE_VIEW_IMAGE_NEUTRAL	= null;
var TREE_VIEW_SELECTED		= null;
var TREE_VIEW_POOL_TO_OPEN	= new Array();

// This is the entry method into the Tree View. It builds an initial single row, single cell table tat will 
// contain the tree. It initialises a global object "treeViewRootCell". This object must be used as the parent for all 
// top-level tree elements.
// There are two methods for creating tree elements: CreatePackage() and CreateNode(). The images for the 
// package are hard coded. CreateNode() allows you to supply your own image for each node element.
function InitialiseTreeView(treeViewContainer) {
	TREE_VIEW_CONTAINER = getElementById(treeViewContainer);
	
	if (TREE_VIEW_CONTAINER == null) return true;
	
	table = document.createElement("TABLE");
	TREE_VIEW_CONTAINER.appendChild( table );

	table.setAttribute( "border", 0 );
	table.setAttribute( "cellpadding", 1 );
	table.setAttribute( "cellspacing", 1 );
		
	tablebody = document.createElement("TBODY");
	table.appendChild(tablebody);
		
	row=document.createElement("TR");
	tablebody.appendChild(row);
		
	cell=document.createElement("TD");
	row.appendChild(cell); 	
	
	treeViewRootCell = cell;	// Initialise the root of the tree view.
}

//--- Ajax callers ------------------------------
var showingWaitCategoryTree = null;
function doAjaxCategoryTreePopulate(url) {
	if (showingWaitCategoryTree == null) {
		var newDiv = document.createElement("div");
		newDiv.style.width = TREE_VIEW_CONTAINER.offsetWidth + "px";
		newDiv.style.height = TREE_VIEW_CONTAINER.offsetHeight + "px";
		newDiv.className = "loading";
		newDiv.style.backgroundImage = "url(" + IMG_AJAX_WAIT + ")";
		
		TREE_VIEW_CONTAINER.parentNode.insertBefore(newDiv,TREE_VIEW_CONTAINER);
		
		showingWaitCategoryTree = newDiv;
	}
	
	AjAX_POOL.processNext(new AjaxCaller('GET',url,null,processXmlCategoryTreePopulate,true,false));
}

function processXmlCategoryTreePopulate(xml,elementSelect) {
	var result = false;
	if (xml != null && xml.getElementsByTagName("childs").length != 0) {
		var toLoad = xml.getElementsByTagName("childs").item(0);
		var xmlRows = toLoad.getElementsByTagName("category");
		for (var i = 0; xmlRows != null && i < xmlRows.length; i++) {
			var xmlRow = xmlRows.item(i);

			var id			= xmlRow.getAttribute("id");
			var label		= xmlRow.getAttribute("label");
			var url			= xmlRow.getAttribute("url");
			var urlAjx		= xmlRow.getAttribute("urlAjx");
			var selected	= toBoolean(xmlRow.getAttribute("selected"));
			var mustOpen	= toBoolean(xmlRow.getAttribute("mustOpen"));
			var childs		= parseInt(xmlRow.getAttribute("childsCount"));
			var items		= parseInt(xmlRow.getAttribute("itemsCount"));
			
			CreateTreeViewItem( TREE_VIEW_SELECTED, id, label, url, urlAjx, selected, childs, items);
			
			if (mustOpen) TREE_VIEW_POOL_TO_OPEN.push(id);
		}
		
	
		TREE_VIEW_SELECTED = null;
		
		result = true;
	}

	if (TREE_VIEW_POOL_TO_OPEN.length > 0) {
		treeViewToggle(TREE_VIEW_POOL_TO_OPEN.shift());
	} else if (showingWaitCategoryTree != null) {
		removeElement(showingWaitCategoryTree);
		showingWaitCategoryTree = null;
	}

	if (result == true) return true;
	
	alert("Ops! Nothing to load");
	return false;
}