﻿window.setTimer = function(method, delay, caller)
{
	// prepare arguments
	var args;
	if(arguments.length > 3)
	{
		args = new Array(arguments.length - 3);
		for(var i = 0; i < arguments.length; i++)
			args[i - 3] = arguments[i];
	}

	var timer = new Timer(method, delay, caller, args);
	return timer.SetTimeout();
};

function Timer(method, delay, caller, args)
{
	this.index;
	this.arguments = args;
	this.caller = caller;
	this.method = method;
	this.timeout;
	this.delay = delay;
	
	// prepare window
	if(window.__timers == null)
		window.__timers = new Array();

	// push new Timer
	this.index = window.__timers.length;
	window.__timers[this.index] = this;
};

Timer.prototype.Dispose = function()
{
	//alert('disposing...');
	window.__timers[this.index] = null;
	//alert(window.__timers[this.index]);
};

Timer.prototype.SetTimeout = function(milliseconds)
{
	if(milliseconds != null)
		this.delay = milliseconds;
	// build function
	var timedFunction = new String();
	timedFunction = 'window.__timers[' + this.index.toString() + '].method.call(';
	timedFunction += 'this.window.__timers[' + this.index.toString() + '].caller';
	for(var i = 0; i < this.arguments.length; i++)
		timedFunction += ', this.window.__timers[' + this.index.toString() + '].arguments[' + i.toString() + ']';
	timedFunction += ');'
	timedFunction += 'this.window.__timers[' + this.index.toString() + '].Dispose();'

	//alert(timedFunction);

	this.timeout = window.setTimeout(
		timedFunction,
		this.delay
	);
	return this.timeout;
};