var ForwardToolbox = {
	create: function(module) {
		for (var property in module) {
			if (typeof module[property] != "function") continue;

			module[property] = this.bindMethod(module[property], module);
		}

		if (module.initialize)
			this.registerLoadEvent(module.initialize);

		return module;
	},
	bindMethod: function(method, owner) {
		return function() {
			return method.apply(owner, arguments);
		}
	},
	registerLoadEvent: function(callback) {
		var previous = window.onload;

		window.onload = previous ? function() {callback(); previous()} : callback;
	}
}

var HeadlinesTicker = ForwardToolbox.create({
	initialize: function() {
		var container = document.getElementById("ticker");

		if (!container) return;

		container.onmouseover = this.pause;
		container.onmouseout = this.resume;

		this.guide = 100;
		this.destination = 0;

		this.items = container.getElementsByTagName("li");
		this.currentItem = this.items[0];

		window.onblur = this.pause;
		window.onfocus = this.resume;

		this.timer = window.setInterval(this.increment, 8000);
	},
	increment: function() {
		if (this.paused) return;

		for (var i = 0; i < this.items.length; i++) {
			if (this.items[i] !== this.currentItem) continue;

			this.nextItem = this.items[i + 1] || this.items[0];
		}

		this.animate();
	},
	animate: function() {
		this.guide += (this.destination - this.guide) / 3;

		var k = Math.round(this.guide);

		this.currentItem.style.opacity = k / 100;

		if (k != this.destination) {
			window.setTimeout(this.animate, 40);

		} else if (this.nextItem !== this.currentItem) {
			this.currentItem.className = "";
			this.currentItem = this.nextItem;
			this.currentItem.style.opacity = 0;
			this.currentItem.className = "active";

			this.destination = 100 - this.destination;

			window.setTimeout(this.animate, 40);

		} else {
			this.guide = this.destination;
			this.destination = 100 - this.guide;
		}
	},
	pause: function() {
		this.paused = true;
	},
	resume: function() {
		this.paused = false;
	}
});

