/*-------------------------------------------------------------------------------
	Thanks to http://tympanus.net/codrops/2010/07/21/related-posts-slide-out-boxes/
	Related Post
	Version 1.0
	By Kreatera
	contacto@kreatera.com
	22.10.10
-------------------------------------------------------------------------------*/

(function($){
$.fn.relatedPost = function(options){
	
	var defaults = {
		pos: 0,
		visible: 5
	};
	
	var options = $.extend(defaults, options);
	
	
	$(this).each(function(i){
		
		$list = $(this);
		
		// number of related posts
		var elems_cnt = $(this).children().length;
		if(defaults.visible > elems_cnt)
			defaults.visible = elems_cnt;
		
		/*
			show the first set of posts.
			200 is the initial left margin for the list elements
		*/
		
		loadPost(defaults.pos);
		
		function loadPost(initial){
			$list.find('li').hide().andSelf().find('div.post').css('left',initial+'px');
			var loaded	= 0;
			//show 5 random posts from all the ones in the list. 
			//Make sure not to repeat
			while(loaded < defaults.visible){
				var r 		= Math.floor(Math.random()*elems_cnt);
				var $elem	= $list.find('li:nth-child('+ (r+1) +')');
				if($elem.is(':visible'))
					continue;
				else
					$elem.show();
				++loaded;
			}
			
			//animate them
			var d = 200;
			$list.find('li:visible div.post').each(function(){
				$(this).stop().animate({
					'left':'166px'
				},d += 100);
			});
		}
			
		/**
		* hovering over the list elements makes them slide out
		*/	
		$list.find('li:visible').live('mouseenter',function () {
			$(this).find('div.post').stop().animate({
				'left':'0px'
			},200);
		}).live('mouseleave',function () {
			$(this).find('div.post').stop().animate({
				'left':'166px'
			},200);
		});
		
		/**
		* when clicking the shuffle button,
		* show 5 random posts
		
		$('#rp_shuffle').unbind('click')
						.bind('click',shuffle)
						.stop()
						.animate({'margin-left':'-18px'},700);
						
		function shuffle(){
			$list.find('li:visible div').stop().animate({
				'marginLeft':'60px'
			},200,function(){
				loadPost(-60);
			});
		}		
		*/
	});

};

})(jQuery);
