function $id(x){return document.getElementById(x);}
function $tag(x,y){return y.getElementsByTagName(x);}


function Slideshow(screen,controls){
	
	////PROPERTIES
	this.screen=screen;
	this.slides=screen.childNodes;
	this.controls=controls;
	this.timeout=[];
	this.opac;
	this.opacdelta=10;
	this.opacrate=20;
	this.delay=4000;
	this.interval;
	this.current;
	var slideshow=this;
	
	////METHODS
	this.advance=function (){
		if(slideshow.interval)clearInterval(slideshow.interval);
		slideshow.opac=100;
		if(slideshow.screen.lastChild.previousSibling.loaded)slideshow.interval=setInterval(function(){slideshow.fadeNext();},slideshow.opacrate);
		clearTimeout(slideshow.timeout);
		slideshow.timeout=setTimeout(function(){slideshow.advance();},slideshow.delay);
	}
	this.fadeNext=function(){
		var item=slideshow.screen.lastChild;
		slideshow.screen.lastChild.previousSibling.style.visibility="visible";
		if(slideshow.opac<=0){
			clearInterval(slideshow.interval);
			slideshow.opac=100;
			slideshow.screen.firstChild.style.visibility="hidden";
			slideshow.screen.insertBefore(item,slideshow.screen.firstChild);
			if(slideshow.current)slideshow.current.id="";
			slideshow.current=slideshow.screen.lastChild.btn;
			slideshow.current.id="current";
			
		}else{
			slideshow.opac=slideshow.opac-slideshow.opacdelta;
		}
		item.style.opacity = slideshow.opac/100;
		item.style.filter  = "alpha(opacity=" + slideshow.opac + ")";
	}
	this.play=function(){
		slideshow.stop();
		slideshow.timeout=setTimeout(slideshow.advance,slideshow.delay);
	}
	this.stop=function(){
		clearTimeout(slideshow.timeout);
		clearInterval(slideshow.interval);
		slideshow.screen.lastChild.style.opacity = 1.0;
		slideshow.screen.lastChild.style.filter  = "alpha(opacity=100)";
		
	}
	
	////INIT
	var btn=$tag("button",controls)[0];
	for(var i=this.slides.length-1;i>=0;i--)if(this.slides[i].nodeType!=1)screen.removeChild(this.slides[i]);
	for(var i=0;i<this.slides.length;i++){
			var newbtn=btn.cloneNode(true);
			newbtn.slide=this.slides[i];
			newbtn.ondblclick=function(){
				//slideshow.play();
			}
			newbtn.onclick=function(){
				slideshow.stop();
				if(slideshow.current)slideshow.current.id="";
				slideshow.current=this;
				this.id="current";
				this.slide.style.visibility="visible";
				while(slideshow.screen.lastChild!=this.slide)slideshow.screen.insertBefore(slideshow.screen.lastChild,slideshow.screen.firstChild);
				slideshow.play();
			};
			this.slides[i].btn=newbtn;
			controls.insertBefore(newbtn,this.controls.firstChild);
	}
	controls.removeChild(btn);
	this.current=this.slides[this.slides.length-1].btn;
	this.current.id="current";
	this.screen.lastChild.style.visibility="visible";
	
	this.timeout=setTimeout(slideshow.advance,this.delay);
}
