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() {
    toggleNavIE();
    //equalizeHeight($$('.drilldown-main'));
    toggleOpener('.main-category-list .block-title');
    animateCarrousel();
    LayeredNavi();
    prodImageRollOver();
    prodAdditionalInfo();
    pngFix();
    imgHover();
    //toggleOpener('.parure-wrapper .toggle');
    addHover();
    quickFAQ();
    FAQ();
});

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


function prodAdditionalInfo() {

    if ($('hide-info-text')){
        var ar = $$('#product-additional-info ul.links li');
        var cnt = $$('#product-additional-info ul.contents li.cnt');
        var sliderButtonWrapper = $$('#product-additional-info .slider-button-wrapper')[0];
        var sliderButton = sliderButtonWrapper.down('.lire');
        var close_text_translation = $('hide-info-text').innerHTML;
        var open_text_translation = sliderButton.innerHTML;
        var tabWrapper = $$('#product-additional-info .contents-wrapper')[0];
        var tabWrapperHeight = tabWrapper.getHeight();
        //var text = Array();
        //var text_translation = $('hide-info-text').innerHTML;
        //var swap = "<a href=\"javascript:void(0)\">"+text_translation+"</a>";
        $$('#product-additional-info ul.links li').each(function(list){
               Event.observe(list,'click', function(event) {
                      for(i=0;i<ar.length;i++) {
                         if(ar[i] == event.findElement('li')) {
                        	 ar[i].addClassName('open');
                          	cnt[i].show();
                          	cnt[i].addClassName('active');
                          } else {
                             if(ar[i].hasClassName('open')){
                        	  ar[i].removeClassName('open');
                        	  cnt[i].hide();
                        	  cnt[i].removeClassName('active');
                             }
                          }
                      }
                      contract();
               });
        });
        function expand(liHeight){
        	tabWrapper.morph({height: liHeight+'px'});
    		tabWrapper.addClassName('expanded');
    		sliderButton.update(close_text_translation);
    		sliderButtonWrapper.addClassName('close');
        }
        
        function contract(){
        	tabWrapper.morph({height: tabWrapperHeight+'px'});
            tabWrapper.removeClassName('expanded');
            sliderButton.update(open_text_translation);
            sliderButtonWrapper.removeClassName('close');
        }
        
        sliderButton.observe('click',function(){
        	var visibleTab = tabWrapper.down('li.active');
        	var liHeight = visibleTab.getHeight();
        	
        	if(tabWrapper.hasClassName('expanded')){
        		contract();
        	} else {
	        	if(tabWrapper.getHeight()<=liHeight){
	        		expand(liHeight);
	        	}
        	}
        });
    }
    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({left: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.ne').each(function(list){


           if(list.select('.drilldown').length == 1) {

               // 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;
            if(pList.nodeName != 'TR')
                pItems = pList.childElements();
            else
                pItems = pList.select('.cell');

            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');
        });
    });

    var products_grid_links = $$('.products-grid .product-image');
    products_grid_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('-on', '').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('-on', '').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('-on', '').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('-on', '').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() {

    var carrousels = $$('.recently-viewed-carrousel, .week-selection-carrousel');

    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'});

        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 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')";
          }
        }
    }
}


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 addBorder(dataTable) {
    if(ie7 || ie6) {
        dataTable.select('tbody tr:not(:last-child)').each(function(elem) {
            elem.insert({after: '<tr class="border-row"><td colspan="9"></td></tr>'});
        });
    }
}

/* ---------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 quickFAQ() {
    $j('.quick-faq dt').click(function() {
        if(!$j(this).hasClass('active')) {
            $j('.quick-faq dt').removeClass('active');
            $j('.quick-faq dd').slideUp('fast');
            $j(this).addClass('active').next('dd').slideDown('fast');
        }
        else {
            $j(this).removeClass('active').next('dd').slideUp('fast');
        }
    });
}


function FAQ() {
    $j('.faq li h2').click(function() {
        var parentLi = $j(this).parent('li');
        if(parentLi.hasClass('active')) {
            parentLi.removeClass('active');
            $j(this).next('.dl-wrapper').slideUp('fast', function() {
                $j(this).find('dd').removeClass('active').hide();
            });
        }
        else
            openAnswer($j(this).next('.dl-wrapper').find('dd').first());
    });

    $j('.faq dt').click(function() {
        openAnswer($j(this).next('dd'));
    });

    function openAnswer(answer) {
        if(answer.hasClass('active')) {
            answer.removeClass('active').slideUp('fast');
        }
        else {
            var newLiActive = answer.parents('.faq li');

            if(newLiActive.hasClass('active')) {
                answer.siblings('dd').removeClass('active').slideUp('fast');
                answer.addClass('active').slideDown('fast');
            }
            else {
                newLiActive.addClass('active').siblings().removeClass('active')
                    .find('.dl-wrapper').slideUp('fast', function() {
                        $j(this).find('dd').removeClass('active').hide();
                    });
                answer.addClass('active').show();
                newLiActive.find('.dl-wrapper').slideDown('fast');
            }
        }
    }
}

var msgWindow;
function openWindow(url, _w, _h, scroll) {
    posX = (screen.width) ? (screen.width - _w)/ 2 : 0;
    posY = (screen.height) ? (screen.height - _h)/ 2 : 0;
    window.focus();
    try{
        if( typeof(msgWindow)=='object')
            msgWindow.close();
    }
    catch(e){}

    msgWindow = open('','window1','top='+posY+', left='+posX+', width='+_w+', height='+_h+', menubar=no, status=yes, location=no, toolbar=no, scrollbars='+scroll);
    msgWindow.location.href = url;if(msgWindow.opener==null) msgWindow.opener=self;msgWindow.focus();
};



/*Varien.DOB.prototype.initialize = function(selector, required, format) {
    var el        = $$(selector)[0];
    this.day      = Element.select($(el), '.dob-day select')[0];
    this.month    = Element.select($(el), '.dob-month select')[0];
    this.year     = Element.select($(el), '.dob-year input')[0];
    this.dob      = Element.select($(el), '.dob-full input')[0];
    this.advice   = Element.select($(el), '.validation-advice')[0];
    this.required = required;
    this.format   = format;

    this.day.validate = this.validate.bind(this);
    this.month.validate = this.validate.bind(this);
    this.year.validate = this.validate.bind(this);

    this.year.setAttribute('autocomplete','off');

    this.advice.hide();
}*/

