var loe;
if(!loe) {
    loe = {};
}
(function($) {
    var global = this,
        win = global.window,
        doc = win.document,
        box = global.box,
        loe = global.loe,
        l10n = global.l10n,
        SCREEN_WIDTH = global.SCREEN_WIDTH,
        BASE_URL = global.BASE_URL,
        BASE_SKIN_URL = global.BASE_SKIN_URL,
        FB_APPID = global.FB_APPID,
        ie6 = global.ie6,
        ie7 = global.ie7;
    
    doc.documentElement.id = 'js';
    
    var jWin = $(win),
        jDoc = $(doc),
        jBody, jHeader, jFooter, jCore, jVisual, jCarousel, jCurrentRollover, resizeTimer, jContextual,
        nCoreWidth, nCoreHeight, nWinWidth, nWinHeight, screenWidth,
        setContextualInCenter, nFooterHeight, maxCoreHeight,
        preloadVisual, insertVisual, jVisualHeight = 0,
        headerButtonMenu = $('#header-display-main-nav');
        
    loe.jDoc = jDoc;
    
    var footerHeaderPosition = loe.footerHeaderPosition = function(nWinHeight,nHeaderHeight,nFooterHeight){
        var globalH = nWinHeight - nHeaderHeight - nFooterHeight;
        var pos;

        if(jVisual.height()<globalH){
            
            var difHeight = Math.round((globalH-jVisual.height())/2);

            jBody.css('paddingTop',difHeight);

            if (ie7||ie6) {
                pos = jCore.offset();
                jHeader.css({
                    'top':pos.top - jHeader.outerHeight(true),
                    'left':pos.left
                });
                jFooter.css({
                    'left':pos.left
                });
            } else {
                jHeader.css({
                    'top':difHeight
                });        
            }
            jFooter.css({
                'bottom':difHeight
            });
        } else {
            jBody.css('paddingTop',0);
            jHeader.css({
                'top':0
            });
            jFooter.css({
                'bottom':0
            });
            if(ie6){
                pos = jCore.offset() - jHeader.outerHeight(true);
                jHeader.css({
                    'top':pos.top,
                    'left':pos.left
                });
                
                jFooter.css({
                    'left':pos.left
                });
            } else if (ie7) {
                pos = jCore.offset();
                jFooter.css({
                    'left':pos.left
                });
                jHeader.css({
                    'left':pos.left
                });
            } 
        }
        
        box.fire({ type: 'footerPositionReady' });
    };
    
    var setCounter = loe.setCounter = function(){
        function _edNb(n){
            return (n < 10) ? '0'+ n : n;
        }
        var step = box.ui('carousel.slider').current; 
        
        $('.counter').html(step+1+'<span>/'+box.ui('carousel.slider').length+'</span>');
    };
    
    var changeContextual = loe.changeContextual = function (carousel){
        var numSlide = carousel.current,
            slide = $('#carousel .slide:eq('+numSlide+')'),
            navSlide = $('#navSlide a[href=#'+slide.attr('id')+']');
        jContextual.find('.content').fadeOut(300,function(){
                $('#contextual .collec').text(navSlide.text());
                $('#contextual .content .subNav').remove();
                $('#contextual .content').append(navSlide.next().clone());
            }).fadeIn(400);
    };
    
    var checkLogoColor = loe.checkLogoColor  = function(n){
        if(jCarousel.find('li.slide:eq('+n+')').hasClass('lightColor') || $('#visual img.bg').hasClass('lightColor')){
            $('#header-main-nav .content').addClass('lightColor');
        } else {
            $('#header-main-nav .content').removeClass('lightColor');
        }
    };
    var checkAnchor = function(){
        var url = window.location.href;
        if(url.indexOf('#') !== -1){
            var idSlide = url.substring(url.indexOf('#'),url.length);
            var numSlide = $(idSlide).index();
            
            if(numSlide >= 0){
                return numSlide;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    
    /* By Sylvain */
    var setCoreSize = function() {
         
            nWinWidth = jWin.width();
            nWinHeight = jWin.height();
            var Twidth = 'auto',
            nHeaderHeight = jHeader.outerHeight();
            nFooterHeight = jFooter.outerHeight();
            screenWidth = screen.width;
            
            if(SCREEN_WIDTH === 1440 && screenWidth === 1440 ){
                maxCoreHeight = 810;    
            } else {
                maxCoreHeight = Math.ceil(810*screenWidth/1440);
            }
            
        nCoreWidth = nWinWidth > screenWidth ? screenWidth : nWinWidth;
        nCoreWidth = (nCoreWidth>1440)? 1440 : nCoreWidth;            
        nCoreHeight = Math.ceil(maxCoreHeight*nCoreWidth/screenWidth);
        
        if (nWinWidth < 980 || nWinHeight<576) {
            nCoreWidth = 980;
            nCoreHeight = 576;
            Twidth = 980;
        } else if(nCoreHeight+nHeaderHeight+nFooterHeight > nWinHeight) {
              var newH = nWinHeight - nHeaderHeight - nFooterHeight;
              
                nCoreWidth = Twidth = Math.ceil(nCoreWidth / nCoreHeight * newH);
                nCoreHeight = newH;
                
        } else {
            Twidth = nCoreWidth;
        }
        loe.nCoreWidth = nCoreWidth;
        loe.nCoreHeight = nCoreHeight;
        loe.nWinWidth = nWinWidth;
        loe.nWinHeight = nWinHeight;
        
        jFooter.css('width',Twidth);
        jHeader.css('width',Twidth);
        
        jCore.width(Twidth).height(nCoreHeight).css('top', nHeaderHeight);
        jBody.removeClass('overflow-hidden');
        jVisual.css({ top: 0, left: 0 });
        loe.display.resize(nCoreWidth,nCoreHeight,jVisual);
        
        footerHeaderPosition(nWinHeight,nHeaderHeight,nFooterHeight);
    };
    
    //scroll
   
    var activeScroll = loe.activeScroll = {
        resize : function( getScrollHeight ){
            $('.scroll').each(function() {
                var that = $(this),
                heightScroll = getScrollHeight(that);
                that.height(heightScroll);
                var heightBtn = that.find('.prev').height() + that.find('.next').height() + 2; // Hauteur des boutons + 1px de sep par bouton
                that.find('.scrollbar').height(heightScroll);
                that.find('.gutter').height(heightScroll - heightBtn);
                var scroll = box.ui('scroll.'+that.getBoxDatas('id'));
                if(scroll !== undefined){
                    scroll.compute();
                    if(scroll.size.elementDiff < 32){
                        scroll.disable();
                    }
                }
            });
        },
        create : function( getScrollHeight ) {

            $('.scroll').each(function() {
                var that = $(this);
                box.ui('scroll').create({
                    element : that,
                    bar : true,
                    buttons : true
                });
            });
            
           activeScroll.resize(getScrollHeight);
           
        }
    };
   
   var slideShare = loe.slideShare = function(){  
        var share = $('#share'), 
            fshare = $('.fshare'), 
            facebook = $('.facebook'),
            open = false, close = true,
            lg = $('html').attr('lang');
        
        if(ie6){
            share.remove();
        }
            
        if(ie7){
          share.find('.gplusone').remove();
        }
        
       share.animate({
            opacity: 1
       });
       
       
       function getWidth(){
           
           return facebook.outerWidth(true) + $('.gplusone').outerWidth(true) + $('.twitter').outerWidth(true) + $('.mail').outerWidth(true);
           
       }

       if(share.length > 0){            
            share.mouseenter(function(){
                if(close){
                    $(".twitter").width($(".twitter iframe").css('width'));
                    $(".mail").width($(".mail").css('width'));
                    
                    if(!ie7){
                        $(".gplusone").width($(".gplusone > div").css('width'));
                    }
                    close = false;
                    share.find('ul').addClass('open');
                    share.css({
                       width:'auto',
                       right: -getWidth()
                   });
                   $(this).animate({   
                         right: '+='+getWidth()                    
                      }, 800, function(){
                          open = true;
                    });
                    fshare.addClass('hover');
                 }
            });
            
            share.mouseleave(function(){            
                if(open){
                    open = false;
                    $(this).animate({                    
                            right: '-='+getWidth()
                        }, 800, function(){
                          share.find('ul').removeClass('open');
                          share.css({
                            right: 0,
                            width:fshare.outerWidth(true)
                          });
                          close = true;
                     });
                    fshare.removeClass('hover');
                }
            });            
        }
        share.addClass('init');
        share.find('.connect_comment_widget .nub').remove();
     };
    
    var CarouselElastic = loe.CarouselElastic = function(el,coreWidth,coreHeight,itemWidth,idName,datas){ this.initialize(el,coreWidth,coreHeight,itemWidth,idName,datas);};
    CarouselElastic.prototype = {
        initialize : function(el,coreWidth,coreHeight,itemWidth,idName,datas){
            var $this = this;            
            this.id = idName;
            this.el = el;
            this.datas = datas;
            this.itemWidth = itemWidth;
            this.coreHeight = coreHeight;
            this.coreWidth = coreWidth;
            this.wrapper = this.el.children().children();
            this.objCarousel = null;
            this.status = true;
            this.set();
            
            if(typeof this.datas.autoPreload === 'boolean'){
                var autoPreload = $this.datas.autoPreload;
            }
            
            box.bind({
                'carouselnext':function(e){

                    $this.setCounter();
                    if($this.status){
                        var carousel = box.ui('carousel.'+$this.id),
                            carouselLengthNb = carousel.length;
                        //$this.setCounter();
                        checkLogoColor(carousel.current);
                        
                        var nb = carousel.current + 1;
                        if(carousel.display === 1){
                            if(typeof autoPreload === 'boolean' && !autoPreload){
                                carouselLengthNb = carousel.length + 1;
                            }
                            if(nb < carouselLengthNb){
                                if(typeof autoPreload === 'boolean' && !autoPreload){
                                    nb--;
                                }
                                var slide = $this.el.find('.slide:eq('+nb+')');
                                if(slide.find('img').size() !== 1){
                                    $this.preloadCarouselImg(slide,e);
                                }
                            }
                        }
                    }
                },
                'carouselprev':function(e){
                    $this.setCounter();
                    if($this.status){
                        checkLogoColor(box.ui('carousel.'+$this.id).current);
                        var nb = box.ui('carousel.'+$this.id).current - 1;
                        if(typeof autoPreload === 'boolean' && !autoPreload){
                            nb++;
                        }
                        if(nb > 0){
                            var slide = $this.el.find('.slide:eq('+nb+')');
                            if(slide.find('img').size() !== 1){
                                $this.preloadCarouselImg(slide,e);
                            }
                        }
                    }
                },
                'visualready':function(){
                    if($this.status && !$this.objCarousel.moving){
                        $this.preloadImg();
                    }
                }
            });
            
            if(typeof this.datas.outPagination === 'string'){
                $(this.datas.outPagination+' a.next').click(function(e){
                    e.preventDefault();
                    if($this.status){
                        box.ui('carousel.'+$this.id).moveNext();
                    }
                    //box.fire({ type: 'carouselnext' });
                });
                $(this.datas.outPagination+' a.prev').click(function(e){
                    e.preventDefault();
                    if($this.status){
                        box.ui('carousel.'+$this.id).movePrev();
                    }
                    //box.fire({ type: 'carouselprev' });
                });
           }
           
            
        
        },
        set:function(currentSlide){
            this.dimCarousel();
        
            if(this.el.find('li.slide').eq(0).outerWidth() === 0) {
                return;
            }
            
            if(typeof currentSlide !== 'number'){                
                currentSlide = checkAnchor();
            }
            var config = { 
                // previous button 
                btnPrev: '<a href="#" class="{$btnPrevCls} {$btnDisabledCls}"><span>' + l10n.prev + '</span></a>', 
                
                // next button 
                btnNext: '<a href="#" class="{$btnNextCls} {$btnDisabledCls}"><span>' + l10n.next + '</span></a>'
            };
            
            var initial = {
                id: 'slider',
                element: '#carousel',
                horizontal: true,
                display: 1,
                circular:true,
                paginate:false,
                duration: 600,
                buttons: false,
                moveBy: this.coreWidth,
                startAt: currentSlide + 1
            };
            
            var configDatas; 
            if(typeof this.datas === 'object'){
                configDatas = {
                    id: this.id,
                    element: this.el,
                    horizontal: true,
                    display: this.datas.display,
                    circular:this.datas.circular,
                    paginate:this.datas.paginate,
                    duration: this.datas.duration,
                    buttons: this.datas.buttons,
                    moveBy: this.coreWidth,
                    startAt: currentSlide + 1
                };
            } else {
                configDatas = initial;    
            }
            
            box.ui('carousel').destroy('carousel.'+this.id);
            this.objCarousel = null;
            
            box.ui('carousel').configure(config);
            this.objCarousel = box.ui('carousel').create(configDatas);
            box.fire({ type: 'mainCarouselReady' });
            
           
            /*var nDuration = this.objCarousel.duration;
            
            delete this.objCarousel.duration;
            this.objCarousel.moveToItem(currentSlide+1);
            this.objCarousel.duration = nDuration;*/
            
            
            if(this.objCarousel.items.length < 2){ this.status = false; }
                        
            var $this = this;
            $(document).keydown(function(e){
               if($this.status){
                   if(e.keyCode === 37){
                       box.ui('carousel.'+$this.id).movePrev();
                       //box.fire({ type: 'carouselprev' });
                   }
                   if(e.keyCode === 39){
                       box.ui('carousel.'+$this.id).moveNext();
                       //box.fire({ type: 'carouselnext' });
                   }
               } 
            });
            
            if(this.datas.counter) {
                this.setCounter();
            }
            checkLogoColor(0);
            
        },
        resize:function(coreWidth,coreHeight,itemWidth){
            this.coreWidth = coreWidth;
            this.coreHeight = coreHeight;
            this.itemWidth = itemWidth;
            
            if(!this.objCarousel) {
                this.set();
            }
            
            if (this.el.find('.prev').size() === 1){ box.ui('carousel.'+this.id).moveToItem(1); }
            
            if (this.datas.buttons) {this.el.find('.prev, .next').remove();}
            
            if (this.datas.paginate && this.el.find('.pagination').size() === 1) {
                box.ui('carousel.'+this.id).removePagination();
            }
            
            var currentSlide = box.ui('carousel.'+this.id).current;
            
            box.ui('carousel').destroy(this.id);

            if(this.wrapper.css('left')!== 0) {this.wrapper.css('left','0px');}
            
            this.set(currentSlide);
            
        },
        dimCarousel:function(){
            this.el.children().css({
                width: this.coreWidth,
                height: this.coreHeight
            });
            
            this.el.find('li.slide').css({
                width: this.itemWidth,
                height: this.coreHeight
            });
        },
        setCounter:function(){            
            var step = box.ui('carousel.' + this.id).current;
            $(this.datas.outPagination+' .counter').html(step+1+'<span>/'+box.ui('carousel.'+this.id).length+'</span>');
        },
        destroy:function(){
            delete this.status;
            box.ui('carousel').destroy(this.id);
        },
        preloadImg:function(hasAnchor){
            var imgs;
            
            if(typeof hasAnchor !== "boolean"){
                hasAnchor = false;
            }
            
            if(this.objCarousel.current === 0){
                imgs = this.el.find('.slide:eq(1) a.pict, .slide:last a.pict');
            } else {
                imgs = this.el.find('.slide:eq('+this.objCarousel.current+') a.pict, .slide:eq('+(this.objCarousel.current-1)+') a.pict, .slide:eq('+(this.objCarousel.current+1)+') a.pict');
            }
            
            if(!(typeof this.datas.autoPreload === 'boolean' && !this.datas.autoPreload) || hasAnchor){
                imgs.each(function(){
                    $(this).parent().append('<img src="'+$(this).attr('href')+'" alt="" />');
                });
            }
                          
            if(typeof this.datas.outPagination === 'string'){
                $(this.datas.outPagination).show();
            } else {
                $('.pagination').show();
            }
        },
        preloadCarouselImg:function(slide,e){
            var $this = this;
            $this.status = false;
            var next = $('.pagination .next'),
                prev = $('.pagination .prev'),
                button = (e.type ==='carouselnext')? next : prev,
                url = slide.find('a.pict').attr('href'),
                oElm = doc.createElement('img');
                
            /*button.css('visibility','hidden');*/
            
            oElm.onload = function() {
                slide.append('<img src="'+url+'" alt="" />');
                //button.css('visibility','visible');
                $this.status = true;
            };
            oElm.src = url;
        },
        preloadCarouselImgs:function(nb,e){
            //Method for product-list.js
            var $this = this,
                next = $('#carousel .next'),
                prev = $('#carousel .prev'),
                button = next, //button = (e.type ==='carouselnext')? next : prev,
                oElm = doc.createElement('img'),
                imgToLoad = new Array(),
                total = nb + $this.objCarousel.display;

           
            nb = nb + $this.objCarousel.display -1;
            for(var i=0; i<$this.objCarousel.display; i++){
                imgToLoad.push(nb+i);
            }

            function loadimgs(imgToLoad){
                for(var i=0; i<imgToLoad.length; i++){
                    var slide = $this.el.find('.slide:eq('+imgToLoad[i]+')');

                    if(slide.find('img').size() !== 1){              
                        var linkPict = slide.find('a.pict'),
                            linkUrl = slide.find('a.urlp'),
                            url = linkPict.attr('href');
                        
                        linkUrl.append('<img src="'+url+'" alt="'+linkPict.text()+'" />');
                        linkPict.remove();
                        linkUrl.find('span').remove();
                        nb++;
                        if(nb === total){
                            $this.status = true;
                        }
                    }  else {
                        nb++;
                        if(nb === total){
                            $this.status = true;
                        }
                    }                    
                }
            }
            loadimgs(imgToLoad);
        }
    };
    
    
    //new CarouselDiapos(1,2,3)
    //- 1 : $(element)
    //- 2 : width Max of image ( in 1440 width)
    //- 3 : id name for Box carousel Object
    var CarouselDiapos = loe.CarouselDiapos = function(el,imgWidthMax,idName){ this.initialize(el,imgWidthMax,idName);};
    CarouselDiapos.prototype = {
        initialize : function(el,imgWidthMax,idName){
            this.el = el;
            this.imgWidthMax =  imgWidthMax;
            this.id = idName;
            
            this.set();
        },
        set:function(){
            var calcH, calcW;
            if(this.imgWidthMax === 'parent') {                
                calcH = this.el.parent().height()-35;
                if(this.el.prev().size() === 1 && this.el.prev()[0].tagName === 'H2') {calcH = calcH - this.el.prev().height();}
                calcW = this.el.parent().width();
                this.el.find('img').height(calcH);
                this.el.children().css({
                    height:calcH,
                    width:calcW
                });
                this.el.find('li').width(calcW);
            } else {
                calcW = Math.round((this.imgWidthMax * loe.nWinWidth)/1440);
                calcW = (calcW>this.imgWidthMax) ? this.imgWidthMax : calcW;
                this.el.find('img').width(calcW);
                this.el.children().width(calcW);
                var hItem = this.el.find('img:first').height();
                this.el.children().height(hItem);
               }
            
            box.ui('carousel').create({
                id:this.id,
                element:this.el,
                horizontal:true,
                display: 1,
                duration: 600,
                paginate:true,
                buttons: false
            });
            this.el.find('.pagination').css('width',this.el.children(':first').width());
        },
        destroy:function(){
            if(this.el.find('.pagination').size() === 1){
                box.ui('carousel.'+this.id).removePagination();
            }
            box.ui('carousel').destroy(this.id);
            this.el.children().find('ul').animate({'left':0});
        },
        resize:function(){
            this.destroy();
            this.set();
        }
    };
    
    var loader = loe.loader = {
        open: false,
        close:true,
        full:true,
        add: function(t,hide){
            if(loader.close){
                loader.close = false;
                var hContent, id, topPos, leftPos, WH_LOADER = 100 ;
                if(hide) {t.css('opacity', 0);}
                if(t.is('body') && loader.full){
                    hContent = jWin.height();
                    topPos = 0; 
                    leftPos  = 0;
                    id='allbody';
                    box.ui('loader').create({
                        id:id,
                        html:'<div class="loaderBody" style="width:'+nWinWidth+'px;height:'+jWin.height()+'px"><div class="loaderBodyWrapper"><div id="swf'+id+'"></div></div></div>'
                    });
                } else {
                    hContent = (t.is('body'))?jWin.height():t.outerHeight();
                    
                    id = t.attr('id');
                    box.ui('loader').create({
                        id:id,
                        html:'<div class="wrapperloader"><div class="loader"><div id="swf'+id+'"></div></div></div>'
                    });
                }
                    
                box.ui('loader.'+id).element.parent().css({'position:absolute, top':topPos+'px','left':leftPos+'px'});
                box.ui('loader.'+id).show();
                
                var flashvars = {};
                var params = {
                    menu: "false",
                    wmode: "transparent"
                };
                var attributes = {};
                
                swfobject.embedSWF(l10n.loader, "swf"+id, "40", "40", "9.0.0", BASE_SKIN_URL + "swf/expressInstall.swf",flashvars, params, attributes);
            loader.open = true;
            }
        },
        remove: function(t,hide){
            if(loader.open){
                loader.open = false;
                var id = (t.is('body') && loader.full)? 'allbody' : t.attr('id');
                setTimeout(function(){
                    $('.loaderBody,div.loader').css('zoom','1');
                    $('.loaderBody,div.wrapperloader').fadeOut(2000,function(){
                        box.ui('loader.'+ id ).hide();
                        box.ui('loader').destroy(id);
                    });
                    if(hide){
                        t.animate({opacity:1},'slow',function(){
                            if(ie7){
                                this.style.removeAttribute('filter');
                            }
                        });
                    }
                    loader.close = true;
                },1000);
            }
        }
        
    };
    
    loe.onVideoReady = function(){
        if(loe.loader.open){
           loe.loader.remove(); 
        }
    };
    
    loe.setContextualInCenter = setContextualInCenter = function() {
        var contextual = $('#contextual');
        contextual.fadeIn(500,function(){
            if(ie7){
                this.style.removeAttribute('filter');
            }
        });
        if(ie6) {setTimeout(function(){jContextual.css('width',$('#contextualWrapper .content').innerWidth());},50);}
        
        if(contextual.find('.prev').length === 0) {
            contextual.find('.collec').addClass('noprev');
        }
    };
    
    loe.preloadVisual = preloadVisual = function(bg) {
        var maskLoader = $('.pageLoader');
        loader.add(maskLoader,false);
        if(bg === 'undifined'){
            jVisual.append('<img src="' + BASE_SKIN_URL + 'images/product/bg-product.jpg" alt="" class="bg" />');
        }
        var oElm = doc.createElement('img');
        oElm.onload = function() {
            this.onload = null;
            jVisual.fadeIn(500,function(){
                setCoreSize();
                box.fire({ type: 'visualready' });
                maskLoader.fadeOut('slow',function(){
                   loader.remove(maskLoader,false);
                   $(this).remove(); 
                });
                if(ie7){
                    this.style.removeAttribute('filter');
                }
            });            
        };
        oElm.src = bg.attr('src');
        
    };
    
     
    var Bullet = function(el){ this.initialize(el);};
    Bullet.prototype = {
        initialize:function(el){
            var that = this;
            this.el = $(el);
            this.isMoving = false;
            this.timer = null;
            this.el.mouseenter(function(){that.manageMouseEnter()});
            this.el.mouseleave(function(){that.manageMouseLeave()});
        },
        restoreRollovered:function(jElm) {
            var oDatas = jElm.data();
            jElm[0].style.top = '-10000px';
            jCurrentRollover = null;
            this.isMoving = false;
        },
        manageMouseEnter:function() {
            this.el.css('zIndex',4);
            if($(document.body).hasClass('cms-index-index')){
                box.fire({ type: 'bulletsopen' });
            }
            
            if (!this.isMoving) {
                this.isMoving = true;
                var jSpan = this.el.children().children();
                    
                var nWidth = jSpan.width(),
                    nItemLeft = Math.round(this.el.offset().left);
                    if(this.el.find('a').hasClass('showLeft')){
                        var nRight = nItemLeft - nWidth,
                        sProp = nRight < 5 ? 'left' : 'right';
                    } else {
                        var nLeft = nItemLeft + nWidth,
                        sProp = nLeft > nCoreWidth-100 ? 'right' : 'left';
                    }
                    var sClassName = sProp === 'left' ? 'show-from-right' : 'show-from-left',
                        oInit = { top: '0px', left:'-2px'};
                    if (sProp === 'right') {
                        oInit = { top: '0px', right:'-9px'};
                    }
                jSpan.css('width',nWidth);
                jCurrentRollover = jSpan.addClass(sClassName).css(oInit);
            } else {
                if(this.timer) {
                    win.clearTimeout(this.timer);
                }
            }
        },
        manageMouseLeave:function() {
            var that = this;
            if (that.isMoving) {
                var jSpan = that.el.children().children();
                this.timer = win.setTimeout(function() {
                    jSpan.data('hideTimer', null);
                    var sProp = jSpan.data('anim-property');
                    that.restoreRollovered(jSpan);
                    that.el.css('zIndex',3);
                }, 500);
            }
        }
    };    
    
    var bulletsManager = loe.bulletsManager  = {
        isMoving:false,
        init:function(rootElm){
            if(typeof(rootElm) == 'undefined'){
                var bullets = jVisual.find('.bullets li'); 
            }else{
                var bullets = $('#'+rootElm).find('.bullets li'); 
            }
            //bullets.hover(bulletsManager.manageMouseEnter, bulletsManager.manageMouseLeave).children();
            bullets.each(function(){
                new Bullet(this);
            });
            bullets.find('a').click(function(e){
                e.preventDefault();
                var that = $(this);
                if(!that.attr('href')){	
                } 
                else if(that.hasClass('video')){
                    popinManager.open(that);
                } 
                else {
                    window.location = that.attr('href');
                }
            });
        }
     };
    
    loe.correctPNG = function(img,mode) { 
        var src = img.src;
        img.src = l10n.url.transparent;
           img.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod="+mode+");";
    };
    
    
    
    var headerLinks = loe.headerLinks = {
      
        init:function(){ 
            $('#header-shopping-nav .links li:first').addClass('first');
            $('#header-shopping-nav .links li:last').addClass('last');
            $('#header-shopping-nav .wishlist a, #header-shopping-nav .top-link-cart a').mouseover(function(){
                if($(this).text().indexOf('(0)')=== -1){
                    if(!doc.getElementById('popinHeader')){
                        headerLinks.openPopin(this);
                    } else {
                        if($(this).parent().attr('class') !== $('#popinHeader').attr('class')){
                            headerLinks.closePopin();
                            headerLinks.openPopin(this);
                        }
                    }
                }
            });
        },
        closePopin:function(){
            $('#header-shopping-nav a').removeClass('hover');
            $('#popinHeader').remove();
            $('.cartTable .not-available-product').parent().remove();
        },            
        openPopin:function(el){
            if(!document.getElementById('popinHeader')){
                $(document.body).append('<div id="popinHeader" class="'+$(el).parent().attr('class')+'"><span class="arrow"></span><div id="popinHeaderWrapper"></div></div>');
            }
            var headerH = $('#header').offset().top + $('#header').innerHeight();
            $('#popinHeader').css({
                top:headerH + 6,
                left:$(el).offset().left - $('#popinHeader').outerWidth(true) + 30 + $(el).width()/2
            });
            
            var datas;
            
            if($(el).parent().hasClass('top-link-cart')){
                datas = $('#loewe-customer-preview-cart').html();
            }
            
            if($(el).parent().hasClass('wishlist')){
                datas = $('#loewe-customer-preview-wishlist').html();
            }
           
            $('#popinHeaderWrapper').html(datas);
            
            if($('#popinHeader').hasClass('top-link-cart')){
                //$('#popinHeader .bt1 a').click(function(e){
                //e.preventDefault();
                //headerLinks.closePopin();
                //});
            } else {
                $('#popinHeader a.button').click(function(e){
                    e.preventDefault();
                    window.location = $('#header .wishlist a').attr('href');
                });
            }
            
            var timer = setTimeout(function(){
                headerLinks.closePopin();
            },5000);

            $('#popinHeader').mouseover(function(){
                clearTimeout(timer);
            }).mouseleave(function(){
                headerLinks.closePopin();
            });;
            
                
        }
    };
    
    var popinConfirm = {
        init:function(){
            popinConfirm.option = box.ui('form.countryLang').field('select-website').dom.find('option[selected=selected]').index();
            box.ui('form.countryLang').field('select-website').setIndex(popinConfirm.option);
        },
        option:null,
        show:function(msg,e){
        
            var url = e.source.dom.val();
            var html = '<div id="popinConfirm"><p>'+msg+'</p><ul>'+
                '<li><a href="#" class="cancel">'+l10n.alert.button.cancel+'</a></li>'+
                '<li><a href="#" class="valid">'+l10n.alert.button.valid+'</a></li>'+
                '</ul></div>';
            $(document.body).append(html);
            var popin = $('#popinConfirm');
            
                box.ui('mask.modale').show();
            
            var left = Math.round(jWin.width() / 2 - 200),
                top  = Math.round(jWin.height() / 2 - (popin.height()/2));
    
                popin.css('left',left);
                popin.animate({top:top},1000,'linear');
            
            popin.find('ul a').click(function(){
                if($(this).hasClass('cancel')){
                    popinConfirm.hide(popin);
                    box.ui('form.countryLang').field('select-website').setIndex(popinConfirm.option);
                } else {
                    if(url.indexOf('#noec') !== -1){
                        url = url.replace('#noec','');
                    }
                    window.location = url;
                }
            });
       },
       hide:function(el){
           el.animate({top:-jWin.height()},1000,function(){
                el.remove();
                box.ui('mask.modale').hide();
            });
       }
    };
    
    loe.swfVideo = {
        endVideo:function(){
            box.fire({ type: 'endvideo' });
        },
        isReady:function(){
            box.fire({ type: 'videoisready' });
        }
    };
    
    var popinManager = loe.popinManager = {
        open:function(el){
            box.ui('mask.modale').show();
            var html = '<div id="popinLoewe"><a href="#" class="close">'+l10n.popin.close+'</a>'+
            '<div id="popinContent"></div>'+            
            '</div>';
            $(document.body).append(html);
            
            popinManager.addContent(el);
            
            
        },
        addContent:function(el){
            var popin = $('#popinLoewe'),
                flash = true;
            if(typeof el === 'object' && el.hasClass('video')){
                popin.addClass('video');

                box.bind({
                    'videoisready':function(){
                        popinManager.show(popin);
                    },
                    'endvideo':function(){
                        popinManager.close(popin);
                    },
                    'popinVideoOpen':function(){
                        if(flash){
                            var objSwf = swfobject.getObjectById("myDynamicContent");
                            objSwf.launchVideo();
                        } else {
                            $('#popinContent').append(l10n.alert.noflashplayer+'<a target="_blank" href="http://get.adobe.com/flashplayer/"><img src="' + BASE_SKIN_URL + 'images/common/get_flashplayer.gif" alt="" /></a>');
                        }
                    }
                });
                
                var flashvars = {
                    jsEndFunction: "loe.swfVideo.endVideo",
                    jsReadyToPlay: "loe.swfVideo.isReady",
                    videoSrc: el.attr('href')
                };
                
                var params = {
                  menu: "false",
                  allowFullScreen: "true"
                };
                var attributes = {
                  id: "myDynamicContent",
                  name: "myDynamicContent"
                };
                
                swfobject.embedSWF(BASE_SKIN_URL + "swf/popin/videoPlayer.swf", "popinContent", "624", "392", "9.0.0", BASE_SKIN_URL + "swf/expressInstall.swf", flashvars, params, attributes);
                
                var v = swfobject.getFlashPlayerVersion();
                
                if(v.major === 0 && v.minor === 0 && v.release === 0){
                    flash = false;
                    popinManager.show(popin);
                }
            } else if(el === 'ie6'){
                $('#popinContent').load(BASE_URL+'warning-ie6',function(){
                    popinManager.show(popin);    
                });
            }
        },
        show:function(popin){
            var left = Math.round(jWin.width() / 2 - popin.width()/2),
            top  = Math.round(jWin.height() / 2 - (popin.height()/2));
            popin.css('left',left);
            
            popin.animate({top:top},1000,'linear',function(){
                if(popin.hasClass('video')){
                    box.fire({ type: 'popinVideoOpen' });
                }
            });
            popin.find('a.close').click(function(e){
                e.preventDefault();
                popinManager.close(popin);
            });
        },
        close:function(popin){
            popin.animate({top:-jWin.height()},1000,function(){
                popin.remove();
                box.ui('mask.modale').hide();
            });
        }
    };

    var setFooter = function (){
    	/*
        if(doc.getElementById('countryLang')) {
            box.ui('form').create({
                element: '#countryLang'
            }).addReplacement();
          }
          */
        
        if(doc.getElementById('languageSwitcher')) {   
            box.ui('form').create({
                element:'#languageSwitcher'
            }).addReplacement();
        }
		
        if(doc.getElementById('countryLang')) {   
            box.ui('form').create({
                element:'#countryLang'
            }).addReplacement();
        }
        
        if(doc.getElementById('countrySwitcher')) {   
            box.ui('form').create({
                element:'#countrySwitcher'
            }).addReplacement();
        }
        
        /*
        if(doc.getElementById('countryLang')) {
            popinConfirm.init();
        }
        */
            
        box.bind({
        	/*
            'change.field.select.select-website':function(e){
                popinConfirm.show(l10n.alert.countryselect,e);
            },
            */
            'change.field.select.select-language':function(e){
                window.location = e.source.dom.val();
            },
            'change.field.select.select-country':function(e){
               doc.getElementById('countryLang').submit();
            },
            'change.field.select.select-country':function(e){
                doc.getElementById('countrySwitcher').submit();
                
                /* destroy popincookie=true if getvalue() != international;
                 */
                 //if(this.getValue().indexOf('international') !== -1){
                  cookieManage.destroy('popinAvailable','true');   
                 //}
                
                
             }
        });
    }; 
    
    var headerMainNav = loe.headerMainNav = {
        minimizedSize:'220',
        maximizedSize:'445',
        isMoving:false,
        isOpen:false,
        off:false,
        init:function(){
            $('#header-display-main-nav').mouseenter(function(){
                if (!headerMainNav.isMoving && !headerMainNav.isOpen && !headerMainNav.off) {
                    headerMainNav.open();
                }
            });
            
            $('#header-display-main-nav').click(function(e) {
                e.preventDefault();
                if (!headerMainNav.isMoving && !jQuery(this).hasClass('minimized') && !headerMainNav.off) {
                    headerMainNav.close();
                }
            });
                
                
            $('#header-main-nav').mouseleave(function(){     
                if (!headerMainNav.isMoving && !jQuery(this).hasClass('minimized')) {
                    headerMainNav.close();
                }
            });
        },
        open:function(){
            
            headerMainNav.isMoving = true;
            var jNav = $('#header-main-nav'),
                button = $('#header-display-main-nav'); 
            headerMainNav.minimizedSize = jNav.children().outerHeight();
            jNav.removeClass('minimized');
            headerMainNav.maximizedSize = jNav.children().outerHeight(); // necessary for IE7 at least
            jNav.height(headerMainNav.minimizedSize);
            button.hide();
            jNav.animate({
                height: headerMainNav.maximizedSize
            }, 500, function(){
                jNav.height(headerMainNav.maximizedSize);
                headerMainNav.isMoving = false;
                headerMainNav.isOpen = true;
                button.show();
            });         
            
        },
        close:function(){
            headerMainNav.isMoving = true;
            var jNav = jQuery('#header-main-nav');
            jNav.height(headerMainNav.maximizedSize);
            headerMainNav.maximizedSize = jNav.children().outerHeight(); // necessary for IE7 at least
            jNav.animate({
                height: '0'
            }, 500, function(){
                jNav.addClass('minimized');
                jNav.height('auto');
                headerMainNav.isMoving = false;
                headerMainNav.isOpen = false;
            });
        }
    };
    
    var setPopin = function(){
        box.ui('mask').create({
            id: 'modale',
            
            html: '<div id="popinMask"></div>',
            insertStyles: {opacity: 0, width: 'viewport:content-box', height: 'document:content-box'},
            insertAnimStyles: {opacity: 0.5},
            insertAnimDuration: 200,
            removeAnimStyles: {opacity: 0},
            removeAnimDuration: 150,
            resizeStyles: {width: 'viewport:content-box', height: 'document:content-box'}
        });
        
        box.ui('mask').create({
            id: 'transparent',
            
            html: '<div id="popinMask"></div>',
            insertStyles: {opacity: 0, width: 'viewport:content-box', height: 'document:content-box'},
            insertAnimDuration: 200,
            removeAnimDuration: 150,
            resizeStyles: {width: 'viewport:content-box', height: 'document:content-box'}
        });
        
        // create a loader for popins
        box.ui('loader').create({
            id: 'loading',
            
            html: '<div id="popinLoader">' + l10n.loading + '</div>',
            insertStyles: {opacity: 0, top: 'viewport:middle', left: 'viewport:middle'},
            insertAnimStyles: {opacity: 1},
            insertAnimDuration: 200,
            removeAnimStyles: {opacity: 0},
            removeAnimDuration: 150
        });
        
        // create a new popin object
        box.ui('popin').create({
            id: 'loewe',
            loader: 'loading',
            mask: 'modale',
            insertStyles: {top: 'viewport:middle', left: 'viewport:middle'},            
            openClassName: 'popinOpen',
            closeClassName: 'popinClose'
        });
        box.bind({
            'open.popin.loewe':function(e){
                
                var e_scroll = $('div.popin').find('.scroll');
                var hasScroll = ( e_scroll.size() > 0 ) ? true : false;
                
                if(hasScroll){
                   box.ui('scroll').create({
                        element: '.scroll',
                        bar : true,
                        buttons : true
                   });
                   
                   /* @note: force scrollbar and gutter heights */
                   var e_scrollHeight = e_scroll.height();
                   e_scroll.css('height', e_scrollHeight);
                   e_scroll.find('.scrollbar').css('height', e_scrollHeight);
                   var gutterHeight = e_scrollHeight - $('span.prev, span.next').outerHeight(true);
                   e_scroll.find('.gutter').css('height', gutterHeight );
                   
                }
            },
            'close.popin.loewe': function(e) {
                box.ui('scroll').destroy('loewe');
            }
            
        });
    };
    
     
    
    //Section Form functions
    /* define a new pattern to check field validity */
   /*  @note password: Any character but 'space', in a range of 5-20 */
    box.ui('form').addPatterns({
        'password': /^\S{5,20}$/, 
        'zipcode' : /^[a-zA-Z0-9]+$/,
        'phoneNumber' : /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/,
        'email':/^([a-zA-Z0-9]+(([\.\-\_]?[a-zA-Z0-9]+)+)?)\@(([a-zA-Z0-9]+[\.\-\_])+[a-zA-Z]{2,4})$/,
        'name': l10n.validation.name
    });
    
    /* @workaround: Box doesn't handle name attribute with [] 
     * A mettre avant getErrorTarget addFormError etc. */
    
    // get box datas in class attribute
    $.fn.getBoxDatas = function(key) {
        var datas = null;
        if(this.length) {
            var cls = this[0].className, tmp;
            if(cls && cls.indexOf('box[') > -1) {
                if(typeof key === 'string') {
                var re = new RegExp(key + '=([^;\\]]+?(\\[[^;\\]]*\\]?)*)[;\\]]'); /*'=([^;\\]]+)' */
                    tmp = cls.match(re);
                    datas = tmp && decodeURIComponent(tmp[1]);
                } else {
                    datas = {};
                    var box = cls.replace(/.*box\[([^)]+)\].*/, '$1');
                    var boxParts = box.split(';');
                    var i = boxParts.length, l = i - 1;
                    while(i--) {
                        tmp = boxParts[i].split('=');
                        datas[tmp[0]] = decodeURIComponent(tmp[1]);
                    }
                }
            }
        }
        return datas;
    };
    // set box datas in class attribute
    $.fn.setBoxDatas = function(datas) {
        if(typeof datas === 'object' && this.length) {
            this.each(function(i, elm) {
                var cls = elm.className, tmp, first = false;
                if(!cls || cls.indexOf('box[') === -1) {
                    $(elm).addClass('box[]');
                    first = true;
                }
                cls = elm.className;
                for(var i in datas) {
                    tmp = i + '=' + encodeURIComponent(datas[i]);
                    // @todo should check for duplicates in keys and override if necessary
                    if(datas.hasOwnProperty(i) && cls.indexOf(tmp) === -1) {
                        cls = cls.replace(']', (first ? '' : ';') + tmp + ']');
                    }
                }
                elm.className = cls;
            });
        }
        return this;
    };
    
    /* class used on dispayed errors */
    var errorCls = loe.errorCls = 'error';
    
    /* helpers to manage error display on form validation */
    var addFormError = loe.addFormError = function(e) {
        box.dom('#' + e.source.id + 'Error').html('<p>' + e.source.msg + '</p>');
    };
    
    /* @return Element where error have to be displayed */
    var getErrorTarget = loe.getErrorTarget = function(field) {
        var errorTarget;
        
        if (field.type === 'radio') {
            errorTarget = field.dom.eq(0).closest('.radios');
        } else if (field.type === 'checkbox') {
            errorTarget = field.dom.eq(0).next('label');
        } else {
            errorTarget = field.dom.parent();
        }
        return errorTarget;
    };
    
    /* Add an error message on a field */
    var addFieldError = loe.addFieldError = function(e) {
        var error = box.dom('#' + e.source.name + 'Error');
        if (error.length) {
           // error.html(e.msg);
        } else {
            /*getErrorTarget(e.source).append('<em id="' + e.source.name + 'Error" class="' + errorCls + '">' + e.msg + '</em>');*/
           if(e.source.type === 'select'){
                   var fakeEl = e.source.dom.parent().find('.fauxSelect');
                   fakeEl.parent().attr('id',e.source.name+'Error').addClass(errorCls);
                   fakeEl.find('span').text(e.msg);
           } else if(e.source.type === 'text'){
                if(e.source.dom.attr('type') === 'password'){
                   e.source.dom.val('');
                   //e.source.dom.focus(function(){e.source.dom.val('');});
                   e.source.dom.parent().attr('id',e.source.name+'Error').addClass(errorCls);
                   e.source.dom.after('<span class="msg" style="width:'+e.source.dom.width()+'px;top:'+e.source.dom.position().top+'px">'+e.msg+'</span>');
                   e.source.dom.parent().find('.msg').click(function(){
                       $(this).prev().focus();
                       $(this).remove();
                   });
                } else {
                   e.source.dom.parent().attr('id',e.source.name+'Error').addClass(errorCls);
                   e.source.dom.val(e.msg);
                }
           } else if(e.source.type === 'radio'){
               e.source.dom.parent().attr('id',e.source.name+'Error').addClass(errorCls);
               e.source.dom.parent().append('<p class="messages">' + e.msg + "</p>");
           }else if(e.source.type === 'checkbox'){
               e.source.dom.parent().attr('id',e.source.name+'Error').addClass(errorCls);
               e.source.dom.parent().append('<p class="messages">' + e.msg + "</p>");
           }
        }
    };
    
    /* Remove an error message on a field */
    var removeFieldError = loe.removeFieldError = function(e) {
        var field = box.dom('#' + e.source.name + 'Error');
          
        if(field.hasClass('text') || field.hasClass('select') || field.hasClass('textarea')){
            field.removeClass(loe.errorCls).removeAttr('id');
            if(e.source.dom.attr('type') === 'password'){
                e.source.dom.next().remove();
            }
            else if(e.source.dom.attr('type') === 'checkbox'){
                e.source.dom.remove('.messages');
            }
        }
        else if(box.dom(e.source.name).hasClass('radios')){
            box.dom(e.source.name).remove('.messages');
        }else{
            $(field).find('.messages').remove();
            field.removeClass(loe.errorCls).removeAttr('id');
        }
        //box.dom('#' + e.source.name + 'Error').remove();
    };
    
    var cookieManage = {
        get:function(name){
            var cookieValue = "";
            var search = name + "=";
            if(document.cookie.length > 0) { 
                var offset = document.cookie.indexOf(search);
                if (offset !== -1) { 
                    offset += search.length;
                    var end = document.cookie.indexOf(";", offset);
                    if (end === -1) {end = document.cookie.length;}
                    cookieValue = unescape(document.cookie.substring(offset, end));
                }
            }
            return cookieValue;
        },
        set:function(name, value, days){
            var expire = "";
            if(days !== null) {
                expire = new Date((new Date()).getTime() + days * 86400000);
                expire = "; expires=" + expire.toGMTString();
            }
            document.cookie = name + "=" + escape(value) + expire;
        },
        test:function(name){
            var test = false;
            var search = name + "=";
            if(document.cookie.length > 0) { 
                var offset = document.cookie.indexOf(search);
                if (offset !== -1) {
                    test = true;
                }
            }
            return test;
        },
        destroy:function(name,value){
             if(cookieManage.test(name)){
                 var expire = new Date();
                 expire = "; expires=" + expire.toGMTString();
                 document.cookie = name + "=" + escape(value) + expire;
             }
        }
    };
    
    var noie6test = function(){
        if(!cookieManage.test('loeweie6')){       
            loe.popinManager.open('ie6');
            cookieManage.set('loeweie6',1,60);
        }
    };
    
    jDoc.ready(function() {
        if(SCREEN_WIDTH === '' || SCREEN_WIDTH < screen.width){
            $.post(BASE_URL+"customer/session/index",{ screenWidth:screen.width });
        }
    
        jBody = $(doc.body);
        jHeader = $('#header');
        jFooter = $('#footer');
        jCore = $('#core');
        jVisual = $('#visual');
        jCarousel = $('#carousel');
        jContextual = $('#contextual');
        
        nWinWidth = loe.nWinWidth = jWin.width();
        
        checkLogoColor();
        setPopin();
        setFooter();
        loe.display.ready(jVisual);
        headerMainNav.init();
        headerLinks.init();
        
        if($('#contextual .openCollection').length){
             box.loadScript('', '/js/nurun/tpl/popincarousel.js');
        }
        
        if(ie6){
            noie6test();
        }
        

        
        
        
        
    });
    jWin.resize(function() {
        win.clearTimeout(resizeTimer);
        jBody.addClass('overflow-hidden');
        resizeTimer = win.setTimeout(setCoreSize, 100);
    });

     box.bind({
         'visualready':function(){
            //waiting until facebook DOM is ready
             if(!$('#share').hasClass('init')) {loe.slideShare();}

            //popin international 
            if($('body').hasClass('international') && !cookieManage.test('popinAvailable')){
                // create a new popin object
                box.ui('popin').create({
                    id: 'available',
                    loader: 'loading',
                    mask: 'modale',
                    insertStyles: {top: 'viewport:middle', left: 'viewport:middle'},            
                    openClassName: 'popinOpen',
                    closeClassName: 'popinClose'
                });            
                box.ui('popin.available').open({
                    id: 'available',
                    url: '/international/online-boutique-availability'
                });            
                cookieManage.set('popinAvailable','true',1);            
            }
        
          }
     });
    
}(jQuery));
