
(function($){
	$.fn.spy = function(limit, interval, direction){
		// Default parameters 
		limit = limit || 4; // Items to show
		interval = interval || 4000; // Please dont use a number less than 4000 (4sec)
		direction = direction || "vertical";
		var list = $(this);
		var items = [];
		var height = list.find(">li:first").height();
		var width = list.find(">li:first").width();
		list.find(">li").each(function () {
			items.push("<li>" + $(this).html() + "</li>");
		});
		
		//var currentItem = limit + 1; // the current item to be hidden
		var total = items.length;
		var currentItem = Math.min(limit -1, total -1); // the current item to be hidden
		if (total == 0) 
		  return;
		  
		return this.each(function () {
			
			// if (total <= interval) return;
			list.find('>li').filter(':gt(' + (limit - 1) + ')').remove();
			
			function start() {
				var currentItemElement = $(items[currentItem]);
				if (direction == "vertical") {
					currentItemElement.css({height: 0});
				} else {
					currentItemElement.css({width: 0});
				}

				var $insert = currentItemElement.css({
					opacity: 0,
					display: "none",
					height: 0
				}).prependTo(list);
				
				
				list.find(">li:last").animate({ opacity: 0}, 1000, function() {
					if (direction == "vertical") {
						$insert.animate({ height: height}, 1000).animate({opacity: 1}, 1000);
						$(this).animate({ height: 0}, 1000, function() {
							$(this).remove();
						});
					} // horizontal 
					else {
						$insert.animate({ width: width}, 1000).animate({opacity: 1}, 1000);
						$(this).animate({ width: 0}, 1000, function() {
							$(this).remove();
						});
					}
				});
				
				currentItem--;
				if (currentItem < 0) {
					currentItem = total -1;
				}
				
				setTimeout(start, interval);
			}
			
			start();
		
		});
		
	}
})(jQuery);
