// JavaScript Document <<< CoreWeb Transition v1.0.1 >>>

function CWTransition(curve, milliseconds, callback) {
	this.inProgress = false;
    
	this.curve_ = curve;
	this.milliseconds_ = milliseconds;
	this.callback_ = callback;
    
	this.onStarted = null;
	this.onEnded = null;
    
	this.start_ = new Date().getTime();
	var me = this;
	this.runCallback_ = function() {
		me.run_();
	};
}

CWTransition.prototype.run_ = function() {
	if (!this.hasNext()) {
		this.inProgress = false;
		return;
	}
	if (this.onStarted != null && !this.inProgress) this.onStarted();
	this.inProgress = true;
	this.callback_(this.next());
	setTimeout(this.runCallback_, 10);
}

CWTransition.prototype.start = function() {
	if (this.inProgress) return;
	this.start_ = new Date().getTime();
	this.done_ = false;
	this.oneLeft_ = false;
	this.run_();
}

CWTransition.prototype.restart = function() {
	if (!this.inProgress) return;
	this.start_ = new Date().getTime();
	this.done_ = false;
	this.oneLeft_ = false;
}

CWTransition.prototype.hasNext = function() {
	if (this.done_) return this.oneLeft_;
	var now = new Date().getTime();
	if ((now - this.start_) > this.milliseconds_) {
		this.done_ = true;
		this.oneLeft_ = true;

		if (this.onEnded != null) this.onEnded();
	}
	
	return true;
}

CWTransition.prototype.next = function() {
	this.oneLeft_ = false;
	var now = new Date().getTime();
	var percentage = Math.min(1, (now - this.start_) / this.milliseconds_);
	return this.curve_(percentage);
}


/* pre-defined sinusoidal and linear */


function SineCurve(percentage) {
	return (1 - Math.cos(percentage * Math.PI)) / 2;
}

function LinearCurve(percentage) {
	return percentage;
}

function PulseCurve(percentage) {
	return (1 - Math.cos((percentage * 2) * Math.PI)) / 2;
}