var scroll1;
var scroll2;
var timeout;
var li;
var pause;
var pauseindex = 2;
var containeroffset;

function FindY(obj)
{
	var curtop = 0;
	
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return curtop;
}

function InitScroller()
{
	var container = document.getElementById('headlinelist');
	containeroffset = FindY(container);
	
	scroll1 = document.getElementById('scroll1');
	scroll1.style.top = '1px';
	
	var l = scroll1.cloneNode(true);
	l.id = 'scroll2';
	container.appendChild(l);
	
	li = container.getElementsByTagName('li');
	pause = li[pauseindex];
	
	scroll2 = document.getElementById('scroll2');
	scroll2.style.top = scroll1.offsetHeight + 'px';
	
	var a = container.getElementsByTagName('a');
	
	// Cannot use mouseover pausing in Safari because it fires both events on mouseover (?!!)
	if(navigator.vendor && navigator.vendor.indexOf('Safari'))
	{
		scroll1.speed = 2;
		scroll2.speed = 2;
	}
	else
	{
		for(var x=0; x<a.length; x++)
		{
			a[x].onmouseover = function() { clearTimeout(timeout); }
			a[x].onmouseout = function() { ScrollNews() };
		}
		
		scroll1.speed = 3;
		scroll2.speed = 3;
	}
	
	scroll1.active = false;
	scroll2.active = true;

	timeout = setTimeout(ScrollNews, 2000);
}

function ScrollNews()
{
	if(scroll2.active)
	{
		if(parseInt(scroll2.style.top, 10) <= 0)
		{
			scroll1.style.top = scroll2.offsetHeight + 'px';
			scroll1.active = true;
			scroll2.active = false;
		}
	}
	else if(scroll1.active)
	{
		if(parseInt(scroll1.style.top, 10) <= 0)
		{
			scroll2.style.top = scroll1.offsetHeight + 'px';
			scroll2.active = true;
			scroll1.active = false;
		}
	}
	
	scroll1.style.top = (parseInt(scroll1.style.top, 10) - 3) + 'px';
	scroll2.style.top = (parseInt(scroll2.style.top, 10) - 3) + 'px';
	
	var pausey = parseInt(FindY(pause), 10) - containeroffset;
	
	// If the item to pause on has reached the top of the container
	if(pausey <= 3)
	{
		// Tidy up and get it to 1px from the top
		while(pausey > 1)
		{
			scroll1.style.top = (parseInt(scroll1.style.top, 10) - 1) + 'px';
			scroll2.style.top = (parseInt(scroll2.style.top, 10) - 1) + 'px';
			pausey--;
		}
		
		// Move the pause index on 3
		pauseindex += 3;
		
		if(pauseindex < li.length)
		{
			pause = li[pauseindex];
		}
		else
		{
			// We've gone past the end, reset the index
			pauseindex = 2;
			pause = li[pauseindex];
		}
		
		timeout = setTimeout(ScrollNews, 3000);
	}
	else
	{
		timeout = setTimeout(ScrollNews, 35);
	}
}