/* jquery.simpleSpy.js
 * Created December 2, 2008
 * Editted April 19, 2009
 *
 * Christian L. Schultz (SCHULTZconcepts)
 * Creative Commons Licensing
 * 
 * Creates a slide down effect trimming a long list of li elements inside an ul or ol
 * to a specified number of elements.  Proceeds to slide the last into the top and 
 * drop the bottom element in a carasel fashion.
 *
 * EDIT: Effect pauses when the mouse enters the spy area.  This functionality now
 * allows for items to be focused on within the spy area.
 *
 * USAGE: $('ul').simpleSpy(limit, interval, location)
 * limit = the number of li elements to be displayed at once
 * interval = the time before the loop repeats in milliseconds
 * location must be set, it is the location of the file that creates the content to
 *   applied the spy...typically a PHP script reading from SQL or RSS
 *
 */

(function($) {

$.fn.simpleSpy = function(limit, interval, location) {
	limit = limit || 4;
	interval = interval || 4000;
	location = location || '../includes/homeSpyHelper.php';
	
	function getSpyItem($source) {
		var $items = $source.find('> li');
		
		if($items.length == 1) {
			// do ajax hit to get some more
			$source.load(location);
		} else if ($items.length == 0) {
			return false;
		}
		
		// grab the first item, and remove it from the $source
		return $items.filter(':first').remove();
	}
	
	return this.each(function () {
		var $list 			= $(this),
			running 		= true,
			height			= $list.find('> li:first').height();
			
		var $source = $('<ul />').hide().appendTo('body');
		
		$list.wrap('<div class="spyWrapper" />').parent().css({ height : height * limit });

		$list.find('> li').filter(':gt(' + (limit - 1) + ')').appendTo($source);
		
		$list.bind('stop', function() {
			running = false;
		}).bind('start', function () {
			running = true;
		});
		
		function spy() {
			if(running) {
				var $item = getSpyItem($source);

				if($item != false) {
					// insert a new item into the page, hidden
					var $insert = $item.css({
						height: 0,
						opacity: 0,
						display: 'none'
					}).prependTo($list);

					// fade the LAST item out
					$list.find('> li:last').animate({ opacity : 0}, 1000, function() {
						// increase the height of the NEW first item into page
						$insert.animate({ height : height }, 1000).animate({ opacity : 1 }, 1000);
						// remove bottom element from page
						$(this).remove();
					});

				} 
				
			}
			
			// Loop the effect
			setTimeout(spy, interval);
		}
		
		// Call the effect initial time after the interval has passed
		var intervalAdjusted = interval / 2;
		setTimeout(spy, intervalAdjusted);
	});
};
	
})(jQuery);
