
//(c) 2007 HSW
// Author: michael squires

//Define class.
function Action_Thread (action, iterations, waitTime, runStart)
{
	this._threadId      = null;
	this._waitValue     = 10;
	this._thread        = null;
	this._action        = '';
	this._iterations    = 1;
	this._incIterations = 0;


	//Constructor
	this.__construct(action, iterations, waitTime, runStart);
}

//Static members
Action_Thread._threads   = new Array();
Action_Thread._threadInc = 0;


//Define instantiated members
Action_Thread.prototype.__construct = function (action, iterations, waitTime, runStart)
{
	//Create thread id for this object
	this._threadId = ++Action_Thread._threadInc;
	
	//Assign self reference to threads pool
	Action_Thread._threads[this._threadId] = this;
	
	this._action = action;
	
	if (typeof iterations != 'undefined')
	{
		this._iterations = iterations;
	}
	
	if (typeof waitTime != 'undefined')
	{
		this._waitValue = waitTime;
	}
	
	if (runStart == true)
	{
		this.run();	
	}
	
}

Action_Thread.prototype.setWait = function (waitValue)
{
	this._waitValue = (waitValue > 0 ? waitValue : this._waitValue);
}

Action_Thread.prototype.setIterations = function (iterations)
{
	this._iterations = (iterations > 0 ? iterations : this.iterations);	
}

Action_Thread.prototype.run = function ()
{
	if (this._thread == null)
	{
		this._incIterations = 0;
		this._thread = setInterval(this._buildAction(), this._waitValue);
		
		return true;
	}
	
	return false;
}

Action_Thread.prototype._buildAction = function ()
{
	var actionPrefix = '';
	var actionSuffix = '';
	if (this._iterations > 0)
	{
		actionPrefix = 'if(Action_Thread._threads[' + this._threadId + ']._incIteration()){ ';
		actionSuffix = ' }';
	}
	
	return actionPrefix + this._action + actionSuffix;
}

Action_Thread.prototype._incIteration = function ()
{
	if (this._iterations == 0)
	{
		return true;
	}
	
	++this._incIterations;
	
	if (this._incIterations > this._iterations)
	{
		this.kill();
		return false;
	}
	
	return true;
}

Action_Thread.prototype.kill = function ()
{
	clearInterval(this._thread);
	this._thread = null;
}