/**
 * Staragora Javascript functions
 *
 * @package    staragora
 * @subpackage web.js
 * @author     WebPulse <contact@webpulse.fr>
 * @copyright  WebPulse 
 * @version    Svn: $Id: staragora.js 17439 2011-11-04 16:55:40Z vincent $
 */

// ** Staragora functions
function decode_utf8( s ) { return decodeURIComponent( escape( s ) ); }

/* -- formulaires email -- */
var Formulaire={Submit:function(formContainer,home){var Form=formContainer.getElement('form'),Log=formContainer.getElement('span.log_response');Form.addEvent('submit',function(event){new Event(event).stop();Log.empty();var LogFx=(home===true)?new Fx.Slide(Log,{mode:'vertical'}).hide():new Fx.Slide(Log,{mode:'horizontal'}).hide();new Request.HTML({url:Form.action,update:Log,onComplete:function(){(function(){LogFx.slideOut();}).delay(3000);},onSuccess:function(){var Resp=this.response.text;if(Resp.length>1){Log.setStyle('display','block');LogFx.slideIn();}}}).post(Form);cashmachine();});}};

/* --  wpGameFacetoFace inviter un ami -- */
var FormFtF={Submit:function(formElem){var Form=formElem,Log=$('log_container').getElement('span');Form.addEvent('submit',function(event){new Event(event).stop();Log.empty();var LogFx=new Fx.Slide(Log,{mode:'horizontal'}).hide();new Request.HTML({url:Form.action,update:Log,onComplete:function(){(function(){LogFx.slideOut();}).delay(3000);},onSuccess:function(){var Resp=this.response.text;if(Resp.length>1){Log.setStyle('display','block');LogFx.slideIn();}}}).post(Form);});}};

/* -- formulaire popup --*/
var Form={Submit:function(formContainer,home){var Form=formContainer.getElement('form'),Log=formContainer.getElement('span.log_response');Form.addEvent('submit',function(event){new Event(event).stop();Log.empty();
Log.setStyle('display','block');var LogFx=(home===true)?new Fx.Slide(Log,{mode:'vertical'}).hide():new Fx.Slide(Log,{mode:'horizontal'}).hide();new Request.HTML({url:Form.action,update:Log,onComplete:function(){(function(){LogFx.slideOut();}).delay(3000);},onSuccess:function(responseText, responseXML){Log.setStyle('display','block');LogFx.slideIn();if(responseXML.getProperty('id')=='nlsuccess'){(function(){$('popupsubcription').setStyle('display','none');$('register_overlay').setStyle('display','none');}).delay(4000);}}}).post(Form);});}};

/* -- formulaire astro -- */
var FormAstro={Submit:function(formContainer){var Form=formContainer.getElement('form'),log_email=formContainer.getElementById('astrolog_email'),log_date=formContainer.getElementById('astrolog_date'),log_valid=formContainer.getElementById('astrolog_valid');Form.addEvent('submit',function(event){new Event(event).stop();log_email.empty();log_date.empty();log_valid.empty();

new Request({
  url:Form.action,
  onSuccess:function(responseText, responseXML){
    var xml = responseXML.documentElement;
    var mynode = xml.getElementsByTagName('err_email').item(0);
    
    log_email.setStyle('display','block');
    log_date.setStyle('display','block');
    log_valid.setStyle('display','block');
    var no_error='';
    
    if(xml.getElementsByTagName('nlastrosuccess').item(0) != null) {
      no_error = xml.getElementsByTagName('nlastrosuccess').item(0).firstChild.nodeValue;
    

      if(no_error!=''){
        var valid_icon = '';
        var item = xml.getElementsByTagName('valid_icon').item(0);
          if(item != null){
            valid_icon='<img src="'+item.firstChild.nodeValue+'" alt="valid icon" />';
          }
      }
    
      log_valid.innerHTML=valid_icon+no_error;
      (function(){$('popupsubcription').setStyle('display','none');$('register_overlay').setStyle('display','none');}).delay(4000);
      
      }else{
        var err_icon = '';
        var item = xml.getElementsByTagName('err_icon').item(0);
        if(item != null){
          err_icon='<img src="'+item.firstChild.nodeValue+'" alt="error icon" />';
        }
        
        var item = xml.getElementsByTagName('err_email').item(0);
        if(item != null){
          log_email.innerHTML=err_icon+item.firstChild.nodeValue;
        }
        
        var item = xml.getElementsByTagName('err_date').item(0);
        if(item != null){
          log_date.innerHTML=err_icon+item.firstChild.nodeValue;
        }
        
      }}}).post(Form);
      
      });
    }};
  
