var mouseInside = false;

var delay = 40; // delay in milliseconds
var delta = 1;  // ticker delta in pixels

var timeoutSet = true;

function makeTickerAnimator(spans) {
	function tickerAnimator() {
		spans.each(function(x) {
			timeoutSet = false;

			span = spans.slice(x,x+1);
			oldLeft = span.css("left");
			oldLeft = oldLeft.substr(0,oldLeft.indexOf("px"));
			span.css("left", (oldLeft-delta)+"px");

			runWidth = span.width();
			if(oldLeft < (0-runWidth)) {
				span.css("left", (runWidth*spans.size()+Number(oldLeft))+"px");
			}
		});

		if(!mouseInside && !timeoutSet) {
			timeoutSet = true;
			setTimeout(tickerAnimator, delay);
		}
	}
	return tickerAnimator;
}

$(document).ready(function() {
	$.get("ticker_messages.html", function(data) {
		// format the messages
		var messages = data.split("\n");
		var allMessages = "";
		for(x in messages) {
			message = messages[x].replace(/^\s*(.*)\s*$/, '$1');
			if(message != "") allMessages += "&nbsp;|&nbsp;"+message;
		}

		// inject the messages
		var spans = new Array();

		// inject the first run of messages
		$("#ticker").append('<span>'+allMessages+'</span>');

		// how many runs do we need?
		var runWidth = $("#ticker>span").width();
		var runs = Math.ceil($('#ticker').width()/runWidth)+1;

		// inject the extra runs
		span = $("#ticker>span").slice(0,1);
		for(i = 1; i < runs; i++) {
			span.clone().css("left", (i*runWidth)+"px").appendTo("#ticker");
		}

		// create the animator function
		animator = makeTickerAnimator($("#ticker>span"));

		// set event handlers for mouse over
		$("#ticker").mouseover(function(e) {
			if(!mouseInside) mouseInside = true;
		});
		$("#ticker").mouseout(function(e) {
			if(mouseInside) {
				mouseInside = false;
				if(!timeoutSet) animator();
			}
		});

		animator();
	});
});


