/**
 * @author Rygor Kharytanovich
 * @extends jquery
 */

jQuery.fn.extend({
	livechat: function (options) {
		
		if (this) {
			
			var me = this,
				options = options || {},
				titleElement = $(this).find('.hdr .title'),
				itemsElement = $(this).find('.items'),
				itemsContainer = $(this).find('.items-container');
			
			options.numVisible = (options.numVisible || 3);
			options.delay = (options.delay || 5);
			
			var getItemsHeight = function () {
				var itemsHeight = 0,
					items = $(me).find('.item');
				for (var i = 0; i < options.numVisible; i++) {
					itemsHeight += getItemHeight(items[i]);
				}
				
				return itemsHeight;
			}
			
			
			var getItemHeight = function (item) {
				return $(item).outerHeight() + 
					parseInt($(item).css('marginTop')) + 
					parseInt($(item).css('marginBottom'))				
			}
			
			itemsElement.height(getItemsHeight());
			
			setInterval(function () {
				
				var item = $(me).find('.item:last');
				
				$(itemsContainer)
					.prepend(item)
					.css('marginTop', "-" + getItemHeight(item) + 'px')
					.animate({
						marginTop: 0
					}, 1000, "swing");
					
				titleElement.addClass('title-newmsg');
				setTimeout(function () {
					titleElement.removeClass('title-newmsg');
				}, 2000);
				
				$(itemsElement).animate({
					height: getItemsHeight()
				}, 1000, "swing");
				
			}, options.delay * 1000);
			
		}
		
	}
}) 

