var moolbum = new Class({
  Implements: Options, 
  
  contentElement  : '',   // élément qui contiendra le contenu
  colorOk         : '#3b5998', // couleur du message de confirmation
  colorError      : '#3b5998', // couleur du message d'erreur
  path            : '',   // répertoire où se trouve le script par rapport à la page appelante
  picturePath     : '',   // répertoire où se trouve les images par rapport à la page appelante
  delayFct        : "",   // pour stocker les fonctions sur lesquel a été appliqué un délai
  
  mySqueezeBox    : SqueezeBox,
  
  presets: {
    picturesPerLine : 5,    // pour savoir combien on affiche de photos par ligne sur une page
    picturesPerCol  : 4,    // pour savoir combien on affiche de photos par colonne sur une page
    maxWidth        : 100,  // largeur maximum d'une vignette
    maxHeight       : 100,  // hauteur maximum d'une vignette
    subMenu         : ''    // pour l'affichage du fil d'Arianne
  },

  initialize: function(contentElement, path, picturePath, presets){
    // teste que les éléments passés en paramètre existent bien
    if (!contentElement)
      return this;
     
    this.contentElement = contentElement;
    this.path = path;
    this.picturesPath = picturePath;
    this.presets = $merge(this.presets, presets);
    this.options = {};
		this.setOptions(this.presets);
	},
	
	/*********************************************
   *
   * Stoppe la dernière fonction delayée   
   *
   *********************************************/   
  clearDelay: function(){
    if (this.delayFct != ""){
      $clear(this.delayFct);
      this.delayFct = "";
    }
  },
  
  /**************************************************
   *  
   * Change la photo de couverture d'un album donné
   *    
   **************************************************/
  setAlbumCover: function(albumId, pictureId){
    // vide le contenant
    $(this.contentElement).empty();
    
    if ($defined(albumId) && $defined(pictureId)){
      var myObject = this;
      var req = new Request.HTML({
        url: this.path + 'setAlbumCover.php',
        onSuccess: function(tree,ele,html,js){
          myObject.contentElement.set('html',html);
        }
      }).send('albumId=' + albumId + '&pictureId=' + pictureId);
    }
    else{
      this.contentElement.set('html','il manque des informations');
    }
  },
  
  /**************************************************
   *  
   * Change l'état d'un album donné
   *    
   **************************************************/
  setAlbumState: function(albumId, state){
    // vide le contenant
    $(this.contentElement).empty();

    if ($defined(albumId) && $defined(state)){
      var myObject = this;
      var req = new Request.HTML({
        url: this.path + 'setAlbumState.php',
        onSuccess: function(tree,ele,html,js){
          myObject.contentElement.set('html',html);
        }
      }).send('albumId=' + albumId + '&state=' + state);
    }
    else{
      this.contentElement.set('html','il manque des informations');
    }
  },
  
  resizePicture : function(h,w){
    SqueezeBox.resize({x:w,y:h},false);
  },
	
	/*********************************************
   *
   * Affiche les images d'un album   
   *
   *********************************************/   
	getPictures: function(albumId, page){
    if (!$defined(page))
      page = 1;
    
    // vide le contenant
    $(this.contentElement).empty();
  
    var myObject = this;
    var req = new Request.HTML({
      url: this.path + 'getPictures.php',
      onSuccess: function(tree,ele,html,js){
        myObject.contentElement.set('html',html);
        
        $$('.pageLink').each(function(el,i){
          el.addEvent('mouseover',function(event){
            this.setStyle('backgroundColor','#3b5998');
            this.setStyle('color','#ffffff');
          });
          
          el.addEvent('mouseout',function(event){
            this.setStyle('background','transparent');
            this.setStyle('color','#3b5998');
          });
          
          el.addEvent('click',function(event){
            myObject.getPictures(albumId, this.get('page'));
          });
        });
        
        SqueezeBox.initialize();
        SqueezeBox.assign($$('.picture'), {
          handler: 'iframe'
      	});
      }
    }).send('albumId=' + albumId + 
            '&picturesPerLine=' + this.options.picturesPerLine + 
            '&picturesPerCol=' + this.options.picturesPerCol + 
            '&page=' + page + 
            '&maxWidth=' + this.options.maxWidth + 
            '&maxHeight=' + this.options.maxHeight + 
            '&windowWidth=' + window.getSize().x + 
            '&windowHeight=' + window.getSize().y + 
            '&path=' + myObject.path + 
            '&pictures_folder=' + myObject.picturesPath);
            
    // sous-menu
    if (this.options.subMenu != ''){
      var div = new Element('div',{
        'html':' » Visualiser les photos'
      });
      
      var a = new Element('a',{
        'href':'#',
        'html':'Albums photos',
        'events':{
          'click':this.getAlbums.pass('',this)
        }
      });
      
      a.inject(div, 'top');
      this.options.subMenu.empty();
      div.inject(this.options.subMenu);
    }
  },
  
  /*********************************************
   *
   * Affiche les images d'un album pour le public
   *
   *********************************************/   
	printPictures: function(albumId, page){
    if (!$defined(page))
      page = 1;
    
    // vide le contenant
    $(this.contentElement).empty();
  
    var myObject = this;
    var req = new Request.HTML({
      url: this.path + 'printPictures.php',
      onSuccess: function(tree,ele,html,js){
        myObject.contentElement.set('html',html);
        
        $$('.pageLink').each(function(el,i){
          el.addEvent('mouseover',function(event){
            this.setStyle('backgroundColor','#3b5998');
            this.setStyle('color','#ffffff');
          });
          
          el.addEvent('mouseout',function(event){
            this.setStyle('background','transparent');
            this.setStyle('color','#3b5998');
          });
          
          el.addEvent('click',function(event){
            myObject.getPictures(albumId, this.get('page'));
          });
        });
        
        SqueezeBox.initialize();
        SqueezeBox.assign($$('.picture'), {
          handler: 'iframe'
      	});
      }
    }).send('albumId=' + albumId + 
            '&picturesPerLine=' + this.options.picturesPerLine + 
            '&picturesPerCol=' + this.options.picturesPerCol + 
            '&page=' + page + 
            '&maxWidth=' + this.options.maxWidth + 
            '&maxHeight=' + this.options.maxHeight + 
            '&windowWidth=' + window.getSize().x + 
            '&windowHeight=' + window.getSize().y + 
            '&path=' + myObject.path + 
            '&pictures_folder=' + myObject.picturesPath);
            
    // sous-menu
    if (this.options.subMenu != ''){
      var div = new Element('div',{
        'html':' » Visualiser les photos'
      });
      
      var a = new Element('a',{
        'href':'#',
        'html':'Albums photos',
        'events':{
          'click':this.getAlbums.pass('',this)
        }
      });
      
      a.inject(div, 'top');
      this.options.subMenu.empty();
      div.inject(this.options.subMenu);
    }
  },
  
  /************************************
   *
   * Création d'un nouvel album photo   
   *
   ************************************/        
  newAlbum: function(){
    // vide le contenant
    $(this.contentElement).empty();
    
    // puis créé le formulaire
    var myObject = this;
    var form = new Element('form',{
      'id':'formNewAlbum',
      'method':'post',
      'action':myObject.path + 'sendAlbum.php',
      'enctype':'application/x-www-form-urlencoded'
    });
    
    var div1 = new Element('div',{
      'styles':{
        'width':'400px',
        'margin':'auto',
        'padding':'10px'
      }
    });
    
    // nom
    var div2 = new Element('div',{
      'styles':{
        'margin':'5px 0 5px 0'
      }
    });
    var div21 = new Element('div',{
      'styles':{
        'clear':'both',
        'float':'left',
        'width':'120px',
        'textAlign':'left',
        'padding':'0 5px 0 0'
      },
      'html':"Nom de l'album : "
    });
    div21.inject(div2);
    var div22 = new Element('div',{
      'styles':{
        'width':'390px',
        'textAlign':'left'
      }
    });
    var input = new Element('input',{
      'type':'text',
      'name':'albumName',
      'class':'required',
      'styles':{
        'width':'250px'
      }
    });
    input.inject(div22);
    div22.inject(div2);
    div2.inject(div1);
    
    // lieu
    div2 = new Element('div',{
      'styles':{
        'margin':'5px 0 5px 0'
      }
    });
    div21 = new Element('div',{
      'styles':{
        'clear':'both',
        'float':'left',
        'width':'120px',
        'textAlign':'left',
        'padding':'0 5px 0 0'
      },
      'html':"Lieu : "
    });
    div21.inject(div2);
    div22 = new Element('div',{
      'styles':{
        'width':'390px',
        'textAlign':'left'
      }
    });
    input = new Element('input',{
      'type':'text',
      'name':'albumPlace',
      'styles':{
        'width':'250px'
      }
    });
    input.inject(div22);
    div22.inject(div2);
    div2.inject(div1);
    
    // Auteur
    div2 = new Element('div',{
      'styles':{
        'margin':'5px 0 5px 0'
      }
    });
    div21 = new Element('div',{
      'styles':{
        'clear':'both',
        'float':'left',
        'width':'120px',
        'textAlign':'left',
        'padding':'0 5px 0 0'
      },
      'html':"Auteur : "
    });
    div21.inject(div2);
    div22 = new Element('div',{
      'styles':{
        'width':'390px',
        'textAlign':'left'
      }
    });
    input = new Element('input',{
      'type':'text',
      'name':'albumAuthor',
      'styles':{
        'width':'250px'
      }
    });
    input.inject(div22);
    div22.inject(div2);
    div2.inject(div1);
    
    // description
    div2 = new Element('div',{
      'styles':{
        'margin':'5px 0 5px 0'
      }
    });
    div21 = new Element('div',{
      'styles':{
        'clear':'both',
        'float':'left',
        'width':'120px',
        'textAlign':'left',
        'padding':'0 5px 0 0'
      },
      'html':"Description : "
    });
    div21.inject(div2);
    div22 = new Element('div',{
      'styles':{
        'width':'390px',
        'textAlign':'left'
      }
    });
    input = new Element('textarea',{
      'name':'albumDescription',
      'styles':{
        'width':'250px',
        'height':'80px'
      }
    });
    input.inject(div22);
    div22.inject(div2);
    div2.inject(div1);
    
    // album enabled
    div2 = new Element('div',{
      'styles':{
        'margin':'5px 0 5px 0'
      }
    });
    div21 = new Element('div',{
      'styles':{
        'clear':'both',
        'float':'left',
        'width':'120px',
        'textAlign':'left',
        'padding':'0 5px 0 0'
      },
      'html':"Afficher : "
    });
    div21.inject(div2);
    div22 = new Element('div',{
      'styles':{
        'width':'390px',
        'textAlign':'left'
      }
    });
    input = new Element('input',{
      'type':'checkbox',
      'name':'albumEnabled',
      'value':'1',
      'checked':'checked'
    });
    input.inject(div22);
    div22.inject(div2);
    div2.inject(div1);
    
    // boutons
    div2 = new Element('div',{
      'styles':{
        'margin':'15px 0 0 0',
        'textAlign':'center'
      }
    });
    var button = new Element('input',{
      'type':'submit',
      'value':"Créer l'album"
    });
    button.inject(div2);
    var sep = new Element('span',{
      'html':'&nbsp;&nbsp;'
    });
    sep.inject(div2);
    var button = new Element('input',{
      'type':'button',
      'value':"Annuler"
    });
    button.addEvent('click',function(){
      myObject.getAlbums();
    });
    button.inject(div2);
    div2.inject(div1);
    div1.inject(form);
    
    form.inject(this.contentElement);
    
    // contrôle du formulaire
    var myObject = this;
    var myCheckForm = new checkForm(form,{useAjax: true,
                                          errorPlace: 'bottom',
                                          divErrorCss: {
                                            'margin':'5px 0 0 120px'
                                          },
                                          ajaxSuccessFct: function(msg){
                                            if (msg == "-1"){
                                              var message = new Element('div',{
                                                'html':"- Une erreur est survenue lors de l'ajout de l'album photos",
                                                'styles':{
                                                  'textAlign':'left',
                                                  'color':myObject.colorError,
                                                  'margin':'0 auto'
                                                }
                                              });
                                              myObject.contentElement.empty();
                                              message.inject(myObject.contentElement,'top');
                                              // ajoute la fonction a la gestion des délais puis l'appelle
                                              myObject.delayFct = (function(){myObject.newAlbum()}).delay(3000);
                                            }
                                            else{
                                              form.dispose();
                                              var message = new Element('div',{
                                                'html':"L'album photos a été créé avec succès",
                                                'styles':{
                                                  'textAlign':'center',
                                                  'color':myObject.colorOk,
                                                  'margin':'0 auto'
                                                }
                                              });
                                              myObject.contentElement.empty();
                                              message.inject(myObject.contentElement,'top');
                                              // ajoute la fonction a la gestion des délais puis l'appelle
                                              myObject.delayFct = (function(){myObject.uploadPictures(msg)}).delay(3000);
                                            }
                                          }
                                        });
    // sous-menu
    if (this.options.subMenu != ''){
      var div = new Element('div',{
        'html':' » Nouvel album photos'
      });
      
      var a = new Element('a',{
        'href':'#',
        'html':'Albums photos',
        'events':{
          'click':this.getAlbums.pass('',this)
        }
      });
      
      a.inject(div, 'top');
      this.options.subMenu.empty();
      div.inject(this.options.subMenu);
    }
  },
  
  
  
  /************************************
   *
   * Upload des photos dans un album   
   *
   ************************************/   
  uploadPictures: function(albumId){
    if ($defined(albumId)){
      // vide le contenant
      $(this.contentElement).empty();
      
      var myObject = this;
      var req = new Request.HTML({
        url: myObject.path + 'upload.php',
        onSuccess: function(tree,ele,html,js){
          myObject.contentElement.set('html',myObject.contentElement.get('html') + html);
          
          var swiffy = new FancyUpload2($('status'), $('list'), {
        		url: $('formUpload').action,
        		fieldName: 'photoupload',
        		'path': myObject.path + 'upload/Swiff.Uploader.swf',
        		limitSize: 2 * 1024 * 1024, // 2Mb
        		limitFiles: 50,
        		data: $('formUpload'),
        		target: 'browse', // the element for the overlay (Flash 10 only)
        		onAllComplete: function(current){
        		  // affiche les détails des photos après X secondes
              myObject.delayFct = (function(){myObject.modifyAlbum(albumId)}).delay(3000);
            }
        	});
        	
          swiffy.options.typeFilter = {'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'};
          
          $('browse').addEvent('click', function(){
            swiffy.browse();
            return false;
          });
          
          $('clear').addEvent('click',function(){
            swiffy.removeFile();
    		    return false;
          });
          
          $('upload').addEvent('click',function(){
            swiffy.upload();
    		    return false;
          });            
        }
      }).send('path=' + myObject.path + '&albumId=' + albumId + '&pictures_folder=' + myObject.picturesPath);
      
      // sous-menu
      if (this.options.subMenu != ''){
        var div = new Element('div',{
          'html':' » Ajouter des photos'
        });
        
        var a = new Element('a',{
          'href':'#',
          'html':'Albums photos',
          'events':{
            'click':this.getAlbums.pass('',this)
          }
        });
        
        a.inject(div, 'top');
        this.options.subMenu.empty();
        div.inject(this.options.subMenu);
      }
    }
  },
  
  /***************************************************
   *
   * Définit les détails des photos d'un album donné  
   *
   **************************************************/   
  modifyAlbum: function(albumId){
    // vide le contenant
    $(this.contentElement).empty();
    
    var myObject = this;
    // récupert la page de détails des photos
    var req = new Request.HTML({
      url: myObject.path + 'getPicturesDetails.php',
      onSuccess: function(tree,ele,html,js){
        myObject.contentElement.set('html',html);
        
        if ($('picturesDetailsForm')){
          $$('.removePicture').each(function(el, index){
            el.addEvent('click',function(){
              if (confirm("Etes-vous sûr de vouloir supprimer cette photo ?")){
                myObject.removePicture(this.get('pictureId'));
                myObject.delayFct = (function(){myObject.modifyAlbum(albumId)}).delay(3000);
              }
            });
          });
          
          $$('.setAlbumCover').each(function(el, index){
            el.addEvent('click',function(){
              if (confirm("Etes-vous sûr de vouloir définir cette photo comme couverture de l'album ?")){
                myObject.setAlbumCover(albumId, this.get('pictureId'));
                myObject.delayFct = (function(){myObject.modifyAlbum(albumId)}).delay(3000);
              }
            });
          });
          
          $$('.annuler').each(function(el,index){
            el.addEvent('click',function(){
              myObject.getAlbums();
            });
          });
          
          var myCheckForm = new checkForm($('picturesDetailsForm'),{useAjax: true,
                                                      errorPlace: "bottom",
                                                      ajaxSuccessFct: function(msg){
                                                        if (msg == "1"){
                                                          $('picturesDetailsForm').dispose();
                                                          var message = new Element('div',{
                                                            'html':"L'album photos a été modifié avec succès !",
                                                            'styles':{
                                                              'width':'100%',
                                                              'textAlign':'center',
                                                              'color':myObject.colorOk
                                                            }
                                                          });
                                                          myObject.contentElement.empty();
                                                          message.inject(myObject.contentElement,'top');
                                                          myObject.delayFct = (function(){myObject.modifyAlbum(albumId)}).delay(3000);
                                                        }
                                                        else if (msg == "-1"){
                                                          var message = new Element('div',{
                                                            'html':"Une erreur est survenue lors de la modification de l'album photos",
                                                            'styles':{
                                                              'width':'100%',
                                                              'textAlign':'center',
                                                              'color':myObject.colorError
                                                            }
                                                          });
                                                          myObject.contentElement.empty();
                                                          message.inject(myObject.contentElement,'top');
                                                          myObject.delayFct = (function(){myObject.modifyAlbum(albumId)}).delay(3000);
                                                        }
                                                        else{
                                                          var message = new Element('div',{
                                                            'html':"Erreur : " + msg,
                                                            'styles':{
                                                              'width':'100%',
                                                              'textAlign':'center',
                                                              'color':myObject.colorError
                                                            }
                                                          });
                                                          myObject.contentElement.empty();
                                                          message.inject(myObject.contentElement,'top');
                                                          myObject.delayFct = (function(){myObject.modifyAlbum(albumId)}).delay(3000);
                                                        }
                                                                               
                                                      }
                                                    });                
        }
      }
    }).send('albumId=' + albumId + '&path=' + myObject.path + '&pictures_folder=' + myObject.picturesPath);
    
    // sous-menu
    if (this.options.subMenu != ''){
      var div = new Element('div',{
        'html':' » Modifier un album'
      });
      
      var a = new Element('a',{
        'href':'#',
        'html':'Albums photos',
        'events':{
          'click':this.getAlbums.pass('',this)
        }
      });
      
      a.inject(div, 'top');
      this.options.subMenu.empty();
      div.inject(this.options.subMenu);
    }
  },
  
  /************************************
   *
   * Supprime une image d'un album   
   *
   ************************************/   
  removePicture : function(id_picture){
    var myObject = this;
    var req = new Request({url:myObject.path + 'removePicture.php', 
		  onSuccess: function(txt){
		    if (txt == 1){
          var message = new Element('div',{
                                    'html':"La photo a été supprimée avec succès !",
                                    'styles':{
                                      'width':'100%',
                                      'text-align':'center',
                                      'color':myObject.colorOk
                                    }
                                  });
        }
        else if(txt == -1){
          var message = new Element('div',{
                                    'html':"Un problème est survenu lors de la suppression de la photo !",
                                    'styles':{
                                      'width':'100%',
                                      'text-align':'center',
                                      'color':myObject.colorError
                                    }
                                  });
        }
        else{
          var message = new Element('div',{
                                    'html':"Un problème est survenu lors de la suppression de la photo : " + txt,
                                    'styles':{
                                      'width':'100%',
                                      'text-align':'center',
                                      'color':myObject.colorError
                                    }
                                  });
        }
        myObject.contentElement.empty();
        message.inject(myObject.contentElement,'top');
      }
    });
    req.send('id_picture=' + id_picture + '&appPath=' + myObject.path);
  },
  
  /************************************
   *
   * Supprime un album  
   *
   ************************************/   
  removeAlbum : function(albumId){
    var myObject = this;
    var req = new Request({url:myObject.path + 'removeAlbum.php', 
		  onSuccess: function(txt){
		    if (txt == 1){
          var message = new Element('div',{
                                    'html':"L'album a été supprimé avec succès !",
                                    'styles':{
                                      'width':'100%',
                                      'textAlign':'center',
                                      'color':myObject.colorOk
                                    }
                                  });
        }
        else{
          var message = new Element('div',{
                                    'html':"Un problème est survenu lors de la suppression de l'album : <br />" + txt,
                                    'styles':{
                                      'width':'100%',
                                      'textAlign':'center',
                                      'color':myObject.colorError
                                    }
                                  });
        }
        myObject.contentElement.empty();
        message.inject(myObject.contentElement,'top');
      }
    });
    req.send('albumId=' + albumId + '&appPath=' + myObject.path);
  },
  
  /************************************
   *
   * Affiche les albums disponibles   
   *
   ************************************/   
  getAlbums: function(onlyEnabled){
    // pour savoir si on ne prend que les albums activés
    if (onlyEnabled == true)
      onlyEnabled = 1;
    else
      onlyEnabled = 0;
    
    // vide le contenant
    $(this.contentElement).empty();
  
    var myObject = this;
    var req = new Request.HTML({
      url: this.path + 'getAlbums.php',
      onSuccess: function(tree,ele,html,js){
        myObject.contentElement.set('html',html);
        
        $$('.viewAlbum').each(function(el,index){
          el.addEvent('click',function(){
            myObject.getPictures(this.get('albumId'));
          });
        });
        
        $$('.modifyAlbum').each(function(el,index){
          el.addEvent('click',function(){
            myObject.modifyAlbum(this.get('albumId'));
          });
        });
        
        $$('.removeAlbum').each(function(el,index){
          el.addEvent('click',function(){
            if (confirm("Etes-vous sûr de vouloir supprimer cet album photo ?")){
              myObject.removeAlbum(this.get('albumId'));
              myObject.delayFct = (function(){myObject.getAlbums()}).delay(3000);
            }
          });
        });
        
        $$('.addPictures').each(function(el,index){
          el.addEvent('click',function(){
            myObject.uploadPictures(this.get('albumId'));
          });
        });
        
        $$('.changeAlbumState').each(function(el,index){
          el.addEvent('click',function(){
            if (confirm("Etes-vous sûr de vouloir modifier l'état de cet album photos ?")){
              myObject.setAlbumState(this.get('albumId'), this.get('state'));
              myObject.delayFct = (function(){myObject.getAlbums()}).delay(3000);
            }
          });
        });
      }
    }).send('path=' + myObject.path + 
            '&pictures_folder=' + myObject.picturesPath +
            '&onlyEnabled=' + onlyEnabled);
    
    // sous-menu
    if (this.options.subMenu != ''){
      var div = new Element('div',{
        'html':'Albums photos'
      });
      
      this.options.subMenu.empty();
      div.inject(this.options.subMenu);
    }
  },
  
  /************************************
   *
   * Affiche les albums pour le public   
   *
   ************************************/   
  printAlbums: function(onlyEnabled){
    // pour savoir si on ne prend que les albums activés
    if (onlyEnabled == true)
      onlyEnabled = 1;
    else
      onlyEnabled = 0;
    
    // vide le contenant
    $(this.contentElement).empty();
  
    var myObject = this;
    var req = new Request.HTML({
      url: this.path + 'printAlbums.php',
      onSuccess: function(tree,ele,html,js){
        myObject.contentElement.set('html',html);
        
        $$('.viewAlbum').each(function(el,index){
          el.addEvent('click',function(){
            myObject.printPictures(this.get('albumId'));
          });
        });
      }
    }).send('path=' + myObject.path + 
            '&pictures_folder=' + myObject.picturesPath +
            '&onlyEnabled=' + onlyEnabled);
    
    // sous-menu
    if (this.options.subMenu != ''){
      var div = new Element('div',{
        'html':'Albums photos'
      });
      
      this.options.subMenu.empty();
      div.inject(this.options.subMenu);
    }
  }
  
  

});