(function($){
	
	$.fn.feed = function( options ){
	
		var settings, opts,  working = false , $elements = $(this);
		
		settings = {
			speed : 300,
			duration : 2000 ,
			limit : 6,
			limitTitle : 50,
			scriptPath : "feed.php"
		};
		
		opts = $.extend( settings , options );
		
		var get = function(){
			
			if( working ) return false;
			
			working = true;
			
			$.ajax({
				"url" 		: opts.scriptPath,
				"type"		:"get",
				"dataType"	: "json",
				"cache" 	: false,
				"data"		: { "limit" : opts.limit },
				"success" 	: function( response ){
					
					var html = '<ul>';
					
					for( var i = 0, max = response.items.length; i < max ; i++ ){
						
						var item = response.items[i];
						
						var title = item.title;
						
						if(title.length>opts.limitTitle){
							title = title.substring(0,opts.limitTitle-3)+"...";
						}
						html += "<li><a href='"+item.link+"' target='_blank' >"+title+"</a></li>";
					};
					
					html += '</ul>';
					
					$elements.each(function(){
						
						$(this).html( html ).trigger("feed:init");
						
					});
				},
				"complete" 	: function(){
					
					working = false;
				}
			});
			
		};
		
		get();
		
		return $elements.each(function(){
			
			var $container = $(this),
				$items,
				total,
				current,
				timeout;
			
			$container.bind("feed:init",function(){
				
				clearTimeout(timeout);
				$items = $container.find("li").hide();
				total = $items.size();
				current = 0;
				
				$items.eq(current).fadeIn(opts.speed,function(){
					
					timeout = setTimeout(function(){
						
						$container.trigger("feed:next");
						
					},opts.duration);
				});
				
			});
			
			$container.bind("feed:next",function(){
				
				var next;
				
				if(current == total - 1){
					next = 0;
				}
				else {
					next = current + 1;
				};
				
				$items.eq(current).fadeOut(opts.speed, function(){
					
					$items.eq(next).fadeIn(opts.speed, function(){
						
						current = next;
						
						timeout = setTimeout(function(){
							
							$container.trigger("feed:next");
							
						},opts.duration);
					});
					
				});
			});
			
		});
		
	};
	
})(jQuery);
