/////////////////////////////////
///// house2couette APPLICATION
/////////////////////////////////

/// Depends on :
///   mootools Core (1.3.1.1)

// Namespace
var H2C = {
    version:"1.0.0",
    config:{}
};

H2C.components={};

////////////////////////////////////////////////////////////////////////////////
///// INIT APPLICATION
////////////////////////////////////////////////////////////////////////////////

// Load 
// Init HTML5+PNG Compatibility for IE6, IE7, IE8
if(Browser.ie6 || Browser.ie7 || Browser.ie8) {
  document.createElement("header"); 
  document.createElement("footer"); 
  document.createElement("section"); 
  document.createElement("aside"); 
  document.createElement("nav"); 
  document.createElement("article");
}

H2C.initApplication = function() {

    // Init FormAjax (id="form_ajax")
    if($('form_ajax')) { new H2C.components.FormAjax({}); };
    
    // Init Vimeo module
    if($('video')) { new H2C.components.Video({}); }
    
    // Init Flickr module
    if($('photo')) { new H2C.components.Photo({}); }
        
    // Init Radio module
    if($('radio')) { new H2C.components.Accordion(0);}
    
    // Init event module
    if($('event')) {
      var anchor = location.hash.substring(1);
      new H2C.components.Accordion(anchor);
    }

};

////// DOMREADY
window.addEvent('domready', H2C.initApplication);


////////////////////////////////////////////////////////////////////////////////
///// CLASS COMPONENTS
////////////////////////////////////////////////////////////////////////////////

//---------------------------------------------------
//Class component FormAjax
H2C.components.FormAjax = new Class({
    initialize: function(config){
        var _component = this ; // this = Class instance    
        $('form_ajax').addEvent('submit', this.submit);
        
        $$('#form_ajax input[class*="requirH2C"]').each(function(el){
            el.addEvent('focus', _component.focus);
            el.addEvent('blur',  _component.blur);
        });

    }, // initialize
    focus: function(e){
        if(this.hasClass('error')) {
            this.removeClass('error');
        }
    },
    blur: function(e){
        if(this.get('value')=='') {
            this.addClass('error');
        }
    },
    submit: function(e){
        // Stop other actions
        new Event(e).stop();
        new H2C.components.SendFormAjax({});
    } // submit 
});



//---------------------------------------------------
//Class component SendFormAjax
H2C.components.SendFormAjax = new Class({
    initialize: function(config){
        var _component = this ; // this = Class instance
        this.submit();
    }, // initialize

submit: function(e){
    
    // Check the requirH2C input (with class="requirH2C")
    var check_requirH2C = null;
    $$('#form_ajax input[class*="requirH2C"]').each(function(el){
        if(el.get('value')==''){
            el.addClass('error');
            check_requirH2C = 1 ;
        } else {
            el.removeClass('error');
        }
    });
    
    // Submit form if requirH2C input are submittH2C
    if(check_requirH2C == null){

        // Config Ajax request from form (url = action)
        $('form_ajax').set('send', { 
            onRequest: function(response) {
                $('log').setStyle('opacity', '1').removeClass('log_validatH2C').removeClass('log_error').addClass('log_load').empty().set('html','Message en cours d\'envoi');  
            },
            onComplete: function(response) {
                if(response=="Votre message a été envoyé. Nous vous répondrons dès que possible.") { 
                    $('log').addClass('log_validatH2C').set('html',response);
                    $('fields').set('html','');
                    $$('#form_ajax input[type="submit"]').each(function(el){
                        el.destroy();
                    });
                }
                else {
                $('log').removeClass('log_load').addClass('log_error').set('html',response);
                }
            },
            onFailure: function(response) { 
                $('log').removeClass('log_load').addClass('log_error').empty().set('html','Error Server');
            }   
        });
        // Send Ajax
        $('form_ajax').send();

    }
    } // submit 
});


