/* Copyright Richard Cornford 2003. */
var TimedQue = (function(){
	var base, timer;
	var interval = 42;
	var newFncs = null;
	function addFnc(next, f){
		function t(){
			next = next&&next();
			if(f()){
				return t;
			}else{
				f = null;
				return next;
			}
		}
		t.addItem = function(d){
			if(next){
				next.addItem(d);
			}else{
				next = d;
			}
			return this;
		};
		t.finalize = function(){
			return ((next)&&(next = next.finalize())||(f = null));
		};
		return t;
	}
	function tmQue(fc){
		if(newFncs){
			newFncs = newFncs.addItem(addFnc(null, fc));
		}else{
			newFncs = addFnc(null, fc);
		}
		if(!timer){
			timer = setTimeout(tmQue.act, interval);
		}
	}
	tmQue.act = function(){
		var fn = newFncs, strt = new Date().getTime();
		if(fn){
			newFncs = null;
			if(base){
				base.addItem(fn);
			}else{
				base = fn;
			}
		}
		base = base&&base();
		if(base||newFncs){
			var t = interval - (new Date().getTime() - strt);
			timer = setTimeout(tmQue.act, ((t > 0)?t:1));
		}else{
			timer = null;
		}
	};
	tmQue.act.toString = function(){
		return 'TimedQue.act()';
	};
	tmQue.finalize = function(){
		timer = timer&&clearTimeout(timer);
		base = base&&base.finalize();
		newFncs = [];
	};
	return tmQue;
})();