//find next image
Object.prototype.nextImage = function() {
    var o = this;
    do o = o.nextSibling;
    while(o && o.tagName != 'IMG');
    return o;
}

//find first image inside an element
Object.prototype.firstChildImage = function() {
    
    var o = this.firstChild;
        
    while(o && o.tagName != 'IMG') {
        o = o.nextSibling;
    }
    
    return o;
}

//set the opacity of an element to a specified value
Object.prototype.setOpacity = function(o) {

	this.style.opacity = (o / 100);
	this.style.MozOpacity = (o / 100);
	this.style.KhtmlOpacity = (o / 100);
	this.style.filter = 'alpha(opacity=' + o + ')';
}

//make image invisible and set next one as current image
function getNextImage(image) {
	
    if(next = image.nextImage()) {
		image.style.display = 'none';
		image.style.zIndex = 0;
		
		next.style.display = 'block';
		next.style.zIndex = 100;
		
	} else {
        //if there is not a next image, get the first image again
		next = image.parentNode.firstChildImage();
	}
	
	return next;
}

//set default values for parameters and starting image
function blendImages(id, speed, pause, caption) {

    if(speed == null) {
        speed = 30;
    }
    
    if(pause == null) {
        pause = 1500;
    }

    var blend = document.getElementById(id);

	var image = blend.firstChildImage();

    startBlending(image, speed, pause, caption);
}

//make image a block-element and set the caption
function startBlending(image, speed, pause, caption) {
	
	image.style.display = 'block';
	
	if(caption != null) {
        document.getElementById(caption).innerHTML = image.alt;
    }

	continueFadeImage(image, 0, speed, pause, caption);
}

//set an increased opacity and check if the image is done blending
function continueFadeImage(image, opacity, speed, pause, caption) {

	opacity = opacity + 3;

	if(opacity < 98) {

		setTimeout(function() {fadeImage(image, opacity, speed, pause, caption)}, speed);
	
	} else {
	    //if the image is done, set it to the background and make it transparent
		image.parentNode.style.backgroundImage = "url("+image.src+")";
		image.setOpacity(0);
		//get the next image and start blending it again
		image = getNextImage(image);
		setTimeout(function() {startBlending(image, speed, pause, caption)}, pause);		
	}
}

//set the opacity to a new value and continue the fading
function fadeImage(image, opacity, speed, pause, caption) {
	
	image.setOpacity(opacity);
	continueFadeImage(image, opacity, speed, pause, caption);
}
