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

document.observe("dom:loaded", function() {


    //buttons rollover effect (with rollover images preloading)
    btnRollover();

    //custom look of checkboxes, radio buttons & selects
    customCheckboxes();
    customRadioButtons();
    //customSelects();


    //fix for IE png transparency bug
    pngFix();

    //dropdown menu in ie6
    startList();

    //product images carrousel
    animateCarrousel()

    //tabs switching
    tabs();

    //displaying help messages on product page
    helpMessages();

    //fix for IE z-index bug
    fixIE();
    
    //open links in new window
    openExtLink();

});


function btnRollover() {
    var buttons = $$('input[type=image], .list-nav a img');

    for(var i=0, images=[]; i<buttons.length; i++) {
        var newSrc = buttons[i].src.replace('.png', '-over.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;
        }
    }

    //alert(images.length);

    for(var i=0; i<images.length; i++) {
        images[i].onload = function() {
            for(j=0; j<buttons.length; j++) {
                origSrc = this.src.replace('-over', '');
                if(buttons[j].src == origSrc) {
                    buttons[j].observe('mouseover', function(){
                        this.src = this.src.replace('.png', '-over.png');
                    });
                    buttons[j].observe('mouseout', function(){
                        this.src = this.src.replace('-over', '');
                    });
                }
            }
        }
    }
}



function customCheckboxes() {
    var checkboxes = $$('input[type=checkbox]');

    for(var i=0; i<checkboxes.length; i++) {
        var checkbox = checkboxes[i];
        var checkboxLabel = checkbox.next('label');
        if(checkboxLabel) checkboxLabel.addClassName('cfLabel');
        checkbox.addClassName('cfHidden').wrap('span', {'class': 'cfWrapper'});
        var wrapper = checkbox.parentNode;
        wrapper.addClassName('cfWrapper');
        wrapper.insert('<span class="cfCheckbox"></span>');

        wrapper.select('.cfCheckbox')[0].observe('click', function() {
            var checkbox1 = this.previous('input');
            if(checkbox1.checked===true) {
                checkbox1.checked = false;
                this.removeClassName('cfChecked');
            }
            else {
                checkbox1.checked = true;
                this.addClassName('cfChecked');
            }
            if (checkbox1.onclick)
                checkbox1.onclick();
            return false;
        });

        if(checkboxLabel) {
            checkboxLabel.observe('click',function() {
                var checkbox2 = this.previous('.cfWrapper').down('input[type=checkbox]');
                if(checkbox2.checked===true) {
                    checkbox2.next('.cfCheckbox').removeClassName('cfChecked');
                }
                else {
                    checkbox2.next('.cfCheckbox').addClassName('cfChecked');
                }
            });
        }

        //set the default state
        if (checkbox.checked){
            checkbox.next('.cfCheckbox').addClassName('cfChecked');
        }

        $$('.cfHidden').invoke('setOpacity', 0);

    }
}


function customRadioButtons() {
    var radios = $$('.product-colours input[type=radio]');
    for(var i=0; i<radios.length; i++) {
        var radio = radios[i];
        var radioLabel = radio.next('label');
        radioLabel.addClassName('cfLabel');
        radio.addClassName('cfHidden').wrap('span', {'class': 'cfWrapper'});
        var wrapper = radio.parentNode;
        wrapper.addClassName('cfWrapper');
		wrapper.insert({top: '<span class="cfRadio"></span>'});

        wrapper.select('.cfRadio')[0].observe('click', function() {
            var radio1 = this.next('input');
			$$('input[name="'+ radio1.readAttribute('name') +'"]').each(function(el){
				el.checked = false;
                el.previous('.cfRadio').removeClassName('cfChecked');
			});

            this.addClassName('cfChecked');
            radio1.checked = true;
            return false;
        });


        $$('.cfHidden').invoke('setOpacity', 0);
    }
}


function fixIE() {
    if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6)) {
        setTimeout(function() {
           var items = $$('.cfCheckbox');
           for(i=0;i<items.length;i++) {
              items[i].setStyle({
                    height: '15px'
              });
           }
        }, 10);
    }

   var items2 = $$('.product-options');
   for(i=0;i<items2.length;i++) {
      items2[i].setStyle({width: items2[i].getWidth() + 'px'});
   }
}

function pngFix() {

    if(!Prototype.BrowserFeatures.XPath && (ie55 || ie6)) {
        var toFix = $$('.pngfix, span.lace, .main-nav ul li');
        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')";
    			}
        }

        var imgToFix = jQuery('.promo-imgs img[src$=.png]');
		imgToFix.each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="img-replace ' + jQuery(this).attr('class') + '" ' : 'class="img-replace"';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});
    }
}






function startList() {
    if (document.all && document.getElementById) {
        var navRoots = $$('.main-nav');

        for (j=0; j<navRoots.length; j++) {
            navRoot = navRoots[j];
            lis = navRoot.childNodes;
            for (i=0; i<lis.length; i++) {
                node = lis[i];

                if (node.nodeName=="LI") {
                    Event.observe(node, "mouseover",function() {
                        toggleMenu(this, true);
                        ie6selects(this.down('ul'));

                    });
                    Event.observe(node, "mouseout",function() {
                        toggleMenu(this, false);
                        ie6selects(this.down('ul'));
                    });
                }
        }
        }
    }
}