//---------------------------------------------------
//Class component Video
H2C.components.Video = new Class({
  initialize: function(){ 
    this.videoList = null;
    this._getData();
  }
  , _getData : function() {
    var self = this;
    var RequestData = new Request.JSONP({
      url : 'http://vimeo.com/api/v2/house2couette/videos.json',
      onRequest: function(){
        $('video').set('text', 'Loading...').addClass('log_load');
      },
      onComplete: function(jsonObj) {
        $('video').empty().removeClass('log_load');
        self.videoList = jsonObj;
        self._showList();
      }
    }).send();
  }
  , _showList : function() {
    var self = this;
    this.videoList.each(function(video) {
      
      var el = new Element('div.vimeo');
      
      var url = new Element('a', {
        //href:'#',
        href:'http://player.vimeo.com/video/'+video.id+'?color=ffffff&autoplay=1',
        title:'Voir la video'
      });
      url.addEvent('click', self._showExternalContent);
      url.inject(el);
      
      var title = new Element('h3');
      title.set('text', video.title);
      title.inject(url);
      
      var img = new Element('img');
      img.set('src', video.thumbnail_small);
      img.inject(title, 'top');
      
      el.inject($('video'));
    });
  }
  // Affiche le lien en popup iframe
  , _showExternalContent : function(e) {
      e.stop();
      
      screenSize = window.getSize();
      
      var mask = new Element('div', {
        id:'mask',
        'class':'mask'
      });
      mask.setStyles({
        left:0,
        top:0
      });
      mask.inject($(document.body));
      
      var popup = new Element('div', {
        id:'popup',
        'class':'popup radius'
      });
      popup.setStyles({
        top:parseInt(screenSize.y/2),
        left:parseInt(screenSize.x/2)
      });
      popup.inject($('externalContent'));
      
      var iframe = new Element('iframe', {
        frameborder:'0',
        width:'800',
        height:'450',
        src:this.href
      });
      
      var openEffect = new Fx.Morph(popup, {
        duration: 'long',
        transition: Fx.Transitions.Expo.easeOut
      });
       
      openEffect.start({
        left:parseInt((screenSize.x/2)-400),
        top:parseInt((screenSize.y/2)-225),
        width:800,
        height:450
      }).chain(function() {
        iframe.inject(popup);
      });
      
      var closeLink = new Element('a', {
        id:"closeLink",
        'class':'case close'
      });
      closeLink.addEvent('click', function() {
        iframe.destroy();
        var closeEffect = new Fx.Morph(popup, {
          duration: 'long',
          transition: Fx.Transitions.Expo.easeIn
        });
        closeEffect.start({
          top:parseInt(screenSize.y/2),
          left:parseInt(screenSize.x/2),
          width:0,
          height:0
        }).chain(function() { 
          popup.destroy();
          mask.destroy();
          //supprime tous les events de touche
          window.removeEvents('keydown');
        });
      });  
      closeLink.inject(popup,'top');
      
      window.addEvent('keydown', function(event){
        if (event.key == 'esc') { 
          iframe.destroy();
          var closeEffect = new Fx.Morph(popup, {
            duration: 'long',
            transition: Fx.Transitions.Expo.easeIn
          });
          closeEffect.start({
            top:parseInt(screenSize.y/2),
            left:parseInt(screenSize.x/2),
            width:0,
            height:0
          }).chain(function() { 
            popup.destroy();
            mask.destroy();
          });
        }
      });
      
  }
});


/**
* Stock les infos de connexion à Flickr par l'url
*/
H2C.components.FlickrConnexion = new Class({

   /**
   * constructeur intialise des constantes
   */
  initialize: function(){
    this.flickrBaseUrl = 'http://api.flickr.com/services/rest/?';
    this.apikey = 'b9385370285e2a3cd3e5d69c12ae715e';
    this.user_id = '64262018%40N05';
  },
  /**
  *getters
  */
  getUrl: function(){
    return this.flickrBaseUrl;
  },
  getKey: function(){
    return this.apikey;
  },
  getId: function(){
    return this.user_id;
  }

});

