(function ($) {
	var rotateItems = function (jItems, jLinks) {
		var oRttr, pageNo = 0;
		if (!(this instanceof rotateItems)) {
			return new rotateItems(jItems, jLinks);
		}
		oRttr = this;
		this.Pages = [];
		this.curPage = 0;
		this.pageNo = 0;
		this.itAnimated = false,
		this.jLinks = jLinks;
		this.jLinks.each(function (index) {
			var jLink = $(this), pageAdd = -2 + (index * 2) + 1;
			jLink.bind('click.Lister', function () {
				var pageNo = oRttr.curPage + pageAdd;
				if (pageNo >= oRttr.Pages.length || pageNo < 0) {
					return false;
				}
				oRttr.selectPage(pageNo);
			});
		});
		jItems.each(function (index) {
			var jItem = $(this);
			if (index != 0 && index % 5 == 0) {
				pageNo += 1;
			}
			if (!oRttr.Pages[pageNo]) {
				oRttr.Pages[pageNo] = [];
			}
			oRttr.Pages[pageNo].push(jItem);
			if (pageNo > 0) {
				jItem.hide();
			}
		});
		this.updateLinks(oRttr);
	};
	rotateItems.prototype = {
		updateLinks: function () {
			var oRttr = this;
			this.jLinks.each(function (index) {
				var jLink = $(this);
				if (oRttr.curPage == (oRttr.Pages.length - 1) * index) {
					jLink.hide();
				} else {
					jLink.show();
				}
			});
		},
		changeItem: function (pageNo, itemNo) {
			var oRttr = this;
			if (!this.Pages[pageNo] || !this.Pages[this.curPage][itemNo]) {
				this.itAnimated = false;
				this.curPage = pageNo;
				this.updateLinks();
				return false;
			}
			this.Pages[this.curPage][itemNo].fadeOut(150, function () {
				if (oRttr.Pages[pageNo][itemNo]) {
					if (!oRttr.Pages || !oRttr.Pages[oRttr.curPage]) {
						return false;
					}
					oRttr.Pages[pageNo][itemNo].fadeIn()
											   .insertBefore(oRttr.Pages[oRttr.curPage][itemNo]);
				}
			});
			/*170 для того чтобы анимация успевала закончиться до запуска сделующей*/
			setTimeout(function () {
				oRttr.changeItem(pageNo, itemNo + 1);
			}, 170);
		}, selectPage: function (pageNo) {
			if (this.itAnimated) {
				return false;
			}
			this.itAnimated = true;
			this.changeItem(pageNo, 0);
		}
	};
	$(function () {
		var jBoxoffices = $('div.js-boxoffice div.js-item'), jBest = $('div.js-best div.js-item'),
			jNigthClubs = $('div.js-best_nightclub div.js-item')
			jItems = jBest.add(jBoxoffices).add(jNigthClubs);
		jItems.find('> a').each(function () {
			var jLink = $(this), jItem = jLink.parents('div.js-item'),
				jBbl = jItem.find('.js-info_event'), hideTimer = false;
			jLink.add(jBbl).bind('mouseover.Bbl', function () {
				if (hideTimer) {
					clearTimeout (hideTimer);
					hideTimer = false;
				} else {
					jItems.find('.js-info_event:visible').hide();
					jBbl.show();
				}
			}).bind('mouseout.Bbl', function () {
				hideTimer = setTimeout(function () {
					jBbl.hide();
					clearTimeout (hideTimer);
					hideTimer = false;
				}, 400);
			});
		});
		rotateItems(jBest, $('div.js-best_lister span'));
		rotateItems(jNigthClubs, $('div.js-best_nc_lister span'));
	});
})(jQuery);
