/**
 * @author Cientista
 */

function Fader() {
	this.speed = 0.05; // 5% each
	this.interval = 10; // 10ms
	var _this = this;
	
	this.onFinish = function() {}
	
	this.fade = function (eOut, eIn) {
		var once = false;
		var onFinishFunc = _this.onFinish;
		
		_this.onFinish = function() {
			if (!once) {
				_this.onFinish = onFinishFunc;
				_fadeIn(eIn);
			}
			once = true;
		}
		_fadeOut(eOut);
	}
	
	this.fadeIn = function(elem) {
		_fadeIn(elem);
	}
	
	this.fadeOut = function(elem) {
		_fadeOut(elem);
	}
	
	function _fadeIn(elem) {
		setAlpha(elem, 0);
		setDisplay(elem, true);
		var alpha = 0;
		var func = function() {
			alpha += _this.speed;
			if (alpha >= 1) alpha = 1;
			setAlpha(elem, alpha);
			if (alpha == 1) {
				clearInterval(i);
				_this.onFinish();
			}
		}
		var i = setInterval(func, _this.interval);
	}
	
	function _fadeOut(elem) {
		var alpha = 1;
		var func = function() {
			alpha -= _this.speed;
			if (alpha <= 0) {
				setDisplay(elem, false);
				clearInterval(i);
				_this.onFinish();
			} else setAlpha(elem, alpha);
		}
		var i = setInterval(func, _this.interval);
	}
	
	function setAlpha(elem, alpha) {
		elem.style.opacity = alpha;
		elem.style.filter = 'alpha(opacity = ' + (alpha*100) + ')';
	}
	
	function setDisplay(elem, display) {
		if (display) elem.style.display = "block";
		else elem.style.display = "none";
	}
}