/*
 * Created on 29.05.2011
 * Copyright (c) Andreas Bauer <andreas.bauer@creaktif.de>
 */

function Opacity(elementId, beginOpacity)
{
	this._element = document.getElementById(elementId);
	this._opacity = beginOpacity;
	this._waitTimer = null;
	this._timer = null;
	
	this.ChangeOpacity = function(maxOpacity, duration, speed)
	{
		// Den neuen Opacity Wert anhand beginOpacity und maxOpacity berechnen
		this._opacity = (this._opacity > maxOpacity) ? this._opacity - duration : this._opacity + duration;
		
		// Soll auch im Internet Explorer bei Objekten ohne Layout funktionieren
		if (Browser.InternetExplorer())
		{
			if (!this._element.currentStyle.hasLayout)
				this._element.style.zoom = 1;
			
			var value = this._opacity * 100;

			this._element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + value + ')'; /* FŸr IE 8 */
			this._element.style.filter = 'alpha(opacity=' + value + ')'; /* FŸr IE 5-7 */
		}
		else
		{
			this._element.style.opacity = this._opacity;
		}
		
		// Neuen Opacity Wert dem Element zuweisen
		var objRef = this;
		this._timer = setTimeout(function() { objRef.Start(maxOpacity, duration, speed, 0); }, speed);
		
		clearTimeout(this._waitTimer);
		this._waitTimer = null;
	}
}

// Dieses Objekt dem CustomEvent Object ableiten und ein Event abonnieren
Opacity.prototype = new CustomEvent("OnOpacityFinish");

// Ein leeres Event abonnieren falls kein Custom Event abonniert wurde
Opacity.prototype.Subscribe(function(sender, eventArgs) { });

Opacity.prototype.Start = function(maxOpacity, duration, speed, delay)
{
	if ((this._opacity > maxOpacity && this._opacity > 0 && this._opacity <= 1) ||
		(this._opacity < maxOpacity && this._opacity >= 0 && this._opacity < 1))
	{
		var objRef = this;
		this._waitTimer = setTimeout(function() { objRef.ChangeOpacity(maxOpacity, duration, speed); }, delay);
	}
	else
	{
		clearTimeout(this._timer);
		this._timer = null;
		
		if (Browser.InternetExplorer())
		{
			var value = maxOpacity * 100;
			
			this._element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + value + ')'; /* FŸr IE 8 */
			this._element.style.filter = 'alpha(opacity=' + value + ')'; /* FŸr IE 5-7 */
		}
		else
		{
			this._element.style.opacity = maxOpacity;
		}
		
		// Wenn der Timer fertig durchgelaufen ist wird ein Event ausgelšst
		this.Fire(null, null);
	}
}

Opacity.prototype.Reset = function()
{
	clearTimeout(this._waitTimer);
	this._waitTimer = null;
	
	clearTimeout(this._timer);
	this._timer = null;
}
