/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:1,interval:100,timeout:100};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);   



$(function() { 
    $('body').addClass('hasJs');
    
    //General Fix for share-social
    function fixSocialShare(selector) {
        var el = $(selector);
        socialPos = el.offset();
        if (!(ua.msie && ua.version.slice(0, 1) <= 7)) {
            $(window).bind('scroll', function(){
                windowTop = $(window).scrollTop();
                windowBottom = windowTop + $(window).height();
                if (windowTop > socialPos.top - 46) {
                    el.css({
                        'position': 'fixed',
                        'top': 46
                    });
                }
                else {
                    el.css({
                        'position': 'absolute',
                        'top': 46
                    });
                    
                }
            });
        }
        
    }
    
    
    /*form header*/
    var formHeader = $('#header .search');
        formHeader.addClass('form-minimize');
    
        formHeader.delegate('button', 'click', function(e){
            if ( formHeader.hasClass('form-minimize') ){
                formHeader.removeClass('form-minimize');
                e.preventDefault();
            }
        });
    
    
    var ua = $.browser;
    $('.external').attr('target', '_blank');
    // placeholder
    $('form.search, form.newsletter').each(function() {
        var self = $(this).find('.field-text');
        var placeholder = self.attr('value');
        self.bind({
            focus: function () {
                if (self.val() === placeholder) {
                    self.val('');
                }
            },
            blur: function () {
                if (self.val() === '') {
                    self.val(placeholder);
                }
            }
        });
    }); 
    
    $('.sub-header .dropdown').bind({
        mouseenter: function() {
            $('>a', this).addClass('open');
            $('.picker', this).show();
        },
        mouseleave: function() {
            $('>a', this).removeClass('open');
            $('.picker', this).hide();
        }
    });
    $('.sub-header .dropdown .picker').bind({
        mouseenter: function() {
            $(this).prev().addClass('open');
            $(this).show();
        }
    });
    
    
    // debats    
    isMoving=0;
    $(".slider-debat li:not(.expanded)").find('.heading-4, .heading-5').fadeTo(1,0.7);
    $('.slider-debat li').hoverIntent(function(){
            if ($(this).hasClass("expanded") == false) {
                if (isMoving == 0) {
                    isMoving = 1;
                    $$ = $(this).find("a");
                    $old = $(this).parent().find(".expanded a");
                    $$.animate({
                        width: 457
                    }, 150, function(){
                        $(this).parent().addClass("expanded");
                        $$.find('.teaser-3').show();
                    });
                    $old.animate({
                        width: 230
                    }, 150, function(){
                        $(this).parent().removeClass("expanded");
                        $old.find('.teaser-3').hide();
                        isMoving = 0
                    });
                    $$.find('.picture').animate({
                        left: 0
                    }, 150);
                    $old.find('.picture').animate({
                        left: -114
                    }, 150);
                    $$.find('.text').animate({
                        width: 417
                    }, 150);
                    $old.find('.text').animate({
                        width: 190
                    }, 150);
                    $$.find('.bubble-orange').fadeIn();
                    $old.find('.bubble-orange').fadeOut();
                    $$.find('.heading-4, .heading-5').fadeTo(300, 1);
                    $old.find('.heading-4, .heading-5').fadeTo(300, 0.7);
                }
            }
    }, function(){});
    
    //magazine
    if($('#mag-article .details .date').length) {   
        $('#mag-article .details .date').css({
            marginTop: $('#mag-article .heading-1').outerHeight(true)
        });
        
        if (!$('#evin').length) {
           $('#mag-article .share-social')
                .attr('style', "top: "+ ($('.heading-1').outerHeight(true) + 212 + 30) +"px; " +
                "_top:"+ ($('.heading-1').outerHeight(true)) +"px;"); 
        }
    } 
    
    if ($('#evin .share-social').length) {
        fixSocialShare('#evin .share-social');
    }

    var cellsMag = $('div.magazine-summary > div.cell');
   
    cellsMag.bind({
        'mouseenter' : function(){
            $(this).addClass('hover');
        },
        'mouseleave' : function(){
            $(this).removeClass('hover');
            $(this).find('span.view-all').hide()
        }
    });
    
    cellsMag.find('h3 a').bind({
       'mouseenter' : function(){

            $(this).parents('div.cell').find('span.view-all').show();
       },
       'mouseleave' : function(){
           $(this).parents('div.cell').find('span.view-all').hide()
       } 
    });
   
    
    $.fn.goToTop = function(options){
        var defaults = {};
        var opts = $.extend(defaults, options);
        return this.each(function(){
            $$ = $(this);
            $$.pos = $$.offset(); 
            $(window).bind('scroll', function() {
                windowTop = $(window).scrollTop();
                windowBottom = windowTop + $(window).height();
                if(windowTop>275 && windowBottom < $$.pos.top + 53 ) {
                    if($$.css('position')=='absolute' && windowTop<400) {
                        $$.hide().fadeIn("fast");
                    }
                    $$.css({
                        'position': 'fixed',
                        'bottom': 20
                    });
                } else {
                    function hideAnchor() {
                        $$.css({
                            'position': 'absolute',
                            'bottom': 32
                        });
                    }
                    if($$.css('position')=='fixed' && windowTop<275) {
                        $$.fadeOut("fast", hideAnchor);
                    } else {
                        hideAnchor();
                    }
                }
            });
            
            $$.click( function(){
                $.scrollTo( "#header", 1000 );
                return false;
            });
        });
    }; 
    if (!(ua.msie && ua.version.slice(0, 1) < 7)) {
        $('#go-to-top').goToTop();
    }
    
    $(".size a").click(function(){
        size = $(this).attr("id");
        $(this).addClass("active").siblings().removeClass("active");
        $(".content .rte")
            .removeClass("rte-small").removeClass("rte-medium").removeClass("rte-big")
            .addClass("rte-"+size);
        return false;
    });
    
    
    /*OFFICE*/
   if ( document.getElementById('office-members') ){
       var officePeople = {
           config : {
               'container'     : 'office-members',
               'lastCell'      : 'cell-last',
               'cell'          : 'cell',
               'cellException' : 'header',
               'content'       : 'infos-member',
               'wrapperContent': 'wrapper-member-description'
           },
           init : function(){
                var that = this;
                
                $('.' + this.config.lastCell, $('#'+this.config.container)).each(function(){
                    that.buildWrapper($(this));
                });
                
                $('.'+this.config.cell, $('#'+this.config.container)).not('.header').bind({
                    'click' : function(){
                        that.start($(this));
                        
                        return false;
                    }
                });
                
                $(document).bind({
                    'keydown':function(e){
                        switch(e.keyCode){
                            case 39 :
                                     if ( $('.'+that.config.wrapperContent+':visible').length > 0 ){
                                         that.goToNext();
                                     } else {
                                         $('.'+that.config.cell).not('.'+that.config.cellException).eq(0).click();
                                     }
                                     break;
                            case 37 : 
                                     if ($('.' + that.config.wrapperContent + ':visible').length > 0) {
                                        that.goToPrev();
                                     }
                                     
                                     break;
                        }
                    }
                })
           },
           buildWrapper : function(target){
               var that = this;
               var cursor = $('<span />',{
                                     'class' : 'icon icon-cursor'
                               });
                               
               var pager = $('<div />', {
                                'class' : 'office-pager'
                           });
               $('<a />', {
                  'class' : 'btn-close',
                  'href'  : '#'
               }).append($('<span />', {
                   'class' : 'icon icon-close',
                   text : 'Fermer'
               })).appendTo(pager)
                  .bind({
                      'click' : function(){
                          that.closeWrapper($(this));
                          
                          return false;
                      }
                  });
               
               $('<a />', {
                  'class' : 'btn-next',
                  'href'  : '#'
               }).append($('<span />', {
                   'class' : 'icon icon-arrow-next-big',
                   text : 'Suivant'
               }))
                  .appendTo(pager)
                  .bind({
                      'click' : function(){
                          that.goToNext();
                          
                          return false;
                      }
                  });
               
               $('<a />', {
                  'class' : 'btn-prev',
                  'href'  : '#'
               }).append($('<span />', {
                   'class' : 'icon icon-arrow-prev-big',
                   text : 'Précédent'
               }))
                 .appendTo(pager)
                 .bind({
                     'click' : function(){
                         that.goToPrev();
                         
                         return false;
                     }
                 })
                               
               var wrap = $('<div />', {
                              'class' : this.config.wrapperContent
                          }).append(cursor);
               wrap.append(pager).hide();
               target.after(wrap);
           },
           start : function(elem){
               if ($('div:animated, span:animated', $('#'+this.config.container)).length <= 0){
                   var nextWrapper = elem.nextAll('.'+this.config.wrapperContent).eq(0);
               
                   $('.'+this.config.cell+'.active', $('#'+this.config.container)).removeClass('active');
                   elem.addClass('active');
                   var cloneContent = $('.'+this.config.content, elem).clone();
                   nextWrapper.find('.'+this.config.content).remove().end().append(cloneContent);
                   this.showHideWrappers(elem, nextWrapper);
                   this.updateCursor(elem, nextWrapper);
                   this.updatePager(elem, nextWrapper);
               }
           },
           showHideWrappers : function(elem, nextWrapper){
               var that = this;
               
               if (elem.siblings('.'+this.config.wrapperContent+':visible').not(nextWrapper).length){
                   
                   elem.siblings('.'+this.config.wrapperContent+':visible').not(nextWrapper).slideUp( 500, function(){
                       that.scrollTarget(elem)
                       nextWrapper.slideDown(500, function(){
                           that.scrollTarget(elem);
                           that.updateCursor(elem, nextWrapper);
                       });
                   });
               } else {
                   that.scrollTarget(elem)
                   nextWrapper.slideDown(500, function(){
                       that.scrollTarget(elem)
                       that.updateCursor(elem, nextWrapper);
                   });
               }
           },
           updateCursor : function(elem, wrapper){
               var cursor = wrapper.find('.icon-cursor');
               var dx = Math.ceil((elem.outerWidth()/2) - (cursor.outerWidth()/2));
               var posX = elem.position().left - 20;
               cursor.stop().animate({
                   'left' : posX+dx
               });
           },
           closeWrapper : function(context){
               context.parents('.'+this.config.wrapperContent).slideUp();
               $('.'+this.config.cell+'.active', $('#'+this.config.container)).removeClass('active');
           },
           goToNext : function(){
               var target = $('div.'+this.config.cell+'.active', $('#'+this.config.container)).nextAll('div.'+this.config.cell).eq(0);
               target.click();
           },
           goToPrev : function(){
               var target = $('div.'+this.config.cell+'.active', $('#'+this.config.container)).prevAll('div.'+this.config.cell).not('.header').eq(0);
               target.click();
           },
           scrollTarget : function(target) {
               $('html, body').animate({
                   scrollTop : target.offset().top-60
               },{duration:500, queue:false})
           },
           updatePager : function(elem, nextWrapper){
               var btnNext = nextWrapper.find('a.btn-next');
               var btnPrev = nextWrapper.find('a.btn-prev');
               //enable - disable prev
               if (elem.prev('div.cell').hasClass('header')){
                   btnPrev.addClass('inactive')
               } else {
                   btnPrev.removeClass('inactive')
               }
               //enable disable next
               if ( elem.nextAll('div.cell').length <= 0 ){
                   btnNext.addClass('inactive')
               } else {
                   btnNext.removeClass('inactive')
               }
           }
        }
        
        officePeople.init();
   }


    /* Accordion */
    $('.accordion > li').bind({
        mouseenter: function() {
            $(this).addClass("hover");
        },
        mouseleave: function() {
            $(this).removeClass("hover");
        },
        click: function() {
            if($(this).hasClass("expanded")) {
                $$ = $(this)
                $(this).find('.accordion-content').slideUp("fast", function(){
                    $$.removeClass("expanded");
                });
            } else {
                $('.accordion li.expanded').removeClass('expanded')
                                             .find(".accordion-content").slideUp("fast");
                $(this).addClass("expanded");
                $(this).find('.accordion-content').slideDown("fast");
            }
        }
    });

    $('a[rel*=external]').click( function() {
        window.open(this.href);
        
        return false;
     });
    
    $(".inner-chiffres .case").each(function() {
        if(($(this).find('.rte').length)) {
            $(this).bind({
                mouseenter: function() {
                    if($(this).hasClass('case-on')==false) {
                        $("body").css("cursor","pointer");
                        $(this).find('.picture, .theme').fadeTo(100,0.4);
                        var position = $(this).find('.picture').position();
                        $(this).find('.more').css({
                            left:position.left+(($(this).find('.picture').width()-51)/2),
                            top:position.top+(($(this).find('.picture').height()-71)/2)
                        }).fadeIn(100);
                    }
                },
                mouseleave: function() {
                    $("body").css("cursor","auto");
                    $(this).find('.picture, .theme').fadeTo(100,1);
                    $(this).find('.more').fadeOut(100);
                },
                click: function() {
                    $$ = $(this); 
                    $(".inner-chiffres .case-on").each(function(){
                        $old = $(this).removeClass('case-on');
                        $old.css({
                            top: parseInt($old.css("top")) + 20,
                            left: parseInt($old.css("left")) + 20
                        });
                    });
                    $$.find('.picture, .theme').fadeTo(100,1);
                    $$.find('.more').hide();
                    if ($$.hasClass("case-on") == false) {
                        $$.addClass('case-on').css({
                            top: parseInt($$.css("top")) - 20,
                            left: parseInt($$.css("left")) - 20
                        });
                    }
                }
            });
        }
    });
    $(".inner-chiffres .case .icon-close").click(function(){
        $$ = $(this).parent().removeClass('case-on');
        $$.css({
            top: parseInt($$.css("top")) + 20,
            left: parseInt($$.css("left")) + 20
        });
        return false;
    });
    
    
    /*carousel-home*/
   if (document.getElementById('carousel-home')){
       var carousel = {
           config : {
               carouselContainer : 'carousel-home',
               carouselId : 'carousel-home-list',
               carouselItems : 'li',
               carouselItemPicture : 'lnk-picture',
               carouselItemContent : 'carousel-item-content',
               carouselItemHeight : 275,
               speedImg : 600,
               speedContent : 400,
               speedAuto : 10000
           },
           init : function(){
               this.items = $('#' + this.config.carouselId + ' ' + this.config.carouselItems);
               this.config.carouselItemsNumbers = this.items.size();
               
               if (this.config.carouselItemsNumbers > 1) {
                   this.current = 1;
                   this.cloneElements();
                   this.buildView();
                   this.hideElement($('#'+this.config.carouselId));
                   this.autoSlideShow();
               }
           },
           buildView : function(){
               var view = $('<div />',{
                   'class' : 'wrapper-outer-carousel'
               });
               var viewInner = $('<div />',{
                   'class' : 'wrapper-inner-carousel'
               });
               
               /*-*/
              //img and content

               var imgInit = this.carouselClones[0].picture;
               var contentInit = this.carouselClones[0].content;
               var wrapperContent = $('<div />', {
                   'class': 'inner-carousel-item'
               });

               imgInit.appendTo(viewInner);
               contentInit.appendTo(wrapperContent);
               
               $('<span />', {
                   'class' : 'icon icon-carousel-arrow-white'
               }).appendTo(wrapperContent);

               wrapperContent.appendTo(viewInner);
               viewInner.appendTo(view);
               viewInner.wrapInner('<div class="wrap-item"></div>');
               
               /*-pager*/
               var pager = this.buildPager();
                   pager.appendTo(view);
               
               /*prev next*/
               var prevNext = this.buildPrevNext();
                   prevNext.appendTo(view);
               view.prependTo($('#' + this.config.carouselContainer));
           },
           buildPager : function(){
               var that = this;
               var pagerList = $('<ul />',{
                   'class' : 'pager-list'
               });

               for ( var i = 1, len = this.config.carouselItemsNumbers; i <= len; i++ ){
                    var active = (i == 1) ? 'active' : '';
                    var first  = (i == 1) ? 'first' : '';
                    var last  = (i == this.config.carouselItemsNumbers) ? 'last' : '';
                    var itemsListEl = $('<li/>', {
                        'class': 'item-'+i+' '+active+' '+first+' '+last,
                        html: '<a href="#" class="icon">'+i+'</a>'
                    }).bind({
                        'click' : function(){
                            var index = that.getIndex($(this));
                            that.prepareGoTo(index);
                            
                            return false
                        }
                    });

                    itemsListEl.appendTo(pagerList);
               }
               
               return pagerList;
           },
           buildPrevNext : function() {
               var that = this;
               var nextprevList = $('<ul/>', { 'class':'carousel-prev-next'});
               var nextprevPrev = $('<li/>', {
                        'class': 'carousel-prev',
                        html: '<a href="#" class="icon">Previous</a>'
                    }).bind({
                        'click' : function(){
                            that.prepareGoTo(that.current-1);
                            
                            return false;
                        }
                    })
                    .appendTo(nextprevList);
                    
               var nextprevNext = $('<li/>', {
                        'class': 'carousel-next',
                        html: '<a href="#" class="icon">Next</a>'
                    }).bind({
                        'click' : function(){
                            that.prepareGoTo(that.current+1);
                            
                            return false;
                        }
                    }).appendTo(nextprevList);
               
               return nextprevList;
           },
           hideElement : function(elem){
               elem.hide();
           },
           cloneElements : function(){
               this.carouselClones = [];
               for ( var i=0, len = this.items.length; i < len ; i++ ) {
                   var contentToPush = {};
                       contentToPush.picture = $(this.items[i]).find('.' + this.config.carouselItemPicture);
                       contentToPush.content = $(this.items[i]).find('.' + this.config.carouselItemContent);
                       this.carouselClones.push(contentToPush);
               }
           },
           prepareGoTo : function(nextIndex){
               if ( $('.wrap-item :animated').length <= 0 && nextIndex != this.current) {
                   if ( nextIndex > this.current ){
                       if ( nextIndex > this.config.carouselItemsNumbers ){
                           nextIndex = 1;
                       }
                       this.goTo(nextIndex, 1);
                   } else {
                       if ( nextIndex <= 0 ){
                           nextIndex = this.config.carouselItemsNumbers
                       }
                       this.goTo(nextIndex, 0);
                   }
               }
           },
           goTo : function(index, direction){
               var that = this;
               //direction : 0 = prev, 1 = next
               var newImg = this.getImage(index);
               var newContent = this.getContent(index);

               if ( direction ) {
                   
                   newImg.prependTo($('.wrap-item'))
                         .css({
                             'top' : -that.config.carouselItemHeight+'px'
                         }).addClass('current');
               } else {
                   newImg.prependTo($('.wrap-item'))
                         .css({
                             'top' : that.config.carouselItemHeight+'px'
                         }).addClass('current');
               }
               $('.wrap-item .'+that.config.carouselItemPicture).each(function(i){
                    var oldTop = parseInt($(this).css('top')),
                        newTop = (direction) ? oldTop + that.config.carouselItemHeight : oldTop - that.config.carouselItemHeight;

                    $(this).animate({
                       'top' : newTop 
                   },that.config.speedImg);
               });
                   
               $('.wrap-item .inner-carousel-item ' + '.' + that.config.carouselItemContent).fadeOut(that.config.speedContent, function(){
                   $(this).remove();
                   $('.wrap-item .'+that.config.carouselItemPicture).not(':first').removeClass('current');
                   that.showContent(newContent);
               });
               
               this.updateActivePagerItem(index);
               this.current = index;
           },
           getImage : function(key){
               return this.carouselClones[key-1].picture;
           },
           getContent : function(key){
               return this.carouselClones[key-1].content;
           },
           showContent : function(content){
               var that = this;
               content.appendTo($('.wrap-item .inner-carousel-item')).hide().fadeIn(that.config.speedContent);
           },
           updateActivePagerItem : function(index){
               $('.pager-list .active').removeClass('active');
               $('.pager-list .item-' + index).addClass('active');
           },
           getIndex : function(elem){
               return parseInt(elem.find('a').html());
           },
           autoSlideShow : function(){
               var that = this;
               var slideShowTimer = setInterval(function(){
                                                              that.prepareGoTo(that.current+1);
                                                          }, 10000); 
           }
       }
       carousel.init();
   }
    
    if($('#manifesto').length) {
        $('#manifesto .inner-manifesto .sign a').click(function(){
            $('#sign-form-wrapper').slideDown(function() {
                    $('.inner-manifesto .sign').slideUp();
            });
            return false;
        })
        
        if ($('#manifesto .share-social').length) {
            fixSocialShare('#manifesto .share-social');
        }
        
        $('.signatures .signature-comment').bind({
            mouseenter: function() {
                $$ = $(this).parent();
                $('.comment', $$).css('left', ($(this).outerWidth()-220)/2).show();
            },
            mouseleave: function() {
                $$ = $(this).parent();
                $('.comment', $$).hide();
            }
        });
    }
    
    
    
});