/* -- plugin diaporama -- */
var MorphList=new Class({Implements:[Events,Options],options:{morph:{'link':'cancel'}},initialize:function(menu,options){var that=this;this.setOptions(options);this.menu=$(menu);this.menuitems=this.menu.getChildren();this.menuitems.addEvents({mouseenter:function(){that.mouseenter(this);},mouseleave:function(){that.morphTo(that.current);}});this.bg=new Element('li',{'class':'background'}).adopt(new Element('div',{'class':'left'}).set('text','.'));this.bg.fade('hide').inject(this.menu).set('morph',this.options.morph);this.setCurrent(this.menu.getElement('.current'));},mouseenter:function(ev,item){this.setCurrent(item,true);},setCurrent:function(el,effect){if(el&&!this.current){this.bg.set('styles',{left:el.offsetLeft,width:el.offsetWidth,height:el.offsetHeight,top:el.offsetTop});(effect)?this.bg.fade('hide').fade('in'):this.bg.setOpacity(1);}if(this.current)this.current.removeClass('current');if(el)this.current=el.addClass('current');},morphTo:function(to){if(!this.current)return;this.bg.morph({left:to.offsetLeft,top:to.offsetTop,width:'300',height:'300'});this.fireEvent('onMorph',to);}});

var Slideshow=new Class({Extends:MorphList,options:{auto:true,autostart:true,autointerval:4000,transition:'fade',tween:{duration:500}},initialize:function(menu,images,loader,options){this.parent(menu,options);this.images=$(images);this.imagesitems=this.images.getChildren().fade('hide');$(loader).fade('in');new Asset.images(this.images.getElements('img').map(function(el){return el.toggleClass('blocknone').get('src');}),{onComplete:function(){this.loaded=true;$(loader).fade('out');if(this.current)this.show(this.menuitems.indexOf(this.current));else if(this.options.auto&&this.options.autostart)this.progress();}.bind(this)});if($type(this.options.transition)!='function'){this.options.transition=$lambda(this.options.transition);}},auto:function(){if(!this.options.auto){return false;}$clear(this.autotimer);this.autotimer=this.progress.delay(this.options.autointerval,this);},mouseenter:function(item){this.parent(item);this.show(this.menuitems.indexOf(item));$clear(this.autotimer);},show:function(index){if(!this.loaded){return;}var image=this.imagesitems[index];if(image===this.curimage){return;}image.set('tween',this.options.tween).dispose().inject((this.curimage||this.images.getFirst()),(this.curimage?'after':'before')).fade('hide');image.getElement('img').setStyle('display','block');image.getElement('a').setStyle('display','block');var trans=this.options.transition.run(null,this).split('-');switch(trans[0]){case 'slide':var dir=$pick(trans[1],'left');var prop=((dir==='left'||dir==='right')?'left':'top');image.fade('show').setStyle(prop,image['offset'+(prop==='left'?'Width':'Height')]*((dir==='bottom'||dir==='right')?1:-1)).tween(prop,0);break;case 'fade':image.fade('in');break;}image.get('tween').chain(function(){this.auto();this.fireEvent('show',image);}.bind(this));this.curimage=image;this.setCurrent(this.menuitems[index]);this.morphTo(this.menuitems[index]);return this;},progress:function(){var curindex=this.imagesitems.indexOf(this.curimage);this.show((this.curimage&&(curindex+1<this.imagesitems.length))?curindex+1:0);}});

/* -- survol d'elements -- */
var doHover={buttonHover:function(element,newClass){$$(element).each(function(e){e.addEvent('mouseenter',function(){e.addClass(newClass);});e.addEvent('mouseleave',function(){e.removeClass(newClass);});});}};


/* -- character count inside textareas -- */
var countCharacters={doCount:function(input,output,max){max=max||512;var myText=input.value;if(max>myText.length){output.innerHTML=max-myText.length;}else{output.innerHTML="0&nbsp;";}}};


