/*
* OOP Image Blender Class. 
* Fading in first image on background of a container div in series, then loop.
* @Author Amine Boulaajaj
*/
function blendImages() {
    var imgArray = new Array();
    var imgIndex = 0;
    var opacity = 0;
    var speed;
    var pause;
    var imgContainer;
    var cImg;
    var fadeIn = true;
 
    //get container id, speed (s) of blend, and (p) pausing time between each blend
    this.init = function(id, s, p) {
        speed = (s == null) ? 30 : s;
        pause = (p == null) ? 1500 : p;
		
		imgContainer = document.getElementById(id);
		for (var i in imgContainer.childNodes) {
			if (imgContainer.childNodes[i].tagName == 'IMG') {
				imgArray[imgIndex] = imgContainer.childNodes[i];
				imgIndex++;
			}
		}
		imgIndex = 0;
        cImg = imgArray[0];
        setTimeout(function() { startBlending(cImg) }, pause);
    }
 
    function startBlending(cImg) {
        if(fadeIn){
            opacity = opacity - 10;
        }else{
            opacity = opacity + 10;
        }
        if (opacity >= 0 && opacity <= 100) {
            //keep blending
            setTimeout(function() { fade(cImg) }, speed);
        } else {
			cImg = imgArray[imgIndex];
			//if next image needs to be faded in, then set the display of the current one to none.
			//then get the next image and set its display to block and opacitiy to 0.
            if(fadeIn){
				opacity=0;
	            cImg.style.display = "none";
				//getting next image
				if ((imgArray.length - 1) > imgIndex) {
					imgIndex++;
				} else {
					imgIndex = 0;
				}
				cImg = imgArray[imgIndex]
				cImg.style.opacity = 0;
	            cImg.style.MozOpacity = 0;
	            cImg.style.KhtmlOpacity = 0;
	            cImg.style.filter = 'alpha(opacity=' + 0 + ')';
				cImg.style.display = "block";
				fadeIn=false;
			}else{//else set the background of the container div to the next image, then fade out the current image.
				opacity=100;
				cImg.parentNode.style.backgroundImage = "url(" + cImg.src + ")";
				fadeIn=true;
			}
            //pause then start over
            setTimeout(function() { fade(cImg) }, pause);
        }
    }
 
    //set the opacity of an element to a specified value
    function fade(cImg) {
        cImg.style.opacity = (opacity / 100);
        cImg.style.MozOpacity = (opacity / 100);
        cImg.style.KhtmlOpacity = (opacity / 100);
        cImg.style.filter = 'alpha(opacity=' + opacity + ')';
        startBlending(cImg)
    }
}
