if (typeof(m) == "undefined" || !m) {
	var m = {};
}

(function($) {
	m.successBlock = function(el) {
		this.el = el;
		this.config = {
			itemClass : 'item-succ',
			idPrefix : 'item-id-',
			changeTimeout : 3000,
			animateTimeout : 600,
			url : '/catalog/goodbuy/'
		};

		this.newItems = [];
		this.items = [];
		this.interval = null;
		this.position = 0;
	}

	m.successBlock.prototype.setConfig = function(config)
	{
	   this.config = $.extend(this.config, config);
	}

	m.successBlock.prototype.setup = function()
	{
		this.items = $('.' + this.config.itemClass, this.el);
		this.startIteration();
	}

	m.successBlock.prototype.startIteration = function()
	{
		var that = this;

		this.position = 0;
		var ids = this.getItemsId();
		$.post(this.config.url, {current:ids}, function(data) {
			if (typeof(data.items) != 'undefined' && data.items.length > 0) {
				that.newItems = data.items;

				that.interval = setInterval(function() {
					that.itemIteration.call(that);
				}, that.config.changeTimeout);
			}
		}, 'json');
	}

	m.successBlock.prototype.itemIteration = function()
	{
		var that = this;
		var item = $(this.items[this.position]);
		var pos = this.position;

		if (typeof(this.newItems[pos]) == 'undefined') {
			clearInterval(this.interval);
			this.startIteration();
			return;
		}

		item.animate({opacity: 0}, this.config.animateTimeout, function() {
			var newItem = that.newItems[pos];

			item
				.html(newItem.html)
				.attr('id', that.config.idPrefix + newItem.id)
				.animate({opacity: 1}, that.config.animateTimeout);
		});

		if (this.position == (this.items.length - 1)) {
			clearInterval(this.interval);
			this.startIteration();
		} else {
			this.position++;
		}
	}

	m.successBlock.prototype.getItemsId = function()
	{
		var itemsId = [];
		var that = this;

		this.items.each(function(key, val) {
			var id = $(val).attr('id').substr(that.config.idPrefix.length);
			itemsId.push(id);
		});

		return itemsId;
	}
}) (jQuery);