function animateCarrousel() {
    var carrousels = $$('.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('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('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); }
                    });
                }
            });
        }


        carrousel_ul.select('a').each(function(el) {
            el.observe('click', function(){
                carrousel_ul.select('a').invoke('removeClassName', 'active');
                this.addClassName('active');
            });
        });

    }
}


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('active');}
            else
                left_btn.addClassName('active');
        }

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


function tabs() {
    $$('.tabs-nav').each(function(tabNav){
        tabNav.adjacent('.tab-item').invoke('hide');

        tabNav.select('a').each(function(tabLink) {
            if(tabLink.hasClassName('active'))
                $(tabLink.readAttribute('href').replace('#', '')).show();

            tabLink.observe('click', function(event){
                var parentUL = this.parentNode.parentNode;
                parentUL.select('a').invoke('removeClassName', 'active');
                this.addClassName('active');

                parentUL.adjacent('.tab-item').invoke('hide');
                $(this.readAttribute('href').replace('#', '')).show();

                event.stop();
            });
        });

    });
}


function helpMessages() {
    var helpLinks = $$('.help-link');
    if(helpLinks) {
        helpLinks.invoke('observe', 'click', function(event) {
            var nextDiv = this.next('div');
            if(nextDiv.hasClassName('visible'))
            {
                nextDiv.removeClassName('visible');
                if($$('.product-recommend .visible').length == 0)
                    $$('.preview-wrapper').invoke('removeClassName', 'backwards');
            }
            else {
                nextDiv.addClassName('visible');
                if($$('.product-recommend .visible').length == 1)
                    $$('.preview-wrapper').invoke('addClassName', 'backwards');
            }
            Event.stop(event);
        });

        $$('.help-wrapper > div > img').invoke('observe', 'click', function(event) {
            this.up('div').removeClassName('visible');
                if($$('.product-recommend .visible').length == 0)
                    $$('.preview-wrapper').invoke('removeClassName', 'backwards');
        });
    }

    var showPreview = $$('a.show-hide-preview');
    if(showPreview && showPreview.length > 0) {
        var showText = showPreview[0].innerHTML;
        var hideText = showPreview[0].readAttribute('rev');
        showPreview[0].observe('click', function(event) {
            this.next('.widget-preview').toggle();
            if(this.innerHTML == showText)
                this.innerHTML = hideText;
            else
                this.innerHTML = showText;
            Event.stop(event);
        });
    }
}


