
Function.prototype.bind = function(self) {
	if (!self) return this;
	var f = this;
	var args = Array.prototype.slice.call(arguments).slice(1);
	return function() {
		return f.apply(self, args.concat(Array.prototype.slice.call(arguments)));
	};
};


YMSL = {};

YMSL.topic = {
	container: null,
	items    : null,
	timer    : null,
	offset   : 0,

	setup: function() {
		var self = this;
		var container = this.container = $('#topic .items');
		var items = $('li', container);
		this.items = items.clone();

		container
			.append(items.eq(0).clone())
			.prepend(items.eq(items.length - 1).clone());
		this.animate_handler();

		$(window)
			.resize(function() {
				self.offset = ($(this).width() - 950) / 2;
				container.css('margin-left', self.offset - 970);
				var height = Math.max(
					$(window).height(),
					$().height(),
					$('body').height()
				);
				$('#topic-background').height(height);

				if ($.browser.msie)
					$('#topic-background-overlay').css({
						position: 'absolute',
						height  : height,
						opacity : 0.65
					});
			})
			.resize();

		$('#topic-navigation')
			.find('.prev').click(this.prev.bind(this)).end()
			.find('.next').click(this.next.bind(this));
	},

	prev: function() {
		var container = this.container;

		var n = parseInt($('li:last', container).attr('class').replace(/\D+/, ''), 10);
		n = (n == (this.items.length - 1)) ? 0 : n + 1;
		this.items.eq(n).clone().appendTo(container);

		var li = $('li:first', container);
		container.animate({ marginLeft: this.offset - 970 * 2 }, 600, 'swing', this.animate_handler.bind(this, li));
	},

	next: function() {
		var container = this.container;

		var n = parseInt($('li:first', container).attr('class').replace(/\D+/, ''), 10);
		n = (n == 0) ? (this.items.length - 1) : n - 1;

		var li = $('li:last', container);
		container
			.prepend(this.items.eq(n).clone())
			.css('margin-left', this.offset - 970 * 2)
			.animate({ marginLeft: this.offset - 970 }, 600, 'swing', this.animate_handler.bind(this, li));
	},

	animate_handler: function(li) {
		if (li) li.remove();
		var src = $('li img', this.container).eq(1).attr('src');
		$('#topic-background img').attr('src', src);

		this.container.css({
			width     : 970 * (this.items.length + 3), // +1
			marginLeft: this.offset - 970
		});

		clearInterval(this.timer);
		this.timer = setInterval(this.prev.bind(this), 1000 * 15);
	}
};