/**
* Modèle de données de la gallerie photos
*/
H2C.components.Photo = new Class({

  initialize: function(){
    //Point d'entrée de l'application gallery
    this.getPhotoSets();
  },
  
  /**
  * Récupère la liste des albums photos et construit la liste de photos
  */
  getPhotoSets: function(){
    var self = this;
    var flickr = new H2C.components.FlickrConnexion();

    var RequestData = new Request.JSONP({
      url : flickr.getUrl()+'method=flickr.photosets.getList&api_key='+flickr.getKey()+'&user_id='+flickr.getId()+'&format=json',
      callbackKey: 'jsoncallback',
      onRequest: function(){
        $('photo').set('text', 'Loading...').addClass('log_load');
      },
      onComplete: function(jsonObj) {
        $('photo').empty().removeClass('log_load');
        var photoSetList = jsonObj.photosets.photoset;
        self.createGalleryList(photoSetList);
      }
    }).send();
  },
  
  /**
  * Créé la liste des galleries sur la page d'acceuil avec une image en thumbail
  */
  createGalleryList : function(photoSetList) {
    var self = this;
    
    photoSetList.each(function(photoSet) {
      
      var el = new Element('div.vimeo');
      
      var url = new Element('a', {
        name : photoSet.id,
        href : '',
        title:'Voir l\'album'
      });
      url.addEvent('click', self.getPhotosFromPhotoSetID);
      url.inject(el);
      
      var title = new Element('h3');
      title.set('text', photoSet.title._content);
      title.inject(url);
      
      var img = new Element('img');
      img.set('src', 'http://farm'+photoSet.farm+'.static.flickr.com/'+photoSet.server+'/'+photoSet.primary+'_'+photoSet.secret+'_t.jpg');
      img.inject(title, 'top');
      
      el.inject($('photo'));
    });
  },
    
  /**
  * Event qui Récupère la liste des photos d'un album et crée une nouvelle popup-gallerie
  */
  getPhotosFromPhotoSetID: function(e){
    e.stop();
    var flickr = new H2C.components.FlickrConnexion();
        
    var RequestData = new Request.JSONP({
      url : flickr.getUrl()+'method=flickr.photosets.getPhotos&api_key='+flickr.getKey()+'&photoset_id='+this.name+'&format=json',
      callbackKey: 'jsoncallback',
      onComplete: function(jsonObj) {
        
        var photoList = jsonObj.photoset.photo;
        new H2C.components.Gallery(photoList);
      }
    }).send();
  
  }

});


