// JavaScript Document

function _tween_timerFunction(obj) {
	obj.timerFunction();	
}

function Tween(init) {
	
	var newtween = {
		/* public */
		from: 0,
		to: 1,
		time: 1,
		onFinish: null,
		update: function () { },
		onStart: null,
		mode: 0, // 0=normal, 1=pingpong		
		
		/* private */
		steps: 1,
		step: 0,
		timer: null,	
		isActive: function() {
			return (this.timer != null);
		},
		fps: 35,
		timerFunction: null,
		transition: function(x) { return 1 - Math.cos(Math.PI*x/2); },
		// transition: function(x) { return x; },		
		// transition: function(x) { return (Math.pow((2*x-1),3)+1)/2; },
					
		stepForward: function() {
			with(this) 
				if (step > (steps - 1)) {
					update(to);
					clearInterval(timer);
					timer = null;
					if(onFinish) onFinish();					
				} else {
					step ++;
					update(from + (to - from)*transition(step/steps));				
				}			
		},
		
		stepBackward: function() {
			with(this) 
				if (step <= 0) {
					update(from);
					clearInterval(timer);
					timer = null;
					if(onFinish) onFinish();					
				} else {
					step --;
					update(from + (to - from)*transition(step/steps));				
				}
		},
				
		programTimer: function() {
			if (this.timerFunction == null) {						
				var ref = this;
				this.timerFunction = function () {
					ref.stepFunction();
				}
			}
			this.timer = setInterval(this.timerFunction, this.time/this.steps);			
		},
		
			
		/* Public */			
		start: function() {		
			if (this.timer==null) {	
				with(this) {
					this.stepFunction = this.stepForward;
					if(onStart) onStart();
					steps = Math.round((fps*time) / 1000);
					step = 0;			
					update(from);			
					programTimer();					
				}				
			} else {
				this.stepFunction = this.stepForward;			
			}
		},
		
		rewind: function() {
			if (this.timer==null) {	
				with(this) {
					this.stepFunction = this.stepBackward;
					if(onStart) onStart();
					steps = Math.round((fps*time) / 1000);
					step = steps;			
					update(to);			
					programTimer();					
				}				
			} else {
				this.stepFunction = this.stepBackward;			
			}
		},
			
		stop: function() {
			if (this.timer) {
				clearInterval(this.timer);
				timer = null;
			}
		}
		
	}
	
	if(init) {
		for (var prop in init) 
			newtween[prop] = init[prop];					
	}
	
	return newtween;
}