﻿
var newsTickerElementId = "";
var newsTickerNewsItems = new Array(0);
var newsTickerLinks = new Array(0);

var newsTickerSHORT_DELAY = 25;
var newsTickerLONG_DELAY = 2000;
var newsTickerEPILEPSY_CHAR = "_";

var newsTickerInBetween = false;
var newsTickerComplete = true;
var newsTickerItemNumber = -1;
 
function newsTicker(elementId, newsItems, links) {
	newsTickerElementId = elementId;
	newsTickerNewsItems = newsItems;
	newsTickerLinks = links;
	
	if (document.getElementById) {
		// Output a link that will act as the ticker
		document.write('<a href="#" id="' + newsTickerElementId + '"></a>');
		
		// Get ticking!
		setTimeout('newsTickerTick()', newsTickerSHORT_DELAY);
	}
}

function newsTickerTick() {
	var element = document.getElementById(newsTickerElementId);
	if (element == null) {
		// Try again until it arrives
		setTimeout('newsTickerTick()', newsTickerSHORT_DELAY);
		return;
	}
	
	if (newsTickerComplete) {
		// It's complete, so clear the current text in the element
		element.innerHTML = "";
		newsTickerComplete = false;
		newsTickerInBetween = false;
		
		// And increment which item we're on
		newsTickerItemNumber++;
		if (newsTickerItemNumber >= newsTickerNewsItems.length) {
			newsTickerItemNumber = 0;
		}
		
		// Now change the target of the ticker
		element.href = newsTickerLinks[newsTickerItemNumber];
	}
	
	if (newsTickerInBetween) {
		newsTickerInBetween = false;
		element.innerHTML += newsTickerEPILEPSY_CHAR;
		setTimeout('newsTickerTick()', newsTickerSHORT_DELAY);
	} else {
		newsTickerInBetween = true;
		
		// Strip the in-between stuff off the end
		if ((element.innerHTML.length - newsTickerEPILEPSY_CHAR.length) > 0) {
			element.innerHTML = element.innerHTML.substring(0,
					element.innerHTML.length - newsTickerEPILEPSY_CHAR.length);
		}
		
		// Add a char from the current item
		var toAdd = newsTickerNewsItems[newsTickerItemNumber].charAt(
				element.innerHTML.length);
		
		// If it's an xhtml entity then grab the whole thing
		if (toAdd == "&") {
			toAdd = newsTickerNewsItems[newsTickerItemNumber].substring(
					element.innerHTML.length,
					newsTickerNewsItems[newsTickerItemNumber].indexOf(";",
							element.innerHTML.length));
		}
		
		element.innerHTML += toAdd;
		
		// If this is complete then we'll pause for a bit, otherwise go fast
		if (element.innerHTML.length >=
				newsTickerNewsItems[newsTickerItemNumber].length) {
			newsTickerComplete = true;
			setTimeout('newsTickerTick()', newsTickerLONG_DELAY);
		} else {
			setTimeout('newsTickerTick()', newsTickerSHORT_DELAY);
		}
	}
}
