var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
var ie7 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 7.0") != -1);

Event.observe(document, 'dom:loaded', function() {
    initHeaderMiniBox();
    initFilterMenu();

    initMainNavigation();


   initLookHover();
    
   initWhatNewList();

});

//jQuery(document).ready(function(){
//    CareIconsTips('.care-icons ul li');
//    partagerOpener();
//})

Element.addMethods({
                     customonmouseenter: function(element,observer) {
                       element = $(element);
                       element.observe('mouseover',
                                       function(evt,currentTarget) {
                                         var relatedTarget = $(evt.relatedTarget || evt.fromElement);
                                         if( relatedTarget!= currentTarget && relatedTarget.childOf(currentTarget)==false )
                                             observer(element);
                                       }.bindAsEventListener({},element));
                       return element;
                     },
                     customonmouseleave: function(element,observer) {
                       element = $(element);
                       element.observe('mouseout',
                                       function(evt,currentTarget) {
                                         var relatedTarget = $(evt.relatedTarget || evt.toElement);
                                         if(relatedTarget!=currentTarget && relatedTarget.childOf(currentTarget)==false )observer(element);
                                       }.bindAsEventListener({},element));
                       return element;
                     }
                   });
/*---------------------------------------------------------------------------*/

function initMainNavigation() {
   $$('#nav li ul').invoke('hide');
   window.menuEffect = new Array();
   var li = $$('#nav li');  
    if(ie6 || ie7) {
        if($('nav') && !$('nav').hasClassName('cms-nav')) {
            var liChildren = $$('#nav > li');  
            var lisWidth = 0;
            for (i=0; i<liChildren.length; i++) {
                lisWidth += liChildren[i].getWidth();
            }
            var ulDiff = $('nav').getWidth() - lisWidth;
            var ulDiffQuot = Math.floor(ulDiff/liChildren.length);
            var ulDiffMod = ulDiff % liChildren.length;     
    
            liChildren.each(function(liItem) {
                liItem.setStyle({width: (liItem.getWidth() + ulDiffQuot) + 'px'});
            });
            liChildren[0].setStyle({width: (liChildren[0].getWidth() + ulDiffMod) + 'px'});
    }
    }
    
    li.each(function(item) {
        Event.observe(item, 'mouseover', function() {
            item.addClassName('over');
            
            if(item.down('ul')) {
              if(window.menuEffect[item.identify()]) window.menuEffect[item.identify()].cancel();
              window.menuEffect = new Effect.Appear(item.down('ul'), { 
                 from:item.down('ul').getOpacity(), to:1, duration: .3,
					       afterFinish: function() {window.menuEffect[item.identify()] = null;}
					    });
					    
					   }
              //item.down('ul').appear({duration: 0.3});
            //console.log(item.down('ul'));
        });
        Event.observe(item, 'mouseout', function() {
            item.removeClassName('over');
             if(item.down('ul')) {
              if(window.menuEffect[item.identify()]) {
                 window.menuEffect[item.identify()].cancel();
              }
               
              window.menuEffect[item.identify()] = new Effect.Fade(item.down('ul'), { 
                 from:item.down('ul').getOpacity(), to:0, duration: .2,
					       afterFinish: function() {window.menuEffect[item.identify()] = null;}
					    });
					 }
        });

  });
}

/*---------------------------------------------------------------------------*/

