// Initialisation du contenu
displayMethod = -1;
$(function() {
   // Gestion de la surbrillance des vignettes de mosaïque
   $('.class-image_gallery .content-view-full .thumbnail a')
      .hover(
         function() {
            $(this).parents('.thumbnail').addClass('hovered');
         },
         function() {
            $(this).parents('.thumbnail').removeClass('hovered');
         }
      );

   // Branchement des URL réelles d'affichages des images à partir des vignettes mosaïque
   if (displayMethod != -1) {
      $('.class-image_gallery .content-view-full .body .thumbnail').each(
         function(index) {
            if (firstOffset + index >= subgalleriesSize) {
               switch (displayMethod) {
                  case 0 : // Full page
                     break;
                  case 1 : // Popup
                     var link = $(this).find('a');
                     link.attr('href', 'javascript:popup("' + link.attr('href') + '")');
                     break;
                  default : // Layer
                     var link = $(this).find('a');
                     link.attr('href', 'javascript:layer("' + link.attr('href') + '")');
                     break;
               }
            }
         });
   }
});

// Initialisation du contenu (après chargement des images)
$(window).load(function () {
   // Calcul de la largeur des vignettes pour remplir les lignes
   var thumb = $('.class-image_gallery .content-view-full .body .thumbnail:visible:first');
   if ( thumb.length > 0 ) {
      var media = $('.class-image_gallery .content-view-full .body .thumbnail:visible:first .media');
      var thumbBorder = thumb.outerWidth({margin: true}) - thumb.width();
      var mediaWidth = media.outerWidth({margin: true});
      var thumbWidth = mediaWidth + thumbBorder;
      var bodyWidth = $('.class-image_gallery .content-view-full .body').width();
      var thumbnailsize = Math.floor( bodyWidth / ( Math.floor( bodyWidth / thumbWidth ) ) ) - thumbBorder;
      $('.class-image_gallery .content-view-full .body .thumbnail')
         .each(
            function() {
               $(this).width(thumbnailsize);
            });
   }
   thumb = $('.class-image_gallery .content-view-full .footer .paginator_film .element.media:visible:first');
   if ( thumb.length > 0 ) {
      var media = $('.class-image_gallery .content-view-full .footer .paginator_film .element.media:visible:first .media');
      var thumbWidth =
         media.outerWidth({margin: true}) + thumb.outerWidth() - thumb.width();
      $('.class-image_gallery .content-view-full .footer .paginator_film .thumbnail')
         .each(
            function() {
               $(this).width(thumbWidth);
            });
   }
   // Calcul de la hauteur des vignettes pour éviter les pbs de float
   $('.class-image_gallery .content-view-full .thumbnail .caption')
      .css('white-space', 'normal');
   var captionHeight = 0;
   $('.class-image_gallery .content-view-full .body .thumbnail .caption')
         .each(
            function() {
               if (captionHeight < $(this).height()) {
                  captionHeight = $(this).height();
               }
            })
         .height(captionHeight);
});

// Affichage d'une image en popup
function popup(href)
{
   window.open(href, "viewer", "toolbar=0,location=0,directories=0,status=0,scrollbars=1,resizable=1,menubar=0,top=180,left=120,height=600,width=800");
}
// Affichage d'une image en layer
function layer(href)
{
   var layer_root = $('#viewer_layer');
   if (layer_root.length == 0) {
      $('body').append('<div id="viewer_layer"><div id="layer_content"></div><div id="layer_waiting"><span>Loading, please wait</span></div><div id="layer_mask"></div></div>');
      $('#layer_mask').css('opacity', '0');
      layer_root = $('#viewer_layer');
   }
   if (layer_root.css('display') == 'none') {
      $('html,body').css('overflow', 'hidden');
      layer_root.css('display', 'block');
      $('#layer_mask').fadeTo(400, 0.8, function() {
         $('#layer_waiting').fadeIn(50, function() {
            loadingLayerContent(href);
         });
      });
   }
   else {
      $('#layer_content').fadeOut(100, function() {
         $('#layer_waiting').fadeIn(50, function() {
            loadingLayerContent(href);
         });
      });
   }
}
function loadingLayerContent(href)
{
   $('#layer_content')
      .load(href.replace('/layout/set/gallery', '/layout/set/clean') + ' #content > *', null,
         function() {
            $(this).find('.footer .command.close a')
               .attr('href', 'javascript:hideLayer()');
            var links = $(this).find('.footer .command.previous a');
            links.attr('href', 'javascript:layer("' + links.attr('href') + '");');
            links = $(this).find('.footer .command.next a');
            links.attr('href', 'javascript:layer("' + links.attr('href') + '");');
            
            $('#layer_waiting').fadeOut(50, function() {
               $('#layer_content').fadeIn(100);
            });
         });
}
function hideLayer()
{
   $('#layer_content').css('display', 'none');
   $('#layer_mask').fadeTo(400, 0, function() {
      $('body,html').css('overflow', 'auto');
      $('#viewer_layer').css('display', 'none');
   });
}

