//cart_popup.js
// includes functions to have a box (div or other HTML element) fade-in, linger for a time, then fade-out

//Global Constants 
var MIN_OPAC = 10;		//minimum opacity
var MAX_OPAC = 100;		//maximum opacity
var FADE_DUR = 500;		//duration of the fade-in/fade-out (milliseconds)
var DISP_DUR = 10000;	//duration for which the box is shown (milliseconds)

//variable for the timer to hide the box
var hide_timer = null;

//Causes the box to fade-in as it is displayed
//	auto-hides the box after DISP_DUR
function showBox(id) {
	var popBox = document.getElementById(id);
	
	//show the box
	popBox.style.display = "block";
	
	//cause the box to fade-in
	opacity(id, MIN_OPAC, MAX_OPAC, FADE_DUR);
	
	//cause the box to fade-out after DISP_DUR

	hide_timer = setTimeout(function() {
		hideBox(id);
	}, DISP_DUR);	

}

//Causes the box to fade-out and be hidden
function hideBox(id) {
	//cancel the timer if it is still going
	if(hide_timer != null)
		clearTimeout(hide_timer);
	
	//fade out
	opacity(id, MAX_OPAC, MIN_OPAC, FADE_DUR);
	
	//hide the element
//	setTimeout(hideElement, FADE_DUR, id);
	setTimeout((function(elem_id){
		return function() {
			hideElement(elem_id);
		}
	})(id), FADE_DUR);
}

function hideElement(id) {
	element = document.getElementById(id);
	element.style.display = "none";
}


//Causes an element to change opacity (fade-in/fade-out)
//	id			- the element id
//	opacStart	- the starting opacity
//	opacEnd		- the ending opacity
//	millisec	- the duration of the fade (from start to end)
function opacity(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(var i = opacStart; i >= opacEnd; i--) {
			var timeoutDur = timer * speed;
			
//			setTimeout(changeOpac, timeoutDur, id, i);
			setTimeout((function(elem_id, opacityVal){
				return function() {
					changeOpac(elem_id, opacityVal);
				}
			})(id, i), timeoutDur);

			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(var i = opacStart; i <= opacEnd; i++) {
			var timeoutDur = timer * speed;
			
//			setTimeout(changeOpac, timeoutDur, id, i);
/*			setTimeout(function(){
				changeOpac(id, i);
			}, timeoutDur);
*/			
			setTimeout((function(elem_id, opacityVal){
				return function() {
					changeOpac(elem_id, opacityVal);
				}
			})(id, i), timeoutDur);


			timer++;
		}
	}
}

//change the opacity for different browsers
function changeOpac(id, opacity) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);	/* CSS Compliant style */
	object.MozOpacity = (opacity / 100);	/* Legacy Mozilla style */
	object.KhtmlOpacity = (opacity / 100);	/* Legacy Konquer style */
	object.filter = "alpha(opacity=" + opacity + ")";  /* IE style */
}

