/*
  File        : auto.js
  Author      : DS
  Date        : 2004-07-30
  Description : JavaScript for automaton and timer
*/

/*** Create a new automaton ***/
function Auto()
{
	this.state         = 0;
	this.repeat        = null;
}
Auto.prototype.trans = new Array(new Array("TEST", "", 0));

/*** Event handler ***/
function event(evt)
{
	var transitionName = "";
	try
	{
		this.repeat = null;
		var ts = this.trans[this.state];
		for (var i=0; i<ts.length; i++)
		{
			var t = ts[i];
			if (this.isEvent(evt, t[0]))
			{
				transitionName = t[1];
				eval(t[1]);
				this.state = t[2];
				break;
			}
		}
	}
	catch (e)
	{
		alert("event("+evt+") "+transitionName+" state "+this.state+" exception : " + e);
	}
	finally
	{
		if (this.repeat != null)
		{
			event(this.repeat)
		}
	}
}

/*** Allow repeated events ***/
function repeatEvent(evt)
{
	this.repeat = evt;
}

/*** Matches events to string or regular expression ***/
function isEvent(evt, code)
{
	if (typeof code == "string")
	{
		return (evt == code);
	}
	else
	{
		return code.test(evt);
	}
}

/*** Attach the automaton methods ***/
Auto.prototype.event       = event;
Auto.prototype.repeatEvent = repeatEvent;
Auto.prototype.isEvent     = isEvent;

/*** Class Timer : for use with Auto ***/
function Timer(id, evt, timeout)
{
	this.id      = id;
	this.evt     = evt;
	this.timeout = timeout;
	this.timerId = null;
}

function Timer_set()
{
	this.timerId = setTimeout("Timer_trigger('"+this.id+"','"+this.evt+"')", this.timeout);
}
function Timer_clear()
{
	clearTimeout(this.timerId);
	this.timerId = null;
}
function Timer_trigger(id, evt)
{
	document.getElementById(id).control.event(evt);
	this.timerId = null;
}
/*** Attach the Timer methods ***/
Timer.prototype.set     = Timer_set;
Timer.prototype.clear   = Timer_clear;

