var FADERINITIALISED = false;

function Fader()
{	
	if(!FADERINITIALISED)
	{
	    var self = this;
		self.fadingStates = new Array();
		var elementPos = new Array();
	
		this.addFadee = function(element, startColor, targetColor, steps)
		{
			if(steps == null)
			{
				steps = 500;
			}
			if(elementPos[element.id] == null)
			{
				elementPos[element.id] = self.fadingStates.length;
			}
			self.fadingStates[elementPos[element.id]] = new FadingState(element, startColor, targetColor, steps);
		}
	
		this.fadeElements = function()
		{
			var stopLoading = document.getElementById("stopLoading");
			if(stopLoading == null || !stopLoading.checked)
			{
				for(var i = 0; i < self.fadingStates.length; i++)
				{
					if(self.fadingStates[i] != null)
					{
						self.fadingStates[i].fade();
						if(self.fadingStates[i].currentStep == self.fadingStates[i].steps)
						{
							self.fadingStates[i] = null;
						}
					}
				}
			}
			setTimeout(self.fadeElements, 50);
		}
		this.start = function()
		{
			this.fadeElements();
	
		}

		this.start();
		FADERINITIALISED = true;
	}
}



function FadingState(element, startColor, targetColor, steps)
{
	this.element = element;
	this.currentColor = startColor;
	this.targetColor = targetColor;
	this.steps = steps;
	this.currentStep = 0;

	this.fade = function()
	{
		if(steps != 0)
		{
//			if(Number(this.currentColor.red) && Number(this.currentColor.green) && Number(this.currentColor.blue) )
			{
				this.element.style.background = "rgb("+ this.currentColor.red+","+this.currentColor.green+","+this.currentColor.blue+")";
				var newRed = Math.round(this.currentColor.red *  (this.steps - this.currentStep)/this.steps + this.targetColor.red * (this.currentStep/this.steps));
				var newGreen = Math.round(this.currentColor.green * (this.steps - this.currentStep)/this.steps + this.targetColor.green * (this.currentStep/this.steps));
				var newBlue = Math.round(this.currentColor.blue * (this.steps - this.currentStep)/this.steps + this.targetColor.blue * (this.currentStep/this.steps));

				this.currentColor = new Color(newRed, newGreen, newBlue);
				this.currentStep++;

//				debug(this.element.id + " " + this.currentColor.toString());
			}
		}
		else
		{
			this.currentColor = targetColor;
			this.element.style.background = "rgb("+ this.currentColor.red+","+this.currentColor.green+","+this.currentColor.blue+")";
//			this.currentStep = steps;
		}
	}
}
FadingState.prototype.toString = function() 
{
	return element.id + " " + currentColor.toString();
}


function Color(red, green, blue)
{
	this.red = red;
	this.green = green;
	this.blue = blue;
}

Color.prototype.toString = function() 
{
    return "rgb("+ this.red +","+ this.green +","+ this.blue +")";
}


