(function($) {
	$.fn.fadeContent = function(options) {
		var settings = {
			'interval'           : 4000,
			'speed'              : 2000,
			'fader_item'         : '.fader-item',
			'controls_enabled'   : false,
			'controls_container' : '#fader-controls'
		};
		
		return this.each(function() {
			if (options) {
				$.extend(settings, options);
			}
			
			var fadeInterval   = false;
			var inst           = this;
			var faderContainer = $(this);
			
			this.curr_id       = '';
			this.fading        = false;
			
			this.fadeItem = function(fade_to_item) {
				var current_speed = settings.speed;
				
				// Fetch current visible item
				if (inst.curr_id == '') {
					inst.curr_id = faderContainer.find(settings.fader_item + ':visible').attr('id');
				}
				
				// Fade target set?
				if (fade_to_item == undefined) {
					// If not, automatically find the next item to fade to
					
					// Fetch next item
					var next_div = $('#' + inst.curr_id + ' ~ ' + settings.fader_item + ':first');
					
					// If next item doesn't exist, fetch the first item
					if (next_div.length == 0) {
						next_div = faderContainer.find(settings.fader_item + ':first');
					}
				} else {
					var next_div  = fade_to_item;
					current_speed = 200;
				}
			
				// If next item and current item are the same, don't fade
				if (inst.curr_id != next_div.attr('id')) {
					if (inst.fading == 0) {
						inst.fading = 1;
			
						// Switch the z-index
						$('#' + inst.curr_id).css('z-index', '10');
						next_div.css('z-index', '11');
						
						// Change the controls
						if (settings.controls_enabled) {
							$(settings.controls_container + ' a').removeClass('active');
							$(settings.controls_container + ' a[rel="' + next_div.attr('id') + '"]').addClass('active');
						}
						
						// And fade in the next item
						next_div.fadeIn(current_speed, function() {
							
							// Done fading? Hide the previous item
							$('#' + inst.curr_id).hide();
							inst.curr_id = next_div.attr('id');
							inst.fading = 0;
						});
					}
				}
			}
			
			// Controls enabled?
			if (settings.controls_enabled) {
				$(settings.controls_container).css('z-index', '12');
				$(settings.controls_container + ' a').click(function() { return false; });
				$(settings.controls_container + ' a').hover(
					function() {
						// Stop fading interval on control mouseover
						clearInterval(fadeInterval);
						inst.fadeItem($('#' + $(this).attr('rel')));
					},
					function() {
						// Restart fading interval on control mouseout
						inst.setTimer();
					}
				);
			}
			
			this.setTimer = function() {
				fadeInterval = setInterval(function() { 
					inst.fadeItem();
				}, settings.interval);
			}
			
			this.setTimer();
		});
	}
})(jQuery);
