(function($) {

	$.fn.innerfade = function(options) {
		var $this, opts;

		var options = $.extend({},$.fn.innerfade.defaults,options);

		return this.each(function(){
			$this = $(this);
			opts = $.meta ? $.extend({}, options, $this.data()) : options;
			
			_init();
		});
	
		function _init() {
			opts.pointer = 0;
		
			opts.elements = $this.children();
			if (opts.type == 'random') {
				_shuffleArray();
			}

			_reIndex();
						
			opts.timeoutFunction = setTimeout(function(){
				_change();
			}, opts.timeout);
		}
		
		function _reIndex() {
			$(opts.elements).each(function(k,v){
				if (k > 0){
					$(this).css('z-index',opts.elements.length-k).hide();	
				} else {
					$(this).css('z-index',opts.elements.length-k);
				}
				
			});
		}
		
		function _shuffleArray() {
			var i = opts.elements.length;
			if ( i == 0 ) return false;
			while ( --i ) {
				var j = Math.floor( Math.random() * ( i + 1 ) );
				var tempi = opts.elements[i];
				var tempj = opts.elements[j];
				opts.elements[i] = tempj;
				opts.elements[j] = tempi;
			}
		}
		
		function _change() {
			if(!opts.elements.length || opts.elements.length < 2) {
				clearTimeout(opts.timeoutFunction);
				return;
			}

			var next;
			var maxOffset = opts.elements.length - 1;

			if(opts.pointer == maxOffset) {
				nextPointer = 0;
			} else {
				nextPointer = opts.pointer + 1;
			}

			next = opts.elements[nextPointer];

			if (opts.animationtype == 'slide') {
				$(opts.elements[opts.pointer]).slideUp(opts.speed,function(){
					$(next).slideDown(opts.speed);
				});
			} else {
				$(opts.elements[opts.pointer]).fadeOut(opts.speed);
				$(next).fadeIn(opts.speed);			
			}
			
			opts.pointer = nextPointer;

			opts.timeoutFunction = setTimeout(function(){
				_change();
			}, opts.timeout);
		}
	}

	$.fn.innerfade.defaults = {
		animationtype: 'fade',
		speed : 'normal',
		timeout : 2000,
		type : 'sequence'
	};
})(jQuery);
