var CMBlender = function(windowid,mainimageid,webroot){
	this.items = [];
	this.container = document.getElementById(windowid);
	this.mainimage = document.getElementById(mainimageid);
	this.mainlink = this.mainimage.parentNode;
	this.webroot = webroot;
	this.limit = 0;
	this.speed = 1000;
	this.iteration = 0;
	this.timer = null;
	this.loadtimer = null;
	this.blendingtimers = null;
	this.objid = 'Blender_' + CMBlender.Instance++;
	eval(this.objid + '=this;');
}
CMBlender.Instance = 1;
CMBlender.prototype.startAutoAnimation = function(){
	this.blendimage();
}
CMBlender.prototype.startAnimation = function(index){
	var preloaded_file = new Image();
	this.mainimage.onload = ''; // removing onload event handler
	if(this.timer) clearTimeout(this.timer);
	if(this.loadtimer) clearTimeout(this.loadtimer);
	this.cancelBlend();
	
	preloaded_file.onload = eval("new function(){ "+this.objid+".blendimage("+index+"); }");
	preloaded_file.src = this.items[index].image;
	return;
}
CMBlender.prototype.blendimage = function(/*index*/) {
	this.limit = this.items.length - 1;
	var speed = Math.round(this.speed / 100),
	timer = 0,
	previous = this.iteration;
	
	//set the current image as background and change opacity on image to 0
	this.container.style.backgroundImage = "url(" + this.mainimage.src + ")";
	this.changeOpac(0,this.mainimage.id);
	
	
	//calculating current image index
	if(arguments.length){
		this.iteration = arguments[0];
		if(this.iteration > this.limit) this.iteration = this.limit;
	}
	else this.iteration = (++this.iteration)>this.limit? 0:this.iteration;
	
	//setting active thumbnail
	var spans = this.container.getElementsByTagName('span');
	spans[previous].firstChild.style.display = 'none';
	spans[this.iteration].firstChild.style.display = 'block';

	//loading the current image
	this.mainimage.src = this.webroot+this.items[this.iteration].image;
	this.mainlink.href = this.items[this.iteration].url;
	
	//applying the fade-in
	this.blendingtimers = [];
	for(i = 1; i <= 100; i++) {
		this.blendingtimers[i] = setTimeout(this.objid+".changeOpac(" + i + ",'"+this.mainimage.id+"')",(timer*speed));
		timer++;
	}
}	
	//change the opacity for different browsers
CMBlender.prototype.changeOpac = function(opacity, id) {
	var Imgobject = document.getElementById(id).style; 
	Imgobject.opacity = (opacity / 100);
	Imgobject.MozOpacity = (opacity/100);
	Imgobject.KhtmlOpacity = (opacity / 100);
	Imgobject.filter = "alpha(opacity=" + opacity + ")";
}	
	//change the opacity for different browsers
CMBlender.prototype.cancelBlend = function() {
	if(this.blendingtimers){
		for(i = 1; i <= 100; i++) {
			if(this.blendingtimers[i]) clearTimeout(this.blendingtimers[i]);
		}
	}
	this.blendingtimers = null;
}

CMBlenderItem = function(image,thumb,url,title){
	this.image = image;
	this.thumb = thumb;
	this.url = url==''?'#':url;
	this.title = title;
}
	