/* -- carousel vignettes photos -- */
var moovignettes_frame = new Class ({
  Implements: [Events, Options],
  options: {
    onNext      : Class.empty,
    onPrev      : Class.empty,
    onStart     : Class.empty,
    direction   : 'horizontal',
    transition  : Fx.Transitions.linear,
    duration    : 500,
    mode        : 'butts',
    mousePlay   : false,
    progressBy  : 4,
    butts       : {
      nextB   : 'vignette_next',
      prevB   : 'vignette_previous'
    },
    items       : {
      space   : 0,
      width   : 105,
      height  : 105
    }
  },
  initialize: function(ziCarrousel, ziItemConteneur, ziItems, options) {
    this.setOptions(options);
    this.carrou   = $(ziCarrousel);
    this.defil    = $(ziItemConteneur);
    this.items    = ($$('.' + ziItems) || []);
    this.current  = $$('.vignette_active');
    this.itemsNum = this.items.length;
    this.itemsRW  = (this.options.items.width + this.options.items.space);
    this.itemsRH  = (this.options.items.height + this.options.items.space);
    this.sectionW = (this.itemsNum * this.itemsRW);
    this.sectionH = (this.itemsNum * this.itemsRH);
    this.dn       = this.options.progressBy;

    if (this.items.length > 5) {
      (2).times(function(){
        this.items.each(function(el){
          el.clone().inject(this.defil, 'bottom');
        }.bind(this));
      }.bind(this));
    } else {
      (1).times(function(){
        this.items.each(function(el){
          el.clone().inject(this.defil, 'bottom');
        }.bind(this));
      }.bind(this));

    }
    
    switch (this.options.direction) {
      case "horizontal" :
        this.defil.setStyles({
          'width'    : (this.sectionW * 3),
          'position' : 'absolute',
          'left'     : (-this.sectionW)
        });
        break;
      case "vertical" :
        this.defil.setStyles({
          'height'   : (this.sectionH * 3),
          'position' : 'absolute',
          'top'      : (-this.sectionH)
        });
        break;
    }

    if (this.options.mode == "butts") {
      $(this.options.butts.nextB).addEvent('click', function(e){
        e.stop();
        this.toNext();
      }.bind(this));
      $(this.options.butts.prevB).addEvent('click', function(e){
        e.stop();
        this.toPrev();
      }.bind(this));
    }

    this.fireEvent('onStart');
    this.defilFx = new Fx.Tween(this.defil, {
      transition : (this.options.transition),
      duration   : (this.options.duration),
      link       : 'ignore',
      onComplete : function(){
        this.repos();
        this.compEvent();
      }.bind(this)
    });

    this.compEvent = function() {
      this.fireEvent('onNext');
    };
    this.defilPos = this.defil.getPosition(this.current[0]);
    this.defilFx.start('left', this.defilPos.x);
    
  },

  repos: function(){
    this.defilPos = this.defil.getPosition(this.carrou);
    if (this.options.direction == "horizontal"){
      if (this.defilPos.x <= (-this.sectionW * 2)) {
        this.defil.setStyle('left', this.defilPos.x + this.sectionW);
      }
      if (this.defilPos.x >= (-this.itemsRW * this.dn)) {
        this.defil.setStyle('left', this.defilPos.x - this.sectionW);
      }
    }
    if (this.options.direction == "vertical"){
      if (this.defilPos.y <= (-this.sectionH * 2)) {
        this.defil.setStyle('top', this.defilPos.y + this.sectionH);
      }
      if (this.defilPos.y >= (-this.itemsRH * this.dn)) {
        this.defil.setStyle('top', this.defilPos.y - this.sectionH);
      }
    }
  },

  toNext: function(){
    this.compEvent = function(){ this.fireEvent('onNext'); };
    this.defilPos = this.defil.getPosition(this.carrou);
    if (this.options.direction == "horizontal"){
      this.defilFx.start('left', this.defilPos.x - (this.itemsRW * this.dn));
    }
    if (this.options.direction == "vertical"){
      this.defilFx.start('top', this.defilPos.y - (this.itemsRH * this.dn));
    }
  },

  toPrev: function(){
    this.compEvent = function(){ this.fireEvent('onPrev'); };
    this.defilPos = this.defil.getPosition(this.carrou);
    if (this.options.direction == "horizontal"){
      this.defilFx.start('left', this.defilPos.x + (this.itemsRW * this.dn));
    }
    if (this.options.direction == "vertical"){
      this.defilFx.start('top', this.defilPos.y + (this.itemsRH * this.dn));
    }
  }
});

