/**
 * @param target Function
 * @param callback Function
 * @param duration int
 */
function Thread(target, callback, duration){
	
	/**
	 * @access private
	 */
	this.complete = false;
	
	/**
	 * @access private
	 */
	this.target = target;
	
	/**
	 * @access private
	 */
	this.callback = callback;
	
	/**
	 * @access private
	 */
	this.duration = duration || 500;
	
	/**
	 * @access private
	 */
	this.target.thread = this;
	
	/**
	 * Destroys this thread, without any cleanup. 
	 * @access public
	 * @type void
	 */
	this.destroy = function(){
		if(target.thread.timer) clearTimeout(target.thread.timer);
		target.thread.removeThread(target.thread);
		target.thread.constructor.current = null;
	};
	
	/**
	 * @access private
	 */
	this.run = function(){
		target.thread.constructor.current = target.thread;
		target.thread.complete = target.thread.target();
		if(target.thread.complete) {
			target.thread.destroy();
			if(target.thread.callback) target.thread.callback();
		}else{
			target.thread.timer = setTimeout(target.thread.run, target.thread.duration);
		}
	};
	
	/**
	 * @access private
	 */
	this.addThread = function(thread){
		//alert(this.constructor);
		if(!this.constructor.threads) this.constructor.threads={length:0};
		this.constructor.threads[this.constructor.threads.length] = thread;
		this.constructor.threads.length++;
	};
	
	/**
	 * @access private
	 */
	this.removeThread = function(thread){
		//alert(this.constructor);
		for(var i=0; i<this.constructor.threads.length;i++){
			//alert(this.constructor.threads[i]);
			if(this.constructor.threads[i]==thread){
				this.constructor.threads[i]=null;
				this.constructor.threads.length--;
				return true;
			}
		}
		return false;
	};
	
	/**
	 * @access private
	 */
	this.currentThread = function(){
		return this.constructor.currentThread();
	};

	/**
	 * @access private
	 */
	this.activeCount = function(){
		return this.constructor.activeCount();
	};
	
	this.addThread(this);
	this.run();
};

/**
 * Returns a reference to the currently executing thread object.
 * @access public
 * @static
 * @type Thread
 * @return the currently executing thread.
 */
Thread.currentThread = function() {
	return (Thread.current) ? Thread.current : null;
};

/**
 * Returns the number of active threads in the current thread's thread group.
 * @access public
 * @static
 * @type int
 * @return the number of active threads in the current thread's thread group.
 */
Thread.activeCount = function(){
	return (Thread.threads) ? Thread.threads.length : 0;
};
