// *************
// Thread Class 
// *************

/*
*** REMARK ***
Owner object must provide a callback member method which the tread instance may call
with the predefined periode of time. The 'this' point is scoped to the owner object.
Thread *must* be ended by calling 'stop()' to prevent leakage (no auto-garbage-coll)

*** INTERFACE METHODS ***

Thread(oOwner, milliSecPeriode, strCallbackMethodName)		//constructor
start();													//begin threading
setPeriode([milli seconds between calls])					//set a periode
setCallbackMethodName([string containing callback name])	//set callback method name							
isRunning();  //is thread running
stop();														//end threading

*** Example ***
//alert's "testing 1 2 3" ever 2 seconds
var testVar ="testing 1 2 3";
var oThread = new Thread(this, "run", 2000);
oThread.start();

function run() {
	alert(testVar);
}
*/

function Thread(oOwner, milliSecPeriode, strCallbackMethodName) {
	if(typeof(oOwner) == 'undefined') throw new Error("no owner object given");
	else this.m_oOwner = oOwner;
	
	if(typeof(strCallbackMethodName) == 'undefined') this.m_callbackMethodName = null;
	else this.m_callbackMethodName=strCallbackMethodName;

	if(typeof(milliSecPeriode) == 'undefined') throw new Error("no periode given");
	else this.m_milliSecPeriode = milliSecPeriode;
	
	//generate a unique id for this session
	//for simulating threading i javascript
	var oDate1 = new Date();
	var oDate2 = new Date();
	while(oDate1.getTime() == oDate2.getTime()) {
		oDate2 = new Date();
	}
	
	this.isRunning=false;
	this.m_name = document.uniqueID;				//"knobb"+oDate2.getTime();		//unique id for this instance
	this.m_threadHook = null;
	//end thread init
}
Thread.prototype.setPeriode = function(milliSecPeriode) {
	this.m_milliSecPeriode = milliSecPeriode;
}

Thread.prototype.setCallbackMethodName = function(strCallbackMethodName) {
	this.m_callbackMethodName = strCallbackMethodName;
}

Thread.prototype.start = function() {
	this.isRunning = true;
	window[this.m_name] = this;
	window[this.m_name+"func"] = new Function("this['"+this.m_name+"'].run()");
	this.m_threadHook = window.setInterval(this.m_name+"func()", this.m_milliSecPeriode);
}
Thread.prototype.stop = function() {
	if(this.isRunning) {
		window[this.m_name] = null;
		window[this.m_name+"func"] = null;
		window.clearInterval(this.m_threadHook);
		this.isRunning=false;
	}
	//alert("thread released");
}
Thread.prototype.isThreadRunning = function() {
	return this.isRunning;
}
Thread.prototype.run = function() {
	if(this.m_callbackMethodName!=null) (this.m_oOwner)[this.m_callbackMethodName]();
	else throw new Error("no callback defined in thread instance");
}



