var frameRate = 32; // How quickly the data is refreshed

/* Init fading an element */
function fadeElement( myElem, initAlpha, targetAlpha, timeTaken, endFunc ) {
	var myElemName = myElem.getAttribute( 'id' );
	var speed = 1000 / frameRate;
	
	var alphaChange = ( targetAlpha - initAlpha ) / ( ( timeTaken * 1000 ) / speed );
	
	changeOpacity( myElemName, initAlpha, targetAlpha, alphaChange, speed, endFunc );
}

/* Set timeouts to slowly fade an element in or out */
function changeOpacity( myElemName, currAlpha, targetAlpha, alphaChange, changeSpeed, endFunc ) {
	var myElem = document.getElementById( myElemName );
		
	if( myElem ) {
		if( ( alphaChange > 0 && currAlpha > targetAlpha ) ||
				(	alphaChange < 0 && currAlpha < targetAlpha ) ) {
			currAlpha = targetAlpha;
			setOpacity( myElem, currAlpha );
			
			// Run function when it's finally faded completely
			if( endFunc ) {
				endFunc();
			}
		}
		else {
			currAlpha += alphaChange;
			
			setOpacity( myElem, currAlpha );
			
			var alterOpacity = function() {
				changeOpacity( myElemName, currAlpha, targetAlpha, alphaChange, changeSpeed, endFunc );																
			}
			
			setTimeout( alterOpacity, changeSpeed ); 	// Keep animating the fade			
		}
	}
}

/* Sets opacity depending on which browser you're using */
function setOpacity( myElem, currAlpha ) {
	if( document.all ) {
		myElem.style.filter = 'alpha(opacity=' + parseInt( currAlpha ) + ')';
	}
	else if( myElem.style.MozOpacity ) {
		myElem.style.MozOpacity = currAlpha / 100;
	}
	else {
		myElem.style.opacity = currAlpha / 100;
	}
}