/*global minY, maxY, maxX, scrolldir, step, delay, timeleft, yPos, stopped, turns, linkname, bannername, banners*/

var thebanner;

function changePos() {
	//alert("yPos="+yPos+",scrolldir="+scrolldir+",minY="+minY+".maxy="+maxY)
	if (scrolldir === 0) {
		return;
	}
	yPos = yPos + scrolldir * step;
	if (yPos < minY) {
		scrolldir = 1;
		yPos = minY;
	}
	if (yPos >= maxY) {
		scrolldir = -1 ;
		yPos = maxY;
	}
	thebanner.style.top = yPos; 
}


function loopfunc()
{
	changePos();
	if ( timeleft > 0) {
		timeleft--;
	} else {
		startscroller();
		return;
	}
	if (stopped != 1) {
		setTimeout(function () {loopfunc();},delay);
	}
}

function startscroller2()
{
	var height=thebanner.height;
	minY=-height;
	timeleft = turns;
	yPos=0;
	if (height <= maxY) {
		scrolldir = 0;
		thebanner.style.top = yPos; 
		setTimeout( function () {startscroller();},timeleft*delay);
	} else {
		scrolldir = -1;
		loopfunc();
	}
}

function startscroller()
{
	thebanner=document.getElementById(bannername);
	var thelink=document.getElementById(linkname);
	var r= Math.floor(Math.random()*banners.length);
	thebanner.src=banners[r][0];
	thelink.href=banners[r][1];
	//500 ms is hopefully enough to load the image
	setTimeout(function () {startscroller2();},500);
}

function startscroll() {
	stopped = 0;
	loopfunc();
}

function stopscroll() {
	stopped=1;
}
