
/**
 * @requirements prototype 1.6
 *
 * @author Helmut Wandl <helmut@wandls.net>
 * @version 0.beta
 *
 * @copy STERNWERK 2008
 *
 */
var motion=Class.create();

motion.prototype = {
	initialize:function(elements, options) {
		this.el=elements;
		this.o={
			duration:400,
			transition:'quadOut',
			fps:50,
			wait:false,
			func:null
		};
		this.a=0;

		Object.extend(this.o, (options ? options : {}));
		//if (typeof this.o.transition == 'string') this.o.transition=transitions[this.o.transition];
	},

	_transition:function(t, b, c, d) {
		if (typeof this.o.transition == 'string') return transitions[this.o.transition](t, b, c, d);
		else return this.o.transition(t, b, c, d);
	},

	start:function(styles) {
		if (!this.o.wait) this.clearTimer();
		if (this.timer) return;

		this.from={};
		this.to = styles;
		this.a=0;

		for (var i=0; this.el[i]; i++)
		{
			this.from[i]={};
			for (var j in this.to[i])
				this.from[i][j]=this.el[i].getStyle(j);
		}

		this.time = new Date().getTime();
		this.timer=setInterval(this.step.bind(this), Math.round(1000/this.o.fps));
	},

	step:function() {
		var i=0;
		this.a+=1;
		var t,b,c,d;
		var v;

		t=((new Date().getTime())-this.time);
		d=this.o.duration;

		var new_style=(t >= d ? this.to : {});

		for (; this.el[i]; i++)
		{
			//dev.log(this.o+' '+this.el[i]+' '+i);

			//dev.log(this._transition((new Date().getTime()), this.from, this.to, this.time));

			if (t < d)
			{

			new_style[i]={};

			for (var j in this.to[i])
			{
				if (this.from[i][j] == this.to[i][j]) continue;

				//dev.log(this.from[i][j]+' > '+this.to[i][j]);
				//dev.log(this.from[i][j]+' > '+this.el[i].getStyle(j));
				//dev.log();

				//var t=this._transition((this.time-(new Date().getTime())), parseInt(this.from[i][j]), (parseInt(this.to[i][j])-parseInt(this.from[i][j])), this.o.duration);

				var pf=this.from[i][j].toString().match(/ *(-?[0-9\.]+)(.*)/);
				var pt=this.to[i][j].toString().match(/ *(-?[0-9\.]+)(.*)/);

				b=parseFloat(pf[1]);
				c=parseFloat(pt[1])-parseFloat(pf[1]);

				var v=this._transition(t, b, c, d);
				//dev.log(t+' '+b+' '+c+' '+d+' = '+v);

				new_style[i][j]=v+pt[2];
				//dev.log(this.from[i][j]+' > '+new_style[i][j]+' > '+this.to[i][j]);

				//this.el[i].setStyle(this.to[i]);
			}}

			this.el[i].setStyle(new_style[i]);
		}

		if (t >= d && this.timer) clearInterval(this.timer);
		if (t >= d && this.o.func) this.o.func();
	},

	set:function(styles) {
		if (!this.o.wait) this.clearTimer();
		if (this.timer) return;
		var i=0;
		var p=this.o.duration;
		this.time = new Date().getTime();

		this.from={};
		this.to = styles;
		this.o.duration=0;
		this.step();
		this.o.duration=p;
	},

	clearTimer:function() {
		clearInterval(this.timer);
		this.timer = null;
		return this;
	}
};