function initHeaderMiniBox() {
  
  $$('.header-services a').each(function(link){
     Event.observe(link,'click', function(event) { 
      
      Event.stop(event);
      
      if(link.hasClassName('active')) {
        link.removeClassName('active');
        $$(link.readAttribute('href')).first().fade({duration: 0.3});
      
      }
      else {
        $$('.mini-box').each(function(i){if(i.visible()) i.fade( {duration: 0.3} );});
        $$('.header-services a').each(function(i){i.removeClassName('active');});
      
        link.addClassName('active');
        $$(link.readAttribute('href')).first().appear({duration: 0.3});
      }
     
     });
  });
}
/*---------------------------------------------------------------------------*/
function initLookHover() {

    window.lookEffect = new Array();
    $$('.grid-row-look li.item').each(function(item) {
        //alert($(item).onMouseEnter);
        if(item.down('.product-image h2')) {

             $(item).customonmouseenter( function() {
                 if(window.lookEffect[item.identify()]) window.lookEffect[item.identify()].cancel();
              window.lookEffect = new Effect.Appear(item.down('.product-image h2'), { 
                 from:item.down('.product-image h2').getOpacity(), to:1, duration: .3,
					       afterFinish: function() {window.lookEffect[item.identify()] = null;}
					       
					       });
                //item.down('.product-image h2').appear({duration: 0.3});

             });

             $(item).customonmouseleave( function() {
                if(window.lookEffect[item.identify()]) {
                   window.lookEffect[item.identify()].cancel();
                }
               
                window.lookEffect[item.identify()] = new Effect.Fade(item.down('.product-image h2'), { 
                  from:item.down('.product-image h2').getOpacity(), to:0, duration: .3,
					         afterFinish: function() {window.lookEffect[item.identify()] = null;}
					     });
                
                
                //item.down('.product-image h2').fade({duration: 0.3});
             });

        }
       
    });

}
/*---------------------------------------------------------------------------*/

function initWhatNewList() {
  $$('.whatnew-row .item').each(function(item){
    	Event.observe(item, "mouseover", function(){
    	 this.down('.product-desc').show();
    	});
    	
    	Event.observe(item, "mouseout", function(){
    	 this.down('.product-desc').hide();
    	});	
  });
}

/*---------------------------------------------------------------------------*/
function initFilterMenu() {
  
  $$('#narrow-by-list dt').each(function(l){
     Event.observe(l,'click', function(e) { 
      l = $(l);
      //YAHOO.log("My log message");
      //console.log(link.adjacent('dd'));
      Event.stop(e);
      
      if(this.up().hasClassName('active')) {
        this.up().removeClassName('active');
        this.adjacent('dd').first().fade({duration: 0.3});
        
      }
      else {
        $$('#narrow-by-list dd').each(function(dds){
          if($(dds).visible()) 
            $(dds).fade( {duration: 0.3} );
        });
        
        $$('#narrow-by-list dt').each(function(dts){
          $(dts).up().removeClassName('active');
        });
      
        this.up().addClassName('active');
        this.adjacent('dd').first().appear({duration: 0.3});
      }
     
     });
  });
}

/*---------------------------------------------------------------------------*/

function initSubmitButtonsToLinks() {
 $$('.submitReplace').each(function(btn){
  
  var link = Builder.node('a', {
  'href': 'javascript:void(0)',
  'class': 'linkbtnreplace'
  },  span = Builder.node('span', { }, span = Builder.node('span', { }, btn.readAttribute('title'))));

  link.observe('click',function(e){ 
      fireEvent(Event.element(e).up('form'),'submit');
   });
  
  btn.insert({'after': link});
  
  btn.setStyle({'display':'none'});
  
 });
}

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}


/*---------------------------------------------------------------------------*/

function prodAdditionalInfo() {

    var ar = $$('#product-additional-info ul.links li');
    var cnt = $$('#product-additional-info ul.contents li.cnt');

    var text = Array();
    var swap = "<a href=\"javascript:void(0)\">X Masquer</a>";
    $$('#product-additional-info ul.links').each(function(list){
           Event.observe(list,'click', function(event) {
                  for(i=0;i<ar.length;i++) {
                     if(ar[i] == event.findElement('li')) {
                          if(ar[i].hasClassName('open')) {
                             ar[i].removeClassName('open').update(text[i]);
                             cnt[i].hide();
                          } else {
                             text[i] = ar[i].innerHTML;
                             ar[i].addClassName('open').update(swap);
                             cnt[i].show();
                          }
                      } else {
                         ar[i].removeClassName('open');
                         if(text[i])
                            ar[i].update(text[i]);
                         cnt[i].hide();
                      }
                  }
           });
    });
    
    return false; 
}

/* Opener for Parure more-info */
function parureInfo() {
    $$('.parure-wrapper a.toggle').each(function(item){
        Event.observe(item,'click', function(event) {
            var wrap = this.up(2);
            if(wrap.hasClassName('open')) {
                wrap.removeClassName('open');
            } else {
                wrap.addClassName('open');
            }
        });
    })
}

function LayeredNavi() {

    if($('layered-nav')) {

       //initially hide all drilldowns
       var drills = $$('#layered-nav .drilldown').each(function(e){
            e.setStyle({right:0}).hide();
       })

       // hide opened drilldown when mouse click anywhere in document (except the layered-nav container)
       document.observe('click', function(event) {
            var element = Event.findElement(event, 'table.row');
            if(!element) {
                drills.each(function(ed){
                    ed.hide().up('td').removeClassName('isopen');
                })
            }
       });
       
      
       $$('#layered-nav td').each(function(list){
           // show & hide - particullary drill downs
           Event.observe(list,'click', function(event) {

                  if(!Event.element(event).up('td')) {
                      var clickedLi = Event.element(event);
                  } else {
                      var clickedLi = Event.element(event).up('td');
                  }

                  var clickedHref = event.findElement('a');
                  var drillList = clickedLi.down('.drilldown');

                  if (clickedLi || clickedHref ) {

                      // hide all other drill downs
                      drills.each(function(itemDrill){
                          if(itemDrill.up('td') !== clickedLi) {
                              itemDrill.hide().up('td').removeClassName('isopen');
                          }
                      });
                        
                        if(clickedLi.hasClassName('isopen')) {
                            if(clickedHref) {
                                new Effect.SlideUp(drillList, {duration: 0.3,
                                    afterFinish: function(effect) {clickedLi.removeClassName('isopen');}
                                });
                            } else {
                                new Effect.SlideUp(drillList, {duration: 0.3,
                                    afterFinish: function(effect) {clickedLi.removeClassName('isopen');},
                                    queue: {position: 'end', scope: 'menuxscope'}
                                });
                            }
                        } else {
                            new Effect.SlideDown(drillList, {duration: 0.3,
                                beforeStart: function(effect) {
                                    clickedLi.addClassName('isopen');
                                },
                                queue: {position: 'end', scope: 'menuxscope'}
                            });
                        }
                    }
                });
        });
    }
    
}


//adding class="over" on main navigation items mouseenter
function toggleNavIE() {
    $$('#nav li.main-option').each(function(item) {
        item.onmouseenter = function() {$(this).addClassName('over');}
        item.onmouseleave = function() {$(this).removeClassName('over');}
    })
}

//setting equal height for elements of the list:
function equalizeHeight(pLists) {
    if(pLists) {
        pLists.each(function(pList) {
            var pItems = pList.childElements();
            var pHeight = 0;
            for(i=0; i <pItems.length; i++) {
                if(pItems[i].getHeight() > pHeight)
                    pHeight = pItems[i].getHeight();
            } 

            pItems.invoke('setStyle', {height: pHeight + 'px'});
        });
    }
}

function prodImageRollOver() {

    var links = $$('.grid-row .product-image');    
    links.each(function(item) {
        Event.observe(item, 'mouseover', function() {

            item.addClassName('switch');
        });
        Event.observe(item, 'mouseout', function() {
            item.removeClassName('switch');
        });
    });
}

//left sidebar opener
//function sideBarOpener() {
function toggleOpener(openers) {
    var links = $$(openers);
    
    links.each(function(item) {
        Event.observe(item, 'click', function() {
            item.up('li').toggleClassName('open')
        });
    });
}

function addHover() {
    var elemTags = $$('.button');
    var hn = 'hover';
    elemTags.each(function(e){
        Event.observe(e,'mouseover',function(){
            this.addClassName(hn);
        });
        Event.observe(e,'mouseout',function(){
            this.removeClassName(hn);
        });
    })
}