/*
 * Part of:
 * jNice
 * version: 1.0 (11.26.08)
 * by Sean Mooney (sean@whitespace-creative.com)
 * Examples at: http://www.whitespace-creative.com/jquery/jnice/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
function customSelects() {
	jQuery(document).mousedown(function(event) {
		if (jQuery(event.target).parents('.jNiceSelectWrapper').length === 0) { SelectHide(); }
	});

    /* Hide all open selects */
    var SelectHide = function(){
    	jQuery('.jNiceSelectWrapper ul:visible').hide();
    };

    var SelectAdd = function(element, index){
    	var $select = jQuery(element);
    	index = index || $select.css('zIndex')*1;
    	index = (index) ? index : 0;
    	/* First thing we do is Wrap it */
    	$select.wrap(jQuery('<div class="jNiceWrapper"></div>').css({zIndex: 80-index}));
    	var width = $select.width();
    	$select.addClass('jNiceHidden').after('<div class="jNiceSelectWrapper"><div><span class="jNiceSelectText"></span><span class="jNiceSelectOpen"></span></div><ul></ul></div>');
    	var $wrapper = jQuery(element).siblings('.jNiceSelectWrapper').css({width: width +'px'});
    	jQuery('.jNiceSelectText, .jNiceSelectWrapper ul', $wrapper).width( width - jQuery('.jNiceSelectOpen', $wrapper).width());
    	/* IF IE 6 */
    	if (!Prototype.BrowserFeatures.XPath && (ie55 || ie6)) {
    		$select.after(jQuery('<iframe src="javascript:\'\';" marginwidth="0" marginheight="0" align="bottom" scrolling="no" tabIndex="-1" frameborder="0"></iframe>').css({ height: $select.height()+5 +'px', width: $select.width()+4 +'px' }));
    	}
    	/* Now we add the options */
    	SelectUpdate(element);

		/* Apply the click handler to the Open */
		jQuery('div', $wrapper).click(function(){
		  if(!$select.attr('disabled')) {
		    $wrapper.removeClass('disabled');
			var $ul = jQuery(this).siblings('ul');
			if ($ul.css('display')=='none'){ SelectHide(); } /* Check if box is already open to still allow toggle, but close all other selects */
			$ul.slideToggle("fast");
			var offSet = (jQuery('a.selected', $ul).offset().top - $ul.offset().top);
			$ul.animate({scrollTop: offSet});
			return false;
		  }
		  else
		    $wrapper.addClass('disabled');
		});
		/* Add the key listener */
		$select.keydown(function(e){
		  if(!this.attr('disabled')) {
			var selectedIndex = this.selectedIndex;
			switch(e.keyCode){
				case 40: /* Down */
					if (selectedIndex < this.options.length - 1){ selectedIndex+=1; }
					break;
				case 38: /* Up */
					if (selectedIndex > 0){ selectedIndex-=1; }
					break;
				default:
					return;
					break;
			}
			jQuery('ul a', $wrapper).removeClass('selected').eq(selectedIndex).addClass('selected');
			jQuery('span:eq(0)', $wrapper).html(jQuery('option:eq('+ selectedIndex +')', $select).attr('selected', 'selected').text());
			return false;
		  }
		}).focus(function(){ $wrapper.addClass('jNiceFocus'); }).blur(function(){ $wrapper.removeClass('jNiceFocus'); });

    };

    var SelectUpdate = function(element){
    	var $select = jQuery(element);
    	var $wrapper = $select.siblings('.jNiceSelectWrapper');
    	if($select.attr('disabled'))
    	   $wrapper.addClass('disabled');
    	else
    	   $wrapper.removeClass('disabled');
    	var ulWidth = 0;
    	var $ul = $wrapper.find('ul').find('li').remove().end()/*.hide()*/;
    	jQuery('option', $select).each(function(i){
    		$ul.append('<li><a href="#" index="'+ i +'"><span>'+ this.text +'</span></a></li>');
    		var rowWidth = $ul.find('span').eq(i).outerWidth();
    		if(rowWidth > ulWidth)
    		     ulWidth = rowWidth;
    	});
    	if(ulWidth > .95*$wrapper.width())
            $ul.css({width: ulWidth + 'px'});
    	var ulheight = $ul.children().length*14;
        var ulcssheight = parseInt($ul.css('height').replace('px',''));
    	if(ulheight < ulcssheight) {
            $ul.css({height: ulheight + 'px'});
        } $ul.hide();
    	/* Add click handler to the a */
    	$ul.find('a').click(function(){
    		jQuery('a.selected', $wrapper).removeClass('selected');
    		jQuery(this).addClass('selected');
    		/* Fire the onchange event */
    		if ($select[0].selectedIndex != jQuery(this).attr('index')) { $select[0].selectedIndex = jQuery(this).attr('index'); fireEvent($select[0], 'change'); }
    		$select[0].selectedIndex = jQuery(this).attr('index');
    		jQuery('span:eq(0)', $wrapper).html(jQuery(this).html());
    		$ul.hide();
    		return false;
    	});
    	/* Set the defalut */
    	jQuery('a:eq('+ $select[0].selectedIndex +')', $ul).click();
    };

    var SelectRemove = function(element){
    	var zIndex = jQuery(element).siblings('.jNiceSelectWrapper').css('zIndex');
    	jQuery(element).css({zIndex: zIndex}).removeClass('jNiceHidden');
    	jQuery(element).siblings('.jNiceSelectWrapper').remove();
    };

	jQuery('select').each(function(index){ SelectAdd(this, index); });
}



function SelectsOnChange() {
    jQuery('select').each(function() {
	var $select = jQuery(this);
	var $wrapper = $select.siblings('.jNiceSelectWrapper');
	setTimeout( function() {
        if($select.attr('disabled'))
    	   $wrapper.addClass('disabled');
    	else
    	   $wrapper.removeClass('disabled');
    }, 10);
	var $ul = $wrapper.find('ul').find('li').remove().end();//.hide();
	jQuery('option', $select).each(function(i){
		$ul.append('<li><a href="#" index="'+ i +'"><span>'+ this.text +'</span></a></li>');
	});
	var ulheight = $ul.children().length*14;
    $ul.css({height: ulheight + 'px'});
	//Add click handler to the a
	$ul.find('a').click(function(){
		jQuery('a.selected', $wrapper).removeClass('selected');
		jQuery(this).addClass('selected');
		//Fire the onchange event
		if ($select[0].selectedIndex != jQuery(this).attr('index') ) { $select[0].selectedIndex = jQuery(this).attr('index'); fireEvent($select[0], 'change'); }
		$select[0].selectedIndex = jQuery(this).attr('index');
		jQuery('span:eq(0)', $wrapper).html(jQuery(this).html());
		$ul.hide();
		return false;
	});
	//Set the defalut
	jQuery('a:eq('+ $select[0].selectedIndex +')', $ul).click();
	});
}





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


actionsAfterColorChange = function() {
    //fix for IE png transparency bug
    pngFix();
    //product images carrousel
    animateCarrousel();
    //update custom selects
    SelectsOnChange();
}


function openExtLink() 
{ 
    $$('a.nw-link').each(function(link) {
            link.writeAttribute('title', 'S\'ouvre dans une nouvelle fenêtre'); 

            link.observe('click', function(event)  { 
                window.open(this.href); 
                Event.stop(event);
            }); 
    });

}



function favourites(url, title)
{
    if ( navigator.appName != 'Microsoft Internet Explorer' ) { 
        window.sidebar.addPanel(title, url,""); 
    }
    else { 
        window.external.AddFavorite(url, title); 
    } 
} 

