/* =========================================================

innerfade.js

Date: 2008-04-29
Author: Plus Three LLC (http://plusthree.com/)

Based heavily on jquery.innerfade.js by Torsten Baldes 
(http://medienfreunde.com), which in turn is based on the work of 
Matt Oakes (http://portfolio.gizone.co.uk/applications/slideshow/) 
and Ralf S. Engelschall (http://trainofthoughts.org/).

Changes include limiting rotation to sequential/fade, and enabling 
a control menu.

// ========================================================= */

(function($) {

	$.fn.innerfade = function(options) {
		return this.each(function() {   
			$.innerfade(this, options);
		});
	};

	$.innerfade = function(container, options) {
		var settings = {
			'speed': 2000,
			'timeout': 2000,
			'containerheight': 'auto',
			'tracker': null,
			'trackerclass': null
        };
		if (options) {
			$.extend(settings, options);
		}

		var elements = $(container).children();
		$(container).data('num_elements', elements.length);

		if (elements.length > 1) {

			// set css on parent and elements
			$(container).css('position', 'relative').css('height', settings.containerheight);
			for (var i = 0; i < elements.length; i++) {
				$(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
			};

			var next, current;
			if ($(container).data('next') == null) { // first run
				next = 1;
				current = 0;
				$(elements[0]).show();
				
				var timer = setTimeout(function() {
					$.innerfade.next(container, elements, settings, next, current);
				}, settings.timeout);
				$(container).data('timer', timer);
				$(container).data('next', next);
			} else {
				next = $(container).data('next');
				if ( next == 0 ) {
					current = elements.length - 1;
				} else {
					current = next - 1;
				}
				$.innerfade.next(container, elements, settings, next, current);
			}
		}
    };

    $.innerfade.next = function(container, elements, settings, next, current) {
		$(elements[current]).fadeOut(settings.speed);
		$(elements[next]).fadeIn(settings.speed, function() {
			if (settings.trackerclass) {
				$('#' + settings.tracker + ' a').removeClass(settings.trackerclass);
				$('#' + (current + 1)).addClass(settings.trackerclass);
			}
		});

		// caluculate for next run
		if ((next + 1) < elements.length) {
			next = next + 1;
			current = next - 1;
		} else {
			next = 0;
			current = elements.length - 1;
		}

		var timer = setTimeout((function() {
            $.innerfade.next(container, elements, settings, next, current);
        }), settings.timeout);

		$(container).data('timer', timer);
		$(container).data('next', next);
    };

})(jQuery);
