/* 
 * Random Child (0.2)
 * by Mike Branski (www.leftrightdesigns.com)
 * mikebranski@gmail.com
 *
 * Copyright (c) 2008 Mike Branski (www.leftrightdesigns.com)
 * Licensed under GPL (www.leftrightdesigns.com/library/jquery/randomchild/gpl.txt)
 *
 * NOTE: This script requires jQuery to work.  Download jQuery at www.jquery.com
 *
 * CHANGELOG: 	0.2 - Added auto rotation, active class
 * 				0.1 - Initial code
 * 
 * POSSIBLE ADDITIONS: 	Accept an argument for the number of children to display.
 * 
 * 						Provide a start/end range, and displayOutsideOfRange parameter 
 * 		 				that would determine if items outside of the given range are visible or not.
 * 
 *						Add a pause on hover option.
 * 
 */

jQuery.fn.randomChild = function(settings) {
	var settings = jQuery.extend({}, jQuery.fn.randomChild.defaults, settings);
	
	return this.each(function(){
		var e = this;
		var c = jQuery(e).children().length;
		var r = settings.random === true ? Math.ceil(Math.random() * c) : 1;
		var n = r;
		var p = false;
		
		// initial visible element
		jQuery(e).children().hide().parent().children(':nth-child(' + r + ')').show().addClass(settings.visibleClass);
		
		if(settings.autoRotate === true) {

			setInterval(function(){

				if(settings.random === true) {
					while (n == r) {
						n = Math.ceil(Math.random() * c)
					}
				} else {
					n = r + 1 <= c ? r + 1 : 1;
				}
				
				if(p === false) {
					jQuery(e).children(':nth-child(' + r + ')').fadeOut("slow", function(){
						jQuery(this).removeClass(settings.visibleClass);
						jQuery(this).parent().children(':nth-child(' + n + ')').fadeIn("slow", function(){
							$(this).addClass(settings.visibleClass);
						});
					});
				}

				r = n;

			}, settings.interval);
		}
	});
};

jQuery.fn.randomChild.defaults = {
	autoRotate: false, 		// bool
	interval: 8000,			// int
	random: true,			// bool
	visibleClass: 'current' // string
}
