/* 
Title:   FadeDivAnimator
Author:  Shadanan Sharma
Site:    http://www.shadanan.com/
Version: 1.0
License: This script is released under the terms specified by
         the LGPL (GNU Lesser General Public License). Under this
         license, the user may use, distribute and link with
         this code in closed source development. Any modifications
         to this code must be released under the LGPL or other
         stricter copy-left licenses.

Description:
This javascript object is used to create an animated DIV that will
fade in and out when the methods show() and hide() are called.

This object can be instantiated as follows:
var animator = new FadeDivAnimator(document.getElementById('yourDivIDHere'), 20, 2);

The rate parameter specifies the interval between calls to the
animator's run() method. It effectively controls the frame rate.

The factor parameter specifies how quickly the animation approaches
the destination value. The higher this value, the slower the
animation. The rate of approach has an inverse-exponential
relationship with the factor parameter.
*/
function FadeDivAnimator(div, rate, factor, opacity) {
	//Properties
	this.div = div;
	this.rate = rate;
	this.factor = factor;
	this.opacity = opacity;
	this.timer = null;
	
	//Init
	this.div.style.zIndex = -1;
	this.div.fadeDiv = this;
	this.div.style.opacity = 0;
	if (navigator.appName == "Microsoft Internet Explorer") {
		this.div.style.height = "0px";
	}
	
	//Methods
	this.show = function() {
		this.div.style.zIndex = 1;
		if (navigator.appName == "Microsoft Internet Explorer") {
			this.div.style.height = "auto";
		}
		this.cancelAnimation();
		this.timer = setTimeout("document.getElementById('" + this.div.id + "').fadeDiv.run(" + this.opacity + ")", this.rate);
	}
	
	this.hide = function() {
		this.cancelAnimation();
		this.timer = setTimeout("document.getElementById('" + this.div.id + "').fadeDiv.run(0)", this.rate);
	}
	
	this.cancelAnimation = function() {
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.timer = null;
		}
	}

	this.run = function(dest) {
		var currop = parseFloat(this.div.style.opacity);
		var nextop = (dest - currop)/this.factor + currop;
		if (Math.abs(dest - nextop) < .005) nextop = dest;
		this.div.style.opacity = nextop;
		if (navigator.appName == "Microsoft Internet Explorer") {
			this.div.style.filter = 'alpha(opacity=' + (100*nextop) + ')';
		}
		if (nextop != dest) {
			this.timer = setTimeout(
					"document.getElementById('" + this.div.id + "').fadeDiv.run(" + dest + ")", 
					this.rate);
		} else {
			if (dest == 0) {
				this.div.style.zIndex = -1;
				if (navigator.appName == "Microsoft Internet Explorer") {
					this.div.style.height = "0px";
				}
			}
		}
	}
}