var Paginator = function(id, initOffset, subgalleriesCount, nodeIDs, baseURL, paramsURL, displayMethod)
{
   this.id = id;
   this.offset = initOffset;
   this.subgalleriesSize = subgalleriesCount;
   this.nextOffset = -1;
   this.nodeIDs = nodeIDs;
   this.baseURL = baseURL + '/';
   this.paramsURL = paramsURL;
   this.displayMethod = displayMethod;
   this._isOnProcess = false;
   this._imageLoading = false;
   
   if (Paginator.instances.length == 0) {
      $(document).ready(Paginator.initDOM);
      $(window).load(Paginator.initWindow);
   }
   Paginator.instances.push( this );
};
Paginator.instances = [];
Paginator.initDOM = function()
{
   for (i = 0; i < Paginator.instances.length; ++i) {
      Paginator.instances[i]._initDOM();
   }
};
Paginator.initWindow = function()
{
   for (i = 0; i < Paginator.instances.length; ++i) {
      Paginator.instances[i]._initWindow();
   }
};
Paginator.prototype =
{
   _initDOM : function()
   {
      this.gallerySize = $('.paginator_film .viewport .client_area .element').length;
      this.windowSize = $('.paginator_film .viewport .client_area .element:visible').length;
      this.windowStart = -Math.floor(this.windowSize / 2);
      this.minWindowStart = -this.windowStart;
      this.windowEnd = this.windowStart + this.windowSize - 1;
      this.maxWindowEnd = this.gallerySize - this.windowEnd - 1;
      this.thumbnails = $('.paginator_film .viewport .client_area .element');
      
      var id = this.id;
      $('.paginator_film .command.previous a')
         .attr('href', 'javascript:' + id + '.prevImage()');
      $('.paginator_film .command.next a')
         .attr('href', 'javascript:' + id + '.nextImage()');
      var subgalleriesSize = this.subgalleriesSize;
      $('.paginator_film .viewport .client_area .element.media .thumbnail')
         .each(
            function(i, thumbnail) {
               $(thumbnail).find('a').attr('href',
                  'javascript:' + id + '.gotoImage(' + (i + subgalleriesSize) + ')');
            }
      );
      
      // Branchement de l'URL réelle en première image en mode film
      if (this.offset >= this.subgalleriesSize) { 
         var displayMethod = this.displayMethod;
         $('.class-image_gallery .content-view-full .body .mediaviewer a')
            .each( function() {
               switch (displayMethod) {
                  case 0 : // Full page
                     break;
                  case 1 : // Popup
                     $(this).attr('href', 'javascript:popup("' + $(this).attr('href') + '")');
                     break;
                  default : // Layer
                     $(this).attr('href', 'javascript:layer("' + $(this).attr('href') + '")');
                     break;
               }
            });
      }
   },
   _initWindow : function()
   {
      //var captionHeight = 0;
      $('.paginator_film .viewport .client_area .element .thumbnail .caption')
         .css({
            whiteSpace: 'normal',
            overflow: 'hidden' });
   },
   nextImage : function()
   {
      this.nextOffset = this.offset + 1;
      this._processCommand();
   },
   prevImage : function()
   {
      this.nextOffset = this.offset - 1;
      this._processCommand();
   },
   gotoImage : function(index)
   {
      this.nextOffset = index;
      this._processCommand();
   },
   _processCommand : function()
   {
      // Prise en compte de la prochaine commande
      if (this._isOnProcess || this._imageLoading) {
         return;
      }
      var reqOffset = this.nextOffset;
      this.nextOffset = -1;
      if (reqOffset == -1) {
         return;
      }
      this._isOnProcess = true;
      
      // Affichage de l'image cible
      $('.class-image_gallery .content-view-full .body .mediaviewer .media')
         .addClass('waiting')
         .empty();
      var url = this.baseURL + this.nodeIDs[reqOffset] +
         this.paramsURL + '/(offset)/' + reqOffset;
      if (reqOffset < this.subgalleriesSize) {
         url += '/(icon)/folder_icon';
      }
      url += ' #content > *';
      var that = this;
      this._imageLoading = true;
      $('.class-image_gallery .content-view-full .body .mediaviewer')
         .load(url, null,
            function(responseText, textStatus, XMLHttpRequest) {
               if (reqOffset >= that.subgalleriesSize) {
                  $(this).find('a').each(
                     function() {
                        switch (that.displayMethod) {
                           case 0 : // Full page
                              break;
                           case 1 : // Popup
                              $(this).attr('href', 'javascript:popup("' + $(this).attr('href') + '")');
                              break;
                           default : // Layer
                              $(this).attr('href', 'javascript:layer("' + $(this).attr('href') + '")');
                              break;
                        }
                     });
               }
               $('.class-image_gallery .content-view-full .body .mediaviewer .media')
                  .removeClass('waiting');
               that._imageLoading = false;
               that._processCommand();
            });

      // Suppression cadre de sélection
      $(this.thumbnails[this.offset]).removeClass('currentViewed');
      
      // Calcul des vignettes à déplacer
      if ( reqOffset < this.offset ) {
         this._doAnimate(-1, this.windowEnd, this.windowStart, reqOffset);
      }
      else {
         this._doAnimate(1, this.windowStart, this.windowEnd, reqOffset);
      }
   },
   _doAnimate : function(inc, removeIndex, addIndex, reqOffset)
   {
      if (reqOffset == this.offset) {
         // On est arrivé à destination
         
         // Ajout du cadre de sélection
         $(this.thumbnails[this.offset]).addClass('currentViewed');
         
         // Gestion des boutons suivants / précédents
         if (this.offset == 0) {
            $('.paginator_film .command.previous')
               .css('visibility', 'hidden');
         }
         else {
            $('.paginator_film .command.previous')
               .css('visibility', 'visible');
         }
         if (this.offset == this.gallerySize - 1) {
            $('.paginator_film .command.next')
               .css('visibility', 'hidden');
         }
         else {
            $('.paginator_film .command.next')
               .css('visibility', 'visible');
         }
         
         // On passe à la prochaine demande si elle existe
         this._isOnProcess = false;
         this._processCommand();
      }
      else {
         // On passe à la vignette précédente / suivante
         var absRemoveIndex = this.offset + removeIndex;
         var absAddIndex = this.offset + inc + addIndex;
         if (absRemoveIndex >= 0 && absRemoveIndex < this.gallerySize
               && absAddIndex >= 0 && absAddIndex < this.gallerySize) {
            // Animation
            var that = this;
            $(this.thumbnails[absRemoveIndex]).fadeOut(50,
               function() {
                  that.offset += inc;
                  $(that.thumbnails[absAddIndex]).fadeIn(50,
                     function() {
                        that._doAnimate(inc, removeIndex, addIndex, reqOffset);
                     });
               });
         }
         else {
            // Pas besoin d'animation
            this.offset += inc;
            this._doAnimate(inc, removeIndex, addIndex, reqOffset);
         }
      }
   }
};