(function($) {
	
	$.fn.contentfade = function(options) {
		
		// setup overriedes for our options
		options = $.extend({
			startIndex: 0,
			duration: 5000,
			transTime: 1000,
			nextId: '#next',
			prevId: '#prev'
		}, options)
		
		// return an each function so we 
		// can use this more then once
		// on each page
		return this.each(function(){
			
			// create some variables
			var slider = $(this),
			children = slider.children('.slides'),
			tabs = jQuery('#slideTabs').children(),
			z = 0,
			index = options.startIndex,
			interval,
			intrans = false,
			prev = null;
			
			// start everything off from here, call out function to move things next
			interval = setTimeout(function(){
				dofade('next');
			}, options.duration);
			
			// set the position of our container and the child elements
			slider.css('position', 'relative');
			children.css({'z-index' : z, 'position' : 'absolute', 'top' : 0, 'left' : 0, 'display' : 'none'});
			children.eq(index).css({'z-index' : 8, 'display' : 'block'});
			children.eq(index).children('div').show();
			tabs.eq(index).addClass('activeTab');
			
			jQuery('.slideTab').click(function() {
				prev = index;
				//index = jQuery('#slideTabs .slideTab').index(this)-1;
				index = jQuery(tabs, '#slideTabs').index(this);
				//console.log(next);
				console.log(index);
				
				clearTimeout(interval);
				dofade('next');
			});
			
			jQuery(options.nextId+', '+options.prevId).click(function() {
				
				if(!intrans) {
					clearTimeout(interval);
					dofade(jQuery(this).text());
				}
				
				return false;
			});
			
			var dofade = function(direction) {
				intrans = true;
				
				if(direction == 'next') {
					next = ((index+1) > (children.length-1)) ? 0 : index+1;
				} else {
					next = ((index-1) < 0) ? children.length-1 : index-1;
				}
				
				if(prev != null) {
					next = index;
					index = prev;
					prev = null;
				}
								
				children.eq(next).css('z-index', 1);
				jQuery('.slide_content').hide();
				tabs.removeClass('activeTab');
				tabs.eq(next).addClass('activeTab');
				
				children.eq(next).fadeIn(options.transTime);
				children.eq(index).fadeOut(options.transTime, function() {
					
					children.eq(next).css('z-index', 8);
					jQuery(this).css({'z-index' : 0});
					intrans = false;
									
					setTimeout(function() {
						jQuery('.slide_content').hide();
						children.eq(next).children('div').show();
					}, 500);
					
				});
				
				
				if(!(index == next)) {
					interval = setTimeout(function(){
						dofade('next');
					}, options.duration);
				}
				index = next;
			}
			
		});
	}
	
})(jQuery);