/* -- chargement google catcher en ajax -- */
var gcatcher={
  element:'',
  url:'',
  Load:function(element,url,flux){
    Referer = $(document).referrer;
    if(element === null || Referer.indexOf("google") < 0){
      return false;
    }
    new Request.HTML({
      method:'post',
      url:url,
      onRequest:function(){
       
        element.setStyle('display','block');
      },
      onSuccess:function(responseTree,responseElements,responseHTML,responseJavaScript){
        element.innerHTML=responseHTML;
       }
     }).post(url + '?flux=' + flux + '&referer=' + Base64.encode(Referer));
     
   }   
};

/* -- base 64 encode -- */
var Base64 = {

  // private property
  _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

  // public method for encoding
  encode : function (data) {
  // http://phpjs.org/functions/base64_encode:358
        
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }
    
    data += '';
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = this._keyStr.charAt(h1) + this._keyStr.charAt(h2) + this._keyStr.charAt(h3) + this._keyStr.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch (data.length % 3) {
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
  },

  // public method for decoding
  decode : function (data) {
  // http://phpjs.org/functions/base64_decode:357


    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do {  // unpack four hexets into three octets using index points in b64
        h1 = this._keyStr.indexOf(data.charAt(i++));
        h2 = this._keyStr.indexOf(data.charAt(i++));
        h3 = this._keyStr.indexOf(data.charAt(i++));
        h4 = this._keyStr.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');

    return dec;
  } 
  
};

/* -- autocompleter -- */
var WpAutocomplete={
  element:'',
  url:'',
  Load:function(element,url,choices){
    if(choices != parseInt(choices)){
      choices = 10;
    }
  }   
};

var MooCarousel=new Class({
  Implements: [Events, Options],
  wrapper:'',
  items:'',
  moveleft:'',
  moveright:'',
  slides:2,
  offset:350,
  currentslide:1,
  pos:0,
  ispaged:false,

  initialize:function(wrapper, items, moveleft, moveright, ns, sss, ispaged) {
    this.wrapper=$(wrapper);
    this.items=$(items);
    this.moveleft=$(moveleft);
    this.moveright=$(moveright);
    this.slides=ns;
    this.offset=sss;
    this.ispaged=ispaged;
    this.parent=this.wrapper.getParent();
    this.scroll=new Fx.Scroll(this.wrapper, {offset:{'x':0,'y':0}});
    this.dir="right";
    var that=this;
    if (this.ispaged) {
      this.carousel_paging=new Element('div').addClass('carousel_paging');
      this.carousel_paging.id=this.wrapper.id+"_p";
      for(i=1;i<=parseInt(this.slides);i++) {
        var aa=new Element('a').addClass('page');
        if(i==1){
          aa.className="current";
        }
        aa.href="javascript:void(0);";
        aa.addEvent('click',this.page.bind(this,[i,aa,this.carousel_paging]));
        aa.innerHTML=i;
        aa.injectInside(this.carousel_paging);
      }
      this.carousel_paging.injectAfter(this.parent);
      var carousel_fix=new Element('div').addClass('clearfix').injectBefore(this.carousel_paging);
      var carousel_fix=new Element('div').addClass('clearfix').injectInside(this.carousel_paging);
    }
    if(this.currentslide>=this.slides){
      this.moveright.getElement('img').setStyle('visibility','hidden');
      this.moveleft.getElement('img').setStyle('visibility','visible');
    }
    if(this.currentslide==1){
      this.moveleft.getElement('img').setStyle('visibility','hidden');
      this.moveright.getElement('img').setStyle('visibility','visible');
    }
    if(this.slides==0){
      this.moveleft.getElement('img').setStyle('visibility','hidden');
      this.moveright.getElement('img').setStyle('visibility','hidden');
    }
    if(this.currentslide==this.slides){
      this.moveright.getElement('img').setStyle('visibility','hidden');
    }
    this.moveleft.addEvent('click',this.domoveleft.bind(this));
    this.moveright.addEvent('click',this.domoveright.bind(this));
  },

  domoveleft:function(event){
    event=new Event(event).stop();
    if(this.currentslide==1){return;}
    this.currentslide--;
    if(this.ispaged){
      this.setcss('left');
      this.dir='left';
    }
    this.pos+=-(this.offset);
    this.scroll.start(this.pos);
    this.doScrollLeft();
  },

  doScrollLeft:function(){
    this.moveright.getElement('img').setStyle('visibility','visible');
    if(this.currentslide==1){
      this.moveleft.getElement('img').setStyle('visibility','hidden');
    }
    this.scroll.toLeft();
  },

  domoveright:function(event){
    event=new Event(event).stop();
    if(this.currentslide>=this.slides){return;}
    this.currentslide++;
    if(this.ispaged){
      this.setcss('right');
      this.dir='right';
    }
    this.pos+=this.offset;
    this.scroll.start(this.pos);
    this.doScrollRight();
  },

  doScrollRight:function(){
    this.moveleft.getElement('img').setStyle('visibility','visible');
    if(this.currentslide>=this.slides){
      this.moveright.getElement('img').setStyle('visibility','hidden');
    }
    this.scroll.toLeft();
  },

  page:function(pagenum,o,p){
    var sss=((pagenum-1)*this.offset);
    if(pagenum>this.slides){return;}
    if(pagenum==1){sss=0;}
    this.currentslide=pagenum;
    this.pos=sss;
    this.scroll.start(this.pos);
    this.scroll.toLeft();
    this.resetcss(o,p);
  },

  setcss:function(dir){
    var x=parseInt(this.currentslide)-1;
    if(x<0){x=0;}
    if(x>9){x=9;}
    var o=this.carousel_paging.getElements('a')[x];
    this.resetcss(o,this.carousel_paging);
  },

  resetcss:function(o,p){
    var cpa=p.getElements('a');
    cpa.each(function(el,i){el.className="page";});
    o.className="current";
  }
});


//
// @todo : ne semble plus être utilisée
//
function getCookieVal(offset){
  var endstr=document.cookie.indexOf(";",offset);
  if(endstr==-1){
    endstr=document.cookie.length;
  }
  return unescape(document.cookie.substring(offset,endstr));
}

//
// @todo : ne semble plus être utilisée
//
function LireCookie(nom) {
  var arg=nom+"=",
      alen=arg.length,
      clen=document.cookie.length,
      i=0;
  while(i<clen){
    var j=i+alen;
    if(document.cookie.substring(i,j)==arg){
      return getCookieVal(j);
    }
    i=document.cookie.indexOf(" ",i)+1;
    if(i==0){
      break;
    }
  }
  return null;
}


// 
// Affichage Ajax de la navigation
// Précédent / Suivant dans les articles
//
var NewsNavig = {
  elements: '',
  url: '',
  Load:function(classname,url){
    elements = $$('.' + classname);
    new Request.HTML({
      method:'get',
      url:url,
      onSuccess:function(responseTree,responseElements,responseHTML,responseJavaScript){
        for(i in elements) {
          var element = elements[i];
          element.innerHTML=responseHTML;
        }
       }
     }).get();
  }
};


//
// Masquage des liens
//
function staragorie(var1, var2) {
  return Base64.decode(var1)+Base64.decode(var2);
}

//
//Popup cash machine
//
function cashmachine() {
  return false;
}

function cm_confirm(fluxId) {
  if( Cookie.read('cm-' + fluxId) != null){
    window.addEvent('domready',cashmachine);
  }
}

//
// Stop refresh
//
function stopRefresh() {
  if(window.timer){
    window.clearTimeout(window.timer);
  }
  
  if(window.autoRoll){
    window.clearTimeout(window.autoRoll);
  }
}

var IE6 = (navigator.userAgent.toLowerCase().indexOf('msie 6') !=- 1);

var IE = (navigator.userAgent.toLowerCase().indexOf('msie 6') !=- 1 ||
          navigator.userAgent.toLowerCase().indexOf('msie 7') !=- 1);


window.addEvent('domready', function() {

  // Positionne correctement la page en cas d'erreur de formulaire
  if ($('error_focus')) {
    var loc = window.location.href;
    if (loc.search(/\#/) == -1) {
      loc = loc + '#what_mind';
    }
    window.location.href = loc;
  }
    
});

