/* Carousel for the Friendfeed entries */

$(document).ready(function(){
	$('.vCarousel').carousel();
	$('.hCarousel').carousel({direction:'horizontal',display:1});
});

(function($){
		  
	$.fn.carousel = function(opts) {
		
		var defaults = {
			direction:'vertical',
			titles:['previous feed','next feed'],
			display:3
		}
		var options = $.extend(defaults,opts);
		
		return $(this).each(function(){
			
			var $this = $(this);
			
			$this.append('<ul class="feedNav"><li class="previous"><a title="'+options.titles[0]+'" href="#"></a></li><li class="next"><a title="'+options.titles[1]+'" href="#"></a></li></ul>');
			
			$('li.previous a',this).click(function(){move(1);return false;});
			$('li.next a',this).click(function(){move(-1);return false;});
			
			$('.friendfeed.widget .feed .entry .title a').attr('target', '_blank');
			
			var $clusters = $(".feed",this).children();
			var len = $clusters.length;
			
			if(options.direction == 'horizontal') {
				var increment = $clusters.width(); // amount of pixels by which the feed container has to move
			}
			else if(options.direction == 'vertical') {
				var increment = $clusters.height();
			}
		
			var limits = [increment*(options.display-len) , 0];
			var active = true;
			
			
			var move = function(dir){
				var cur = current();
				cur += dir*increment;
				
				cur = Math.max(cur,limits[0]);
				cur = Math.min(cur,limits[1]);
				
				if (cur == limits[1]) {
					$(".feedNav li.previous a",$this).hide();
				}
				else if (cur == limits[0]) {
					$(".feedNav li.next a",$this).hide();
				}
				else {
					$(".feedNav li a",$this).show();
				}
				if(active) {
					active = false;
					set(cur);
				}
			}
			
			var current = function(){
				if(options.direction == 'horizontal') {
					current = function() {
						return $(".feed",$this).position().left;
					}
				}
				else if(options.direction == 'vertical') {
					current = function() {
						return $(".feed",$this).position().top;
					}
				}
				else {
					current = function(){return 0;}
				}
				return current();
			}
			
			var set = function(pos){
				if(options.direction == 'horizontal') {
					set = function(p) {
						$(".feed",$this).animate({left: p+'px'},function(){active=true;});
					}
				}
				else if(options.direction == 'vertical') {
					set = function(p) {
						$(".feed",$this).animate({top: p+'px'},function(){active=true;});
					}
				}
				else {
					set = function(){}
				}
				set(pos);
			}
			
			move(0);
			
		});
	}
})(jQuery);