/*---------------------------------------------------------------------------*/
function imgHover() {

    var buttons = $$('img.btn-hover');

    for(var i=0, images=[]; i<buttons.length; i++) {
        var newSrc = buttons[i].src.replace('.png', '-on.png');
        var j;
        var check = false;
        for(j=0; j<images.length; j++) {
            if(images[j].src == newSrc) {
                check = true;
                break;
            }
        }
        if(!check) {
            images.push(new Image());
            images.last().src = newSrc;
        }
    }

    for(var i=0; i<images.length; i++) {
        images[i].onload = function() {
            for(j=0; j<buttons.length; j++) {
                origSrc = this.src.replace('-on', '');
                if(buttons[j].src == origSrc) {
                    if(buttons[j].parentNode.nodeName == 'BUTTON') {
                        Element.extend(buttons[j].parentNode);
                        buttons[j].parentNode.observe('mouseover', function(){
                            childImg = this.down('img');
                            childImg.src = childImg.src.replace('.png', '-on.png');
                        });
                        buttons[j].parentNode.observe('mouseout', function(){
                            childImg = this.down('img');
                            childImg.src = childImg.src.replace('-on', '');
                        });
                    }
                    else if(buttons[j].hasClassName('nav-img')) {
                        buttons[j].up('li').observe('mouseover', function(){
                            childImg = this.down('img');
                            childImg.src = childImg.src.replace('.png', '-on.png');
                            toggleMenu(this,1);
                        });
                        buttons[j].up('li').observe('mouseout', function(){
                            childImg = this.down('img');
                            childImg.src = childImg.src.replace('-on', '');
                            toggleMenu(this,0);
                        });
                    }
                    else {
                        buttons[j].observe('mouseover', function(){
                            this.src = this.src.replace('.png', '-on.png');
                        });
                        buttons[j].observe('mouseout', function(){
                            this.src = this.src.replace('-on', '');
                        });
                    }
                }
            }
        }
        if(navigator.appName == "Microsoft Internet Explorer")
            images[i].src = images[i].src;
    }
}

// animated Carrousels 
function animateCarrousel(objects, isShowActive) {
    var carrousels = objects;
    isShowActive = isShowActive || false;

    for (i=0; i<carrousels.length; i++) {
        var carrousel = carrousels[i];
        var carrousel_ul = carrousel.down('ul');
        var carrousel_ul_size = carrousel_ul.childElements().length; 
        var carrousel_li_width = carrousel.down('li', 0).getWidth();
        var carrousel_ul_width = carrousel_li_width*carrousel_ul_size;
        var left_btn = carrousel.down('span.left-views');
        var right_btn = carrousel.down('span.right-views');
        var carrousel_area_width = carrousel.down('.view-area').getWidth();

        carrousel_ul.setStyle({width: carrousel_ul_width + 'px'});
        
        if(isShowActive) {
            if(carrousel_ul_width > carrousel_area_width) {
                var centerOffset = carrousel_li_width * Math.floor(carrousel_area_width/(2*carrousel_li_width));
                var currentOffset = carrousel.down('li.item-active').positionedOffset()[0];
                var offsetDiff = centerOffset - currentOffset;
                if(offsetDiff < 0)
                    if(offsetDiff >= carrousel_area_width - carrousel_ul_width)
                        carrousel_ul.setStyle({left: offsetDiff + 'px'});
                    else
                        carrousel_ul.setStyle({left: (carrousel_area_width - carrousel_ul_width) + 'px'});
            }
        }

        updateNav(carrousel_ul, left_btn, right_btn, carrousel_ul_width, carrousel_area_width);


        if(left_btn) {
            Event.observe(left_btn, 'click', function() {
                if(this.hasClassName('left-active')) {
                    carrousel_ul = this.next('.view-area').down('ul');
                    carrousel_li_width = carrousel_ul.down('li', 0).getWidth();
                    left_btn = this;
                    right_btn = this.next('.right-views');
                    carrousel_ul_size = carrousel_ul.childElements().length;
                    carrousel_ul_width = carrousel_li_width*carrousel_ul_size;
                    carrousel_area_width = this.next('.view-area').getWidth();


                    new Effect.Move(carrousel_ul, {
                        x: carrousel_li_width,
                        y: 0,
                        mode: 'relative',
                        duration: 0.4,
                        queue: {
                            scope: 'carousel_scope',
                            limit: 1
                        },
                        afterFinish: function() {updateNav(carrousel_ul, left_btn, right_btn, carrousel_ul_width, carrousel_area_width);}
                    });
                }
            });
        }

        if(right_btn) {
            Event.observe(right_btn, 'click', function() {
                if(this.hasClassName('right-active')) {
                    carrousel_ul = this.previous('.view-area').down('ul');
                    carrousel_li_width = carrousel_ul.down('li', 0).getWidth();
                    left_btn = this.previous('.left-views');
                    right_btn = this;
                    carrousel_ul_size = carrousel_ul.childElements().length;
                    carrousel_ul_width = carrousel_li_width*carrousel_ul_size;
                    carrousel_area_width = this.previous('.view-area').getWidth();


                    new Effect.Move(carrousel_ul, {
                        x: - carrousel_li_width,
                        y: 0,
                        mode: 'relative',
                        duration: 0.4,
                        queue: {
                            scope: 'carousel_scope',
                            limit: 1
                        },
                        afterFinish: function() {updateNav(carrousel_ul, left_btn, right_btn, carrousel_ul_width, carrousel_area_width);}
                    });
                }
            });
        }

    }
}

