/********
*
*   Playhead (minimal version)
*
********/

function Playhead(){
	this.starttime;
}

Playhead.prototype.start = function(){
	this.starttime = new Date();
}

Playhead.prototype.getTime = function(){
	return (new Date()) - this.starttime;
}

/********
*
*   Picture
*
********/

function Picture(elemId){
	this.element = document.getElementById(elemId);
	this.setOpacity(0);
	this.playhead = new Playhead(); // time-based animation: fade duration is the same on all machines
	this.timeout = null;

	var scope = this;

	this.loop = function(){
		var time = scope.playhead.getTime();
		if(scope.state == 'in'){
			value = time / 1500;
			if(value < 1)
				scope.timeout = window.setTimeout(scope.loop, 60);
		}
		if(scope.state == 'out'){
			value = 1 - time/1500;
			if(value > 0)
				scope.timeout = window.setTimeout(scope.loop, 60);
		}
		scope.setOpacity(value);
	}
}

Picture.prototype.setUrl = function(url){
	this.element.src = url;
}


Picture.prototype.fadeIn = function(){
	this.reset();
	this.state = 'in';
	this.loop();
}


Picture.prototype.fadeOut = function(){
	this.reset();
	this.state = 'out';
	this.loop();
}


Picture.prototype.reset = function(){
	window.clearTimeout(this.timeout);
	this.playhead.start();
}


Picture.prototype.setOpacity = function(value){
	this.element.style.opacity = value;
	this.element.style.filter = 'alpha(opacity='+Math.round(100*value)+')';
}


/********
*
*   PictureViewer
*
********/

PictureViewer = {};

PictureViewer.init = function(){
	this.pic1 = new Picture('lower');
	this.pic2 = new Picture('upper');
	this.state = 1;

	this.album;
	this.position;

	this.setAlbum(album);
	if (this.album.length>0)
	{
		this.pic1.setUrl(this.album[0]);
		setTimeout('PictureViewer.next()',3000);
	}
	else
	{
		document.getElementById('upper').style.display = "none";
		document.getElementById('lower').style.display = "none";
	}
}


PictureViewer.setPosition = function(pos){
	pos = pos < 0 ? 0 : pos > this.album.length-1 ? this.album.length-1 : pos;

	this.position = pos;
	if (this.album[this.position] != undefined) {
		this.fadeTo(this.album[this.position]);
	}
}


PictureViewer.next = function(){
	randomgetal = Math.floor(Math.random() * this.album.length);

	this.setPosition(randomgetal);

	if (this.position>=this.album.length-1){
		this.position = -1;
	}

	setTimeout('PictureViewer.next()',3000);
}


PictureViewer.previous = function(){
	this.setPosition(this.position - 1);
}



PictureViewer.setAlbum = function(album){
	this.album = album;
	this.setPosition(0);
}

PictureViewer.fadeTo = function(url){
	if(this.state == 1){
		this.pic1.setOpacity(1);
		this.pic2.setOpacity(0);
		this.pic2.setUrl(url);

		this.pic2.fadeIn();
		this.state = 2;
	}
	else{
		this.pic1.setOpacity(1);
		this.pic1.setUrl(url);
		this.pic2.setOpacity(1);

		this.pic2.fadeOut();
		this.state = 1;
	}
}
