// JavaScript Galerie
var Galerie = Class.create();
Galerie.prototype = {
	initialize: function(url, path) {
    
    var me = this;
    
    // var bool
	  this.autostart = true;// mode du diaporama auto ou manuel
    this.loading = false;// état de chargement des effets
    
    // var integer
    this.timer = 7;// interval pour le diaporama en mode auto
    this.x = 1;// nombre de scroll de photo par défaut
    this.pictureWidth = 116 // largeur des miniatures
    this.idFirstPicture = $$('.pic').first().id.split('_').last();
    this.idLastPicture = $$('.pic').last().id.split('_').last();
    
    // var id
    this.copyright = 'copyright';
    this.descr = 'descr';
    this.previous = 'previous';// lien suivant
    this.next = 'next';// lien précédent
    this.liens = 'liens';
    this.links = 'pagination';// bloc de pagination
    this.list = 'list';// bloc liste de photo
    this.pictureBox = 'pictureBox';// bloc photo sélectionnée
    this.picture = 'picture';// bloc photo
    this.slider = 'slider';// bloc slider
    this.title = 'titre';// titre de la photo
    this.photo = 'photo';// grande photo affichée
    this.overhideLeft = 'overhide1';// ...
    this.overhideRight = 'overhide2';// ...
    
    // var class
    this.selected = 'selected';// élément sélectionné
    this.sliderClass = 'slide';// classe du slider une fois initialisé
    this.listOfPictures = '#'+this.list+' a';// liste des miniatures
    this.pictureSelected = '#'+this.list+' a.'+this.selected;// miniature sélectionnée
    this.listOfLinks = '#'+this.links+' a';// liste des liens de pagination
    this.linkSelected = '#'+this.links+' a.'+this.selected;// lien selectionné
    
    // var element
    this.liens = $(this.liens);
    this.copyright = $(this.copyright);
    this.descr = $(this.descr);
    this.title = $(this.title);
    this.photo = $(this.photo);
    this.overhideLeft = $(this.overhideLeft);
    this.overhideRight = $(this.overhideRight);
    
    this.periodicalExecuter = null;
    
    // var ajax
    this.ajaxUrl = url;
    this.ajaxMethod = 'get';
    this.photoPath = path;
    		
	  this.initializeSlider(me, this.list, this.sliderClass);

    if(this.autostart)
    {
      this.periodicalExecuter = new PeriodicalExecuter(function(pe) {
      	if (!me.autostart)
      		pe.stop();
      	else
        	me.nextPicture(me.x);
      }, me.timer);
    }
	},
	
  initializeSlider: function(me, boxId, sliderClass) {
    me.getPictures();
    $(boxId).addClassName(sliderClass);
    $$(me.listOfPictures).each(function(el){
      Event.observe(el,'click',
      function(ev){
        Event.stop(ev);
        if(!me.loading)
        {
        	me.autostart = false;
          $$(me.listOfPictures).each(function(el){
            el.removeClassName(me.selected);
          });
          el.addClassName(me.selected);
          me.sendPictureRequest(el.id.substring(4));       
        }
      });
    });
    $$('#blocPhoto .' + me.next).each(function(el){
      Event.observe(el, 'click', function(e) {Event.stop(e);if(!me.loading) { me.autostart = false; me.nextPicture(); } });
    });
    
    $$('#blocPhoto .' + me.previous).each(function(el){
      Event.observe(el, 'click', function(e) {Event.stop(e);if(!me.loading) { me.autostart = false; me.previousPicture(); } });
    });
    me.initializeLinks();
    me.getLinksEvent();
  },
  
  setUrl: function(url) {
  	this.ajaxUrl = url;
  },
   
  nextPicture: function() {
    var me =this;
    var i=0;
    var curPic=me.getSelectedPicture();
    while(i<me.pictures.length && me.pictures[i].picture_id!=curPic.substring(4)) i++;
    if(i<me.pictures.length-1) me.scrollToPicture('pic_'+me.pictures[++i].picture_id);
    else me.scrollToPicture('pic_'+me.idFirstPicture);
  },
  
  previousPicture: function() {
    var me =this;
    var i=0;
    var curPic=me.getSelectedPicture();
    while(i<me.pictures.length && me.pictures[i].picture_id!=curPic.substring(4)) i++;
    if(i>0) me.scrollToPicture('pic_'+me.pictures[--i].picture_id);
    else me.scrollToPicture('pic_'+me.idLastPicture);
  },
  
  scrollToPicture: function(id) {
    var me = this;
    me.elId = id;
    var elSelected = me.getSelectedPicture();    
    var elCurPos = me.getPictureIndex(elSelected.substring(4));
    var elPos = me.getPictureIndex(me.elId.substring(4));
    
    $$(me.pictureSelected).each(function(el){
      el.removeClassName(me.selected);
    });
    
    $(me.elId).addClassName(me.selected);
    
    if(me.isOnLeftSide(elCurPos, elPos))
      me.scrollLeft(elCurPos, elPos);
    else if(me.isOnRightSide(elCurPos, elPos))
      me.scrollRight(elCurPos, elPos);
  },
  
  getLinksEvent: function() {
    var me = this;
    $$(me.listOfLinks).each(function(el) {
      Event.observe(el, 'click', function(e){
        Event.stop(e);
        if(!me.loading) { me.autostart = false; me.scrollToPicture(el.className.split(' ')[0]) };
      });
    });
  },
  
  getPictureIndex: function(id) {
    var me = this;
    for(i=0; i<me.pictures.length; i++)
    {
      if(me.pictures[i].picture_id==id)
        return i;
    }
  },
  
  getSelectedPicture: function() {
    var me = this;
    $$(me.pictureSelected).each(function (el) {
      selectedId = el.id;
    });
    return selectedId;
  },
  
  getPictures: function() {
    var me = this;
    var ajax = new Ajax.Request(me.ajaxUrl, {
            method: me.ajaxMethod,
            onSuccess: function(pictures) { me.generatePictures(pictures); }
    });
  },
  
  isOnLeftSide: function(currentIndex, selectedIndex) {
    if(selectedIndex>currentIndex)
      return true;
    return false;
  },
  
  isOnRightSide: function(currentIndex, selectedIndex) {
    if(selectedIndex<currentIndex)
      return true;
    return false;
  },
  
  scrollLeft: function(currentIndex, selectedIndex) {
    var me = this;
    var offset=2;
    if(selectedIndex==me.pictures.length-1) offset+=2;
    if(selectedIndex==me.pictures.length-2) offset+=1;
    if(selectedIndex==1 && currentIndex<5) 
    {x=0;}
    else
    {x=(selectedIndex-offset+(Position.positionedOffset($(me.slider))[0]/me.pictureWidth));}
    this.scrollToElement(-x);
  },

  scrollRight: function(currentIndex, selectedIndex) {
    var me = this;
    var offset=2;
    if(selectedIndex==0) offset-=2;
    if(selectedIndex==1) offset-=1;
    if(selectedIndex==me.pictures.length-2 && currentIndex>me.pictures.length-6) 
    {x=0;}
    else
    {x=(-selectedIndex+offset-(Position.positionedOffset($(me.slider))[0]/me.pictureWidth));}
    this.scrollToElement(x);
  },
  
  scrollToElement: function(x) {
    var me=this;
    me.loading=true;
    var iMax = me.pictures.length-1;
    if(x==0 || iMax < 5) 
      me.sendPictureRequest(me.elId.substring(4));
    else
    {
      new Effect.MoveBy(me.slider, 0, me.pictureWidth*x, 
      {
        duration:1, fps:25, from:0.0, to:1.0, 
          afterFinish:function(){
            me.sendPictureRequest(me.elId.substring(4));
          }
      });
    }
  },
  
  generatePictures: function(pictures) {
    var me = this;
    me.pictures = pictures.responseText.evalJSON(true);
  },
  
  sendPictureRequest: function(id) {
    var me = this;
    var index = me.getPictureIndex(id);
    var objImg = new Image();
    me.loading = true;
    me.pictureBox.className = 'off';               
    

    Effect.Fade(me.picture,{duration:1,fps:25,from:1.0,to:0.001, 
      afterFinish:function() {
        $('photo').remove();
        Event.observe(objImg, 'load', function() {
          Event.observe(objImg, 'load', null);
          var html = '<p id="photo"><img src="'+me.photoPath+me.pictures[index].picture_name+'.'+me.pictures[index].picture_extension+'" alt="'+me.pictures[index].picture_alt+'" title="'+me.pictures[index].picture_alt+'" /></p>';
          new Insertion.Top(me.picture, html);          
          me.title.innerHTML = me.pictures[index].picture_description;
          me.copyright.innerHTML = me.pictures[index].picture_copyright;
          if (me.liens) me.liens.innerHTML = me.pictures[index].picture_liens;
          if (me.descr) me.descr.innerHTML = me.pictures[index].picture_title;
          Effect.Appear(me.picture,{duration:1,fps:25,from:0.001,to:1.0,
            afterFinish:function() {
              me.loading=false;
            }
          });
        });  
        objImg.src = me.photoPath+me.pictures[index].picture_name+'.'+me.pictures[index].picture_extension;
      }
    });
    me.refreshPagination(index);
  },
  
  initializeLinks: function() {
    var me = this;
    var iMax = $$(me.listOfLinks).length-1;
    var i = 0; 

    $$(me.listOfLinks).each(function (el) {
      if(i>2 && i<iMax-2)
      {
        el.hide();
        $(me.overhideRight).show();
      }
      i++;
    });
  },
  
  refreshPagination: function(index) {
    var me = this;
    var iMax = me.pictures.length-1;
    var offset = 2;

    if(index>(2*offset+1))
      $(me.overhideLeft).show();
    else
    	if ($(me.overhideLeft))
     		 $(me.overhideLeft).hide();
      
    if(index<(iMax-(2*offset)-1))
      $(me.overhideRight).show();
    else
    	if ($(me.overhideRight))
      		$(me.overhideRight).hide();
    
    for(i=0; i<=iMax; ++i)
    { 
      $$(me.listOfLinks+'.pic_'+me.pictures[i].picture_id)[0].removeClassName(me.selected);
      
      if(i!=index && i>offset && i<(iMax-offset) && (i<(index-2) || i>(index+2)))
        $$(me.listOfLinks+'.pic_'+me.pictures[i].picture_id)[0].hide();
      else
        $$(me.listOfLinks+'.pic_'+me.pictures[i].picture_id)[0].show();
    }
    
    $$(me.listOfLinks+'.pic_'+me.pictures[index].picture_id)[0].addClassName(me.selected);
  }
}
