/*global Class, $, $$, Event, Ticker */
Ticker = Class.create(
{

	id: null,
	delay: 3000,
	speed: 30,
	prefix: 'Latest News: ',
	messages: [],

	offset:  -1,
	current: null,
	chunk: null,

	initialize: function (id) {
		this.id = id;
		this.anchor = document.createElement('a');
		this.anchor.setAttribute('id', this.id);
		this.anchor.href =  '#';
		this.anchor.style.display = 'block';
	},

	iterate: function ()
	{
		this.offset = ((this.offset + 1 < this.messages.length) ? this.offset + 1 : 0);
		this.current = this.messages[this.offset];
		this.anchor.href = this.current[1];
		this.chunk = 0;
		this.display();
		return true;
	},

	display: function ()
	{
		this.chunk++;
		if (this.chunk === this.current[0].length) {
			this.message = this.current[0];
		} else {
			this.message = this.current[0].substr(0, this.chunk) + '_';
		}

		$(this.id).update('<span class="prefix">' + this.prefix + '</span>' + this.message);

		if (this.chunk === this.current[0].length) {
			setTimeout(this.iterate.bind(this), this.delay);
		} else {
			setTimeout(this.display.bind(this), this.speed);
		}
		return true;
	},

	setDelay: function (milliseconds)
	{
		this.delay = milliseconds;
		return true;
	},

	setSpeed: function (milliseconds)
	{
		this.speed = milliseconds;
		return true;
	},

	setPrefix: function (prefix)
	{
		this.prefix = prefix;
		return true;
	},

	add: function (message, url)
	{
		this.messages.push([message, url]);
		return true;
	},

	attachTo: function (elementId)
	{
		if (!elementId || null === $(elementId)) {
			return false;
		}
		var items = $$('.ticker-items')[0];

		$(items).select('a').each(function (element) {
			this.add(element.innerHTML, element.href);
		}.bind(this));
		$(elementId).insert(this.anchor);
		setTimeout(this.iterate.bind(this), this.speed);
		return true;
	}

});
