// Spawning code for randomly creating and deleting new nodes 
// Written Nov. 2003 by David Turover
// This code is hereby placed in the public domain.

// API: 
// killNodeById(id) -- delete node with ID 'id'
// killNode(node) -- delete node
// spawn(parent, node) -- Put node under parent and assign it an ID
// spawnt(parent, node, seconds, function_name)



// Counter for random nodes' IDs so they can be deleted by timeouts
// There is never a node ID 0; nodeIDctr is incremented first.
// triggers[0] is wasted space, can be maligned by bad code in any way
var nodeIDctr = 1;
var max_node_id = 65;
var triggers = new Array(max_node_id + 1);


function spawn(parent, node){
	if((parent) && (node)){
		if(nodeIDctr >= max_node_id){
		//	alert("Warning: reached maximum nodes "
		//	+ max_node_id + ", recycling"); 
			nodeIDctr = 0;
		}

		++nodeIDctr;

		// Check for a node with this ID already existing
		if(document.getElementById(nodeIDctr)){
			killNodeById(nodeIDctr);
		}

		node.setAttribute("id", nodeIDctr);
		parent.appendChild(node);
		//alert("Created node " + nodeIDctr);
		return nodeIDctr;
	}
	// Fail if parent or node is null
	//alert("D'oh!");
	return 0;
}


function killNode(node){
	if(node){
		var id = parseInt(node.getAttribute("id"));
/*
		alert(id);
		alert(node);
		alert(node.parentNode);
*/
		node.parentNode.removeChild(node);
		//alert("Yo.");
		clearTimeout(triggers[parseInt(id)]);
		// alert(triggers[parseInt(id)]);
	} else {
		//alert("null passed to killNode");
	}
}

function killNodeById(id){
	killNode(document.getElementById(id));
}


function spawnt(parent, node, time, call){
	// Spawn a random node with its own timeout-triggered function
	// 'time' is delay before function is run;
	// the function must have its own delay if it repeats

	var id = parseInt(spawn(parent, node));
	if(id){
		/// !!! TODO: Only if can be parseInt()ed
		// Something else must be done for other triggers
		if(typeof(triggers[id]) != "undefined"){
			//alert(typeof triggers[id]);
			clearTimeout(triggers[id]);
		}
		triggers[id] = setTimeout(call + "(" + id + ")", time * 1000);
		//alert(triggers[id]);
	} else {
		//alert("Spawn failed");
	}
}

