function spawn(generator) {
	return new Thread(generator).start();
}

// the classic sleep method implementation
function sleep(millis) {
	setTimeout((yield CONTINUATION), millis);
	yield SUSPEND;
}

// a simple counting function that demonstrates how to sleep
function count(elem) {
numero = document.getElementsByTagName("td").item(3).innerHTML;
for (var i = numero; i >= 0; i--) {
elem.removeChild(elem.firstChild);
elem.appendChild(document.createTextNode(i));
		yield sleep(1000);
if (TagTooga.Mp3.playimg.src == "play.png") 
{
 yield SUSPEND;
}
	}
}

// global vars for thread management
var activeThreads = [];
var waitingThreads = [];
var threadCount = 0;

spawn( function() {
	// wait for the page to load
	while (document.body == null) {
		yield sleep(100);
	}

	// this thread runs for the lifetime of the page
	while (true) {
		// wait for all running threads to end
		while (activeThreads.length) {
			yield activeThreads.shift().join();
		}

// launch a thread if one is waiting
		if (waitingThreads.length) {
			var thread = waitingThreads.shift();
			activeThreads.push(thread);
			thread.start();
		}

		// wait for new threads if necessary
		while (!activeThreads.length && !waitingThreads.length) {
			yield sleep(100);
		}


	}
});

// creates a new thread for counting, unstarted
function createCounter() {

	box = document.getElementsByTagName("td").item(3);

	return new Thread(
		count(box)
	);
}

// starts a counting thread the moment it is called
function startImmediate() {
	var thread = createCounter();
	activeThreads.push(thread);
	thread.start();
}
	
