(function($) {
	
    $.fn.scaleSlide = function(params, images)
    {
        params = $.extend( {
            sleep: 6000, 
            fade: 2000
        }, params);
		
        this.each(function() {
			
            var $diapo = $(this);
			
            var containerWidth = $diapo.width();
            var containerHeight = $diapo.height();
            
            // create images
            $.each(images, function(key, image){
                if( image ) {
                    $img = $('<img src="'+ image +'" alt="" />');
                    // resize onLoad
                    $img.load(function(){
                        resizeImage($(this), $diapo);
                    });
                    $diapo.append($img);
                }
            });
			
            // show first image and start diaporama
            $diapo.find('img:eq(0)').load(function(){
                $(this).fadeIn(300);
                setTimeout(function(){
                    nextImage($diapo, params['sleep'], params['fade']);
                }, params['sleep']);
            });
                

        });
		
        return this;
    };
	
   

	
    function nextImage($diapo, sleep, fade)
    {
        if( $('#'+$diapo.attr('id')+' img').length < 2 ) {
            return false;
        }
        
        var currentImg = $('#'+$diapo.attr('id')+' img:visible');
        
        nextImg = currentImg.next('img');
        
        if( nextImg.length == 0 ) {
            nextImg = $('#'+$diapo.attr('id')+' img:first');
            if( nextImg.length == 0 ) {
                return false;
            }
        }
        nextImg.fadeIn(fade);

        currentImg.fadeOut(fade, function(){
            setTimeout(function(){
                nextImage($diapo, sleep, fade);
            }, sleep);
        });
        
        
        return false;
    }
})(jQuery);
