(function( $ ){

    $.fadingbox = function(element, options) {

        var defaults = {
            autofade : true,
			autofadetime : 3000,
			nextButtonId : '',
			prevButtonId : '',
			fadespeed : 'fast'
        }

        var plugin = this;

        plugin.settings = {}

        var $element = $(element),
        element = element;
		var $children = $element.children('li');
			
        plugin.init = function() {
		
            plugin.settings = $.extend({}, defaults, options);
-
			$element.css('overflow','hidden');
			$children.css({'width':$element.width(),'height':$element.height(),'overflow':'hidden'});
			if (plugin.settings.autofade)
				trigger = setInterval(function() {fade('next');},plugin.settings.autofadetime);
			if (plugin.settings.nextButtonId!='' && plugin.settings.prevButtonId!='') {
				$('#'+plugin.settings.nextButtonId).bind('click',function() {fade('next');});
				$('#'+plugin.settings.prevButtonId).bind('click',function() {fade('prev');});
			}
			
        }
		
		var trigger;
		
		var childrenCount = $children.size();
		var currentIndex = 0;
		
		var fade = function(direction) {
			var targetIndex;
			switch (direction) {
				case 'next':
					if (currentIndex == childrenCount - 1)
						targetIndex = 0;
					else
						targetIndex = currentIndex + 1;
					break;
				default:
					if (currentIndex == 0)
						targetIndex = childrenCount - 1;
					else
						targetIndex = currentIndex - 1;
					break;
			}
			$children.fadeOut(plugin.settings.fadespeed,function() {
				$element.children('li:first').css('margin-top','-'+targetIndex*$element.height()+'px');
				currentIndex = targetIndex;
				$children.fadeIn(plugin.settings.fadespeed);
			});
		}
		
        plugin.init();

    }

    $.fn.fadingbox = function(options) {
        return this.each(function() {
            if (undefined == $(this).data('fadingbox')) {
                var plugin = new $.fadingbox(this, options);
                $(this).data('fadingbox', plugin);
            }
        });
    }
	
})( jQuery );