function updateNav(carrousel_ul, left_btn, right_btn, carrousel_ul_width, carrousel_area_width) {
        if(left_btn) {
            if(carrousel_ul.positionedOffset()[0] >= 0){
                left_btn.removeClassName('left-active');}
            else
                left_btn.addClassName('left-active');
        }

        if(right_btn) {
            if(carrousel_ul.positionedOffset()[0] + carrousel_ul_width <= carrousel_area_width)
                right_btn.removeClassName('right-active');
            else
                right_btn.addClassName('right-active');
        }
}



function animateCarrouselVertical(objects, itemsInRow) {

    var carrousels = objects;

    for (i=0; i<carrousels.length; i++) {
        var carrousel = carrousels[i];
        var carrousel_ul = carrousel.down('ul');
        var carrousel_ul_size = Math.ceil(carrousel_ul.childElements().length/itemsInRow);
        var carrousel_li_height = carrousel.down('li', 0).getHeight();
        var carrousel_ul_height = carrousel_li_height*carrousel_ul_size;
        var up_btn = carrousel.down('span.left-views');
        var down_btn = carrousel.down('span.right-views');
        var carrousel_area_height = carrousel.down('.view-area').getHeight();

        carrousel_ul.setStyle({height: carrousel_ul_height + 'px'});

        updateNav_vert(carrousel_ul, up_btn, down_btn, carrousel_ul_height, carrousel_area_height);

        if(up_btn) {
            Event.observe(up_btn, 'click', function() {
                if(this.hasClassName('active')) {
                    carrousel_ul = this.next('.view-area').down('ul');
                    carrousel_li_height = carrousel_ul.down('li', 0).getHeight();
                    up_btn = this;
                    down_btn = this.next('.right-views');
                    carrousel_ul_size = Math.ceil(carrousel_ul.childElements().length/itemsInRow);
                    carrousel_ul_height = carrousel_li_height*carrousel_ul_size;
                    carrousel_area_height = this.next('.view-area').getHeight();


                    new Effect.Move(carrousel_ul, {
                        x: 0,
                        y: carrousel_li_height,
                        mode: 'relative',
                        duration: 0.4,
                        queue: {
                            scope: 'carousel_scope',
                            limit: 1
                        },
                        afterFinish: function() {updateNav_vert(carrousel_ul, up_btn, down_btn, carrousel_ul_height, carrousel_area_height);}
                    });
                }
            });
        }

        if(down_btn) {
            Event.observe(down_btn, 'click', function() {
                if(this.hasClassName('active')) {
                    carrousel_ul = this.previous('.view-area').down('ul');
                    carrousel_li_height = carrousel_ul.down('li', 0).getHeight();
                    up_btn = this.previous('.left-views');
                    down_btn = this;
                    carrousel_ul_size = Math.ceil(carrousel_ul.childElements().length/itemsInRow);
                    carrousel_ul_height = carrousel_li_height*carrousel_ul_size;
                    carrousel_area_height = this.previous('.view-area').getHeight();


                    new Effect.Move(carrousel_ul, {
                        x: 0,
                        y: - carrousel_li_height,
                        mode: 'relative',
                        duration: 0.4,
                        queue: {
                            scope: 'carousel_scope',
                            limit: 1
                        },
                        afterFinish: function() {updateNav_vert(carrousel_ul, up_btn, down_btn, carrousel_ul_height, carrousel_area_height);}
                    });
                }
            });
        }

    }
}

