//////////////////////////////////////////////////////////////////////
// Fade in/out a DOM object
// Dependencies: Utils.js (for SetOpacity)
//////////////////////////////////////////////////////////////////////
function Fader(obj_or_id, minOpacity, maxOpacity, startVisible, removeOnHide, defaultStep, defaultInterval)
{
	if (typeof(obj_or_id) == "string")
	{
		this.obj = document.getElementById(obj_or_id);
	}
	else
	{
		this.obj = obj_or_id;
	}
	this.minOpacity = minOpacity ? minOpacity : 10;
	this.maxOpacity = maxOpacity ? maxOpacity : 100;

	this.removeOnHide    = removeOnHide;
	this.defaultStep     = defaultStep;
	this.defaultInterval = defaultInterval;
	
	this.visible = startVisible;
	this.SetOpacity(startVisible ? this.maxOpacity : this.minOpacity);
	this.listeners = new Array();
}

Fader.prototype.SetOpacity = function(opacity)
{
	this.currentOpacity = opacity;

	if (!this.obj)
	{
		return;
	}
	else if (this.obj.SetOpacity)
	{
		this.obj.SetOpacity(opacity);
	}
	else
	{
		SetOpacity(this.obj, opacity);
	}

	if (this.removeOnHide)
	{
		this.obj.style.display = (this.currentOpacity == this.minOpacity) ? "none" : "";
	}
}

Fader.prototype.Fade = function(fade_in, step, interval)
{
	this.visible = fade_in;
	var direction = fade_in ? 1 : -1;
	if (!step)
	{
		step = this.defaultStep ? this.defaultStep : 40;
	}
	if (!interval)
	{
		interval = this.defaultInterval ? this.defaultInterval : 55;
	}
	this.StartFade(direction * step, interval);
}

Fader.prototype.FadeIn = function(step, interval)
{
	this.Fade(true, step, interval);
}

Fader.prototype.FadeOut = function(step, interval)
{
	this.Fade(false, step, interval);
}

Fader.prototype.StartFade = function(step, interval)
{
	if (step != this.step || interval != this.interval)
	{
		this.EndFade();
		this.step     = step;
		this.interval = interval;

		var me = this;
		var func = function()
		{
			me.DoFadeStep();
		}
		this.fadeInterval = setInterval(func, interval);
	}
}

Fader.prototype.EndFade = function()
{
	if (!this.fadeInterval)
	{
		return;
	}

	clearInterval(this.fadeInterval);
	this.fadeInterval = null;
	this.step         = null;
	this.interval     = null;
	this.OnEnd();
}

Fader.prototype.DoFadeStep = function()
{
	this.SetOpacity(Math.max(this.minOpacity, Math.min(this.currentOpacity+this.step, this.maxOpacity)));
	if (this.currentOpacity == this.minOpacity || this.currentOpacity == this.maxOpacity)
	{
		this.EndFade();
	}
}

Fader.prototype.AddListener = function(listener)
{
	this.listeners.push(listener);
}

Fader.prototype.OnEnd = function()
{
	for (var i = 0; i < this.listeners.length; ++i)
	{
		this.listeners[i].OnFadeEnd();
	}
}