/**
* Gère une gallerie sous forme de popup contenant un album flickr
*/
H2C.components.Gallery = new Class({

  /**
  *constructeur, liste des photos
  */
  initialize: function(photoList){
    this.photoList = photoList;
    this.nbPhotos = photoList.length;
    this.photoIndex = 0;
    //creer la popup
    this.createPopup();
    //affiche la 1ere photo
    this.displayPhoto(this.photoIndex);
    this.toggle = 0;
  },
  
  /**
  * Créer la popup html
  */
  createPopup: function(){
    var self = this;
    
    var mask = new Element('div', {
      id:'mask',
      'class':'mask'
    });
    mask.inject($(document.body));

    var popup = new Element('div', {
      id:'popup',
      'class':'popup radius'
    });
    var screenSize = window.getSize();
    //positionne la popup au milieu de la fenêtre
    popup.setStyles({
      width:600,
      height:400,
      top:parseInt(screenSize.y/2-200),
      left:parseInt(screenSize.x/2-300)
    });
    popup.inject($('externalContent'));
    
    //creation du bouton de fermeture
    var closeLink = new Element('a', {
      id:"closeLink",
      'class':'case close'
    });
    closeLink.addEvent('click', self.closePopup.bind(self));
    closeLink.inject(popup,'top');
    
    //Ajout evenement sur le bouton echap
    window.addEvent('keydown', function(event){
      if (event.key == 'esc') {
        self.closePopup();
      }
    });
    
    //creation du bouton suivant
    var forwardLink = new Element('a', {
      id:"forwardLink",
      'class':'case forward',
      html : '▶'
    });
    //ajout evenement sur le bouton suivant
    forwardLink.addEvent('click', this.nextPhoto.bind(self));  
    forwardLink.inject(popup,'top');
    
    //Ajout evenement sur le bouton arrowleft
    window.addEvent('keydown', function(event){
      if (event.key == 'left') {
        self.backPhoto();
      }
    });
    
    //Ajout evenement sur le bouton arrowright
    window.addEvent('keydown', function(event){
      if (event.key == 'right') {
        self.nextPhoto();
      }
    });
    
  },
  
  /**
  * Créer une div contenant une image
  */
  createImageDiv: function(image){
    if (this.toggle == 0){
      this.toggle = 1
    } else {this.toggle = 0}
    
    //creation d'une div contenant une image dans la popup
    var divid = 'imgdiv'+this.toggle;
   
   /*var imgdiv = new Element('div', {
      id: divid,
      'class':'imgdiv'
    });*/
    
    var imgdiv = new Element('img', {
      src: image.src,
      id: divid,
      'class':'imgdiv'
    });
    //img.inject(imgdiv);
    
    return imgdiv;
  },
  
  /** 
  * Affiche la photo suivante
  */
  nextPhoto: function(){
    var forward = $('forwardLink');
    var popup = $('popup');

    //verifie si possible de passer à la photo suivante
    if (this.photoIndex < this.nbPhotos-1){
      this.photoIndex++;
      this.displayPhoto(this.photoIndex);          
    }
    
    //destruction du bouton suivant
    if (this.photoIndex == this.nbPhotos-1 && forward != null){
      forward.destroy();
    }
    
    //creation du bouton precedent
    if (this.photoIndex == 1){
      var backwardLink = new Element('a', {
        id:"backwardLink",
        'class':'case backward',
        html : '◀'
      });
      //ajout evenement sur le bouton precedent
      backwardLink.addEvent('click', this.backPhoto.bind(this));  
      backwardLink.inject(popup,'top');
    }
    
  },
  
  /** 
  * Affiche la photo précédente
  */
  backPhoto: function(){
    var backward = $('backwardLink');
    var popup = $('popup');
    
    //verifie si possible de passer à la photo precedente
    if(this.photoIndex > 0){
      this.photoIndex--;
      this.displayPhoto(this.photoIndex);          
    }
    
    //destruction du bouton precedent 
    if (this.photoIndex == 0 && backward != null){
      backward.destroy();
    }
    
    if (this.photoIndex == this.nbPhotos-2){
      //creation du bouton suivant
      var forwardLink = new Element('a', {
        id:"forwardLink",
        'class':'case forward',
        html : '▶'
      });
      //ajout evenement sur le bouton suivant
      forwardLink.addEvent('click', this.nextPhoto.bind(this));  
      forwardLink.inject(popup,'top');
    }
    
  },
  /**
  * Affiche la photo à partir de son index avec resize de la popup
  */
  displayPhoto: function(photoIndex){
    var self = this;
    var popup = ($('popup'));
    var imgdiv = $('imgdiv'+this.toggle);
    
    //1er cas, aucune image dans la div pas de fadeout
    if (imgdiv == null){ 
      var photo = this.photoList[photoIndex];
      var image = Asset.image('http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_z.jpg', {
        onload:function(){
          var newimgdiv = self.createImageDiv(image);
          newimgdiv.setProperties({
            width: 0,
            height: 0
          });
          newimgdiv.inject(popup);

          var screenSize = window.getSize();

          //morph popup
          var morphEffect = new Fx.Morph(popup, {
              duration: 'long',
              transition: Fx.Transitions.Expo.easeOut
          });
          morphEffect.start({
            left:parseInt((screenSize.x/2)-(image.width/2)),
            top:parseInt((screenSize.y/2)-(image.height/2)),
            width:image.width,
            height:image.height
          });
          
          //morph new img
          var morphImgEffect = new Fx.Morph(newimgdiv, {
              duration: 'long',
              transition: Fx.Transitions.Expo.easeOut
          });
          morphImgEffect.start({
            width:image.width,
            height:image.height
          });
          
          //dilution
          var fadeEffect = new Fx.Morph(newimgdiv, {
            duration: 'long',
            transition: Fx.Transitions.Sine
          });
          fadeEffect.start({'opacity': 1});         
        }
      });
    }
    //2sd cas, image dans la div, fadein-fadeout 
    else {
      
      var photo = this.photoList[photoIndex];
      
      var image = Asset.image('http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_z.jpg', {
        onload:function(){
          var oldimgdiv = $('imgdiv'+self.toggle);
          var newimgdiv = self.createImageDiv(image);
          newimgdiv.inject(popup);
          var screenSize = window.getSize();
          
          //morp de la popup          
          var morphEffect = new Fx.Morph(popup, {
              duration: 'long',
              transition: Fx.Transitions.Expo.easeOut
          });
          morphEffect.start({
            left:parseInt((screenSize.x/2)-(image.width/2)),
            top:parseInt((screenSize.y/2)-(image.height/2)),
            width:image.width,
            height:image.height
          });
          
          //dilution new image
          var fadeEffectNew = new Fx.Morph(newimgdiv, {
            duration: 'long',
            transition: Fx.Transitions.Sine
          });
          //dilution old image
          var fadeEffectOld = new Fx.Morph(oldimgdiv, {
            duration: 'long',
            transition: Fx.Transitions.Sine
          });
          
          fadeEffectOld.start({'opacity': 0}).chain(function() { 
            oldimgdiv.destroy();
          });
          
          fadeEffectNew.start({'opacity': 1});
        }
      });
      
    }
  },
  /**
  * Fermeture de la popup
  */
  closePopup : function(e) {    
    var imgdiv = $('imgdiv'+this.toggle);
    
    if (imgdiv != null){
      var screenSize = window.getSize();
      var popup = $('popup');
      var mask = $('mask');
      //effet de fermeture
      var closePopupEffect = new Fx.Morph(popup, {
        duration: 'long',
        transition: Fx.Transitions.Expo.easeIn
      });
      
      //effet de fermeture
      var imgScaleOutEffect = new Fx.Morph(imgdiv, {
        duration: 'long',
        transition: Fx.Transitions.Expo.easeIn
      });
      
      //dilution old image
      var fadeEffect = new Fx.Morph(imgdiv, {
        duration: 'long',
        transition: Fx.Transitions.Sine
      });
      fadeEffect.start({
        'opacity': 0
      }).chain( function() { 
        imgdiv.destroy();
      });
      
       //scaleout img
      imgScaleOutEffect.start({
        width:0,
        height:0
      });
      
      //scaleout popup
      closePopupEffect.start({
        top:parseInt(screenSize.y/2),
        left:parseInt(screenSize.x/2),
        width:0,
        height:0
      }).chain(function() { 
        popup.destroy();
        mask.destroy();
      });
      
    }
    //supprime tous les events de touche
    window.removeEvents('keydown');
  }

});


//---------------------------------------------------
//Class component FormAccordion
//---------------------------------------------------
H2C.components.Accordion = new Class({

    initialize: function(anchor){
    new Fx.Accordion($('date_filters_container'), 'div.toggler', 'div.element', {
        display : anchor,               // No layer display at Start
        initialDisplayFx: false,    // False : no effect at start
        alwaysHide: false,           // True : make all layer closed possible
        opacity: false,
        onActive: function(toggler, element){
            //toggler.setStyle('color', '#41464D');
            toggler.addClass('open');
            toggler.removeClass('close');
        },
        onBackground: function(toggler, element){
            toggler.addClass('close');
            toggler.removeClass('open');
            //toggler.setStyle('color', '#528CE0');
        }
    });
    }
});

