
(function($) {
    $.fn.gallery = function()
    {	
        var $images = null;    
        var $imageExposedContainer = null;
        var $currentImage = null;
        var $imageExposed = null;
        var $loadingImage = null;
        
        this.each(function() {
            var $container = $(this);

            var $galleryContainer = $('<div class="glr-cnt"></div>');
            $container.append($galleryContainer);
            
            $imageExposedContainer = $('<div class="glr-imgex-cnt"></div>');
            $galleryContainer.prepend($imageExposedContainer);
            
            var $imagesContainer = $('<div class="glr-img-cnt"></div>');
            $galleryContainer.append($imagesContainer);
            
            $rows = $container.find('div.row');
            $imagesContainer.append($rows);
             
            $images = $container.find('img');
            $images.each(function(){
                $(this).parent('a').click(function(){
                    setImage($(this).find('img'));
                    return false;
                });
            });
            
            $loadingImage = $('<img class="glr-load"/>');
                       
            setImage($($rows.get(0)).find('img').first());
        });
        
        function setImage($image){
            if (null != $currentImage){
                $currentImage.removeClass('glr-exposed');
            }
            
            $currentImage = $image;
            $currentImage.addClass('glr-exposed');
            
            $imageExposed = $imageExposedContainer.find('img');
            if (null != $imageExposed){
                $imageExposed.fadeOut('fast');
            }
            
            $imageExposed.remove();
            $imageExposedContainer.append($loadingImage);
            
            var $imageExposedSrc = $currentImage.parent('a').attr('href');
            
            $imageExposed = $('<img src="#"/>');
            $imageExposed.attr('src', $imageExposedSrc);

            // Ces 2 lignes remplacent le bloc suivant
            $loadingImage.remove();
            $imageExposedContainer.append($imageExposed);
            /*
            // Ne fonctionne pas dans IE
            $imageExposed.load(function(){
                alert($imageExposedSrc);
                $loadingImage.remove();
                $imageExposedContainer.append($imageExposed);
            });
            */
        };
		
        return this;
    };
})(jQuery);