function updateNav_vert(carrousel_ul, up_btn, down_btn, carrousel_ul_height, carrousel_area_height) {
    
        if(up_btn) {
            if(carrousel_ul.positionedOffset()[1] >= 0){
                up_btn.removeClassName('active');}
            else
                up_btn.addClassName('active');
        }

        if(down_btn) {
            if(carrousel_ul.positionedOffset()[1] + carrousel_ul_height <= carrousel_area_height)
                down_btn.removeClassName('active');
            else
                down_btn.addClassName('active');
        }
}

function pngFix() {
    if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6)) {
        var toFix = $$('.pngfix');
        for (var i=0;i<toFix.length; i++) {
            var bgImg = toFix[i].getStyle('backgroundImage');
    			if(bgImg.indexOf(".png")!=-1){
    			    var iebg;
    			    if(bgImg.indexOf('url("')!=-1)
    				    iebg = bgImg.split('url("')[1].split('")')[0];
    				else
    				    iebg = bgImg.split('url(')[1].split(')')[0];

    				toFix[i].setStyle({backgroundImage: 'none'});
    				toFix[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
    			}
        }
    }
}



/* ---------jQuery Script ---------- */

// partager opener
// with hack to hide html select list
function partagerOpener() {

        jQuery('#addthisbutton').toggle(function(){
            jQuery(this).next().show();
            if(ie55 || ie6) jQuery('select[name=qty]').css('visibility','hidden');
        },function(){
            jQuery(this).next().hide();
            if(ie55 || ie6) jQuery('select[name=qty]').css('visibility','visible');
        });
}

function CareIconsTips(target) {


    var showTT = function() {
                
                jQuery(this).addClass('over');
                var curTip = jQuery(this).children().attr('data-tip');
                var tipCloud = "<div class='care-tip-cloud'><p>";
                tipCloud += curTip;
                tipCloud += "</p></div>";
                jQuery(tipCloud).insertAfter(jQuery(this).children('span'));
    }
    var hideTT = function() {
                jQuery(this).removeClass('over');
                jQuery('.care-tip-cloud').remove();
    }
    jQuery(target).hover(showTT,hideTT);
}

//function hideUniqueOptions(){
//    if (typeof(spConfig) == 'undefined') return false;
//    hideUniqueOptionsFrom(spConfig,0);
//}

function hideUniqueOptionsFrom(obj,silhId) {
    obj.settings.each(function(elem) {
        if(elem.childElements().length==2){
            elem.selectedIndex = 1;
            if ($('product-options-wrapper')) { //configurable
                $('product-options-wrapper').hide();
            } else { //silhouette
                jQuery('#'+silhId).hide();
            }
        }
    });
    obj.reloadPrice();
}

