//
// Left Menu : Permet d'ajouter une class sur la div "leftSidebarRayonTitle" pour les rayons qui doivent s'afficher sur 2 lignes
// La classe "twoLinesRayonTitle" permet ceci.
function vAlignDepartmentLeftMenuV2() {
    $(".selectorLeftSidebar").each(function() {
        if ($(this).height() > 14) {
            $(this).parent(".leftSidebarRayonTitle").addClass("twoLinesRayonTitle")
        }
    });
}

(function($) {

    // Flash Tops
    function change(sitemapnodeid, skinid) {
        $(".stdBombContent .bombInfoContainer").attr("class", "bombInfoContainer univers" + skinid + "");
    }

    //History Navigation
    function historyDisplay() {
        $(".historyDisplayBlock").hide();
        $(".displayPdtList li").each(function() {
            if ($(this).hasClass("active")) {
                var urlBlock = $(this).find("a").attr("rel");
                $("#" + urlBlock).show();
            }
            $(this).find("a").hover(function() {
                $(this).parent("li").siblings().removeClass("active");
                $(this).parent("li").addClass("active");
                var urlBlockDisplay = $(this).attr("rel");
                $("#" + urlBlockDisplay).show();
                $("#" + urlBlockDisplay).siblings().hide();
            }, function() {
            });
        });
    }

    /*************************************************************************
    * fixZIndex
    * Fix the css z-index bug on Ie7 and previous version
    ****************************************************************************/
    $.fn.fixZIndex = function() {
        if ($.browser.msie == true && $.browser.version <= 8) {
            var zIndexNumber = 1000;
            $(this).each(function() {
            $(this).css("zIndex", zIndexNumber);
            zIndexNumber -= 10;
            });
        }
    }; 


    /*************************************************************************
    * Fix tabs size content (used in search brower view) :
    * - the content of elements marqued with "jq-fixTab" are truncated to fit in 
    *  the "contentareatabs" parent width
    * - if the text spans two lines, class twoLinesContentareatabs is added to parent
    *
    * remark : this function assumes that tabs are repeated through the page  
    * with the same labels and in the same order 
    ****************************************************************************/
    $.fn.fixTabsContent = function () {
        var truncatedTexts = []; // already calculated optimals texts 
        var correctedHeights = [];
        var i = 0;
        var first = null;
        var isFirstRowDone = false;

        $("span.jq-fixTab").each(function () {
            $this =  $(this);
            var original =  $this.html();
            var parent =  $this.parent(".contentareatabs");
            var container = parent.parent(".tabs");

            if (first == null) {
                first = original;
            }
            else if (first == original) {
                isFirstRowDone = true;
                i = 0;
            }

            if (isFirstRowDone) {
                $this.html(truncatedTexts[i]);

                if (correctedHeights[i])
                    parent.addClass("twoLinesContentareatabs");
            }
            else {
                var len = original.length;
                var position = $this.position().left;
                var positionP = parent.position().left;                
                var maxWidth = container.width() - (position - positionP) - 4; // 4 : size of the tab image border

                var optimalString = original;

                // Find the optimal string length (by dichotomy)
                var posBottom = 0;
                var posTop = len;
                var pos = 0;
                if ($(this).width() > maxWidth) {
                    while (posTop != posBottom) {
                        if (posTop - posBottom < 2) {
                            pos = posBottom;
                            posTop = posBottom; // end the loop after this iteration
                        }
                        else
                            pos = parseInt((posBottom + posTop) / 2);

                        optimalString = original.substring(0, pos) + "&#8230;"
                        $(this).html(optimalString);
                        var newW = $(this).width();
                        if (newW > maxWidth) {
                            posTop = pos;
                        }
                        else if (newW < maxWidth) {
                            posBottom = pos;
                        }
                        else {
                            posTop = posBottom;
                        }
                    }
                }

                truncatedTexts[i] = optimalString;

                // correct the class if the text spans two lines
                if ($this.height() > container.height()) {
                    parent.addClass("twoLinesContentareatabs");
                    correctedHeights[i] = true;
                }
                else
                    correctedHeights[i] = false;
            }

            i++;
        });
    };
    
    /*************************************************************************
    * picHover
    * Adds a on mouse over effect on pictures
    *  ! Allows to fix ie performance issues with :hover pseudo-class
    *
    * options :
    *   - cssMode : working mode :
    *       - true, hover event changes css class (with over properties)
    *         if several classes are used on the element, only the fist one is changed 
    *       - false, hover event changes image src 
    *   - imgOverSrc : the over image's name
    *   - overClass : the name of the over class
    *  
    ****************************************************************************/
    $.fn.picHover = function(options) {
        var OVER_CSS_SUFFIX = '_over';
        var OVER_IMG_SUFFIX = '-over';

        var settings = {
            imgOverSrc: '',
            overClass: ''
        };

        //extending options
        options = options || {};
        $.extend(settings, options);

        // For each elements applies hover mouse effect 
        $(this).each(function(i) {
            var $this = $(this);
            if ($this.is('input:image, img')) { //image src mode
                changeImgSrc($this);
            } else { //css mode
                changeCss($this);
            }
        });

        // Changes image src
        function changeImgSrc($element) {
            var imgSrc = $element.attr('src');
            var indexExt = imgSrc.lastIndexOf('.');
            var imgOverSrc = (settings.imgOverSrc == '')
                ? imgSrc.substring(0, indexExt) + OVER_IMG_SUFFIX + imgSrc.substring(indexExt, imgSrc.length)
                : settings.imgOverSrc;

            $element.hover(
                function() {
                    $element.attr('src', imgOverSrc);
                },
                function() {
                    $element.attr('src', imgSrc);
                }
            );
        }

        // Changes css style
        function changeCss($element) {
            var className = $element.attr('class').split(' ')[0];
            var classOverName = (settings.overClass == '') ? className + OVER_CSS_SUFFIX : settings.overClass;

            $element.hover(
                function() {
                    $element.addClass(classOverName);
                },
                function() {
                    $element.removeClass(classOverName)
                }
            );
        }
    };

    /**
    * Empty some fields and replace with a default value on load/focus
    * 
    * @todo base that on placeholder attribute to allow HTML5 fallback and nice degradation
    * @todo documentation
    * 
    * @author  Thomas Parisot <tparisot@clever-age.com>
    * @version 1.0
    */
    $.fn.emptyValue = function(inputValue) {
        var value = inputValue;

        return this
	    .bind('focus', function() {
	        var $this = $(this);

	        if ($this.attr("value").toLowerCase() === value.toLowerCase()) {
	            $this.attr("value", "");
	        }
	    })
	    .bind('blur', function() {
	        var $this = $(this);

	        if ($this.attr("value") === "") {
	            $this.attr("value", value);
	        }
	    });
    };

    /**
    * Manage the undisplay/reveal of elements in a container by hovering
    * other elements inside the container.
    *
    * Hide elements (for replacing effect) if there is elements to reveal
    * (if not, the elements are not hided)
    * 
    * @recquires jQuery 1.4.X    * 
    * @author   Thomas Parisot <tparisot@clever-age.com>
    * @author   Boris Schapira <bschapira@clever-age.com>
    * @version 1.1
    */
    $.fn.revealHover = function(options) {
        var default_options = {
            "hoverClass": 'reveal-hover-active',
            "hoverEvent": 'mouseenter',
            "hoverOutEvent": 'mouseleave',
            "itemSelector": '.reveal-hover-item',
            "itemToHideSelector": '.reveal-hover-hide',
            "onHover": $.noop,
            "onHoverOut": $.noop,
            "hoverAddClass": '',
            "hoverRemoveClass": '',
            "hoverOutAddClass": '',
            "hoverOutRemoveClass": '',
            "hideAddClass": '',
            "hideRemoveClass": '',
            "hideOutAddClass": '',
            "hideOutRemoveClass": ''
        };

        options = $.extend({}, default_options, options);

        return this
		.bind(options.hoverEvent, function() {
		    var $this = $(this);

		    var $hoverSelectors = $this.addClass(options.hoverClass).find(options.itemSelector);
            $hoverSelectors.addClass(options.hoverAddClass).removeClass(options.hoverRemoveClass);
            
            if($hoverSelectors.length){
                $this
                    .find(options.itemToHideSelector).addClass(options.hideAddClass).removeClass(options.hideRemoveClass);
                }

		    options.onHover.call(this, options);
		})
		.bind(options.hoverOutEvent, function() {
		    var $this = $(this);

		    var $hoverSelectors = $this.removeClass(options.hoverClass).find(options.itemSelector);
            $hoverSelectors.addClass(options.hoverOutAddClass).removeClass(options.hoverOutRemoveClass);
            
            if($hoverSelectors.length){
                $this
                    .find(options.itemToHideSelector).addClass(options.hideOutAddClass).removeClass(options.hideOutRemoveClass);
                }

		    options.onHoverOut.call(this, options);
		});
    };

    /****** ! DOCUMENT READY EVENT ******/
    

    $(function() {
        historyDisplay();
        $("input.inputMailValue").emptyValue("Votre email");

        // Main Navigation
        // Nouvelle gestion des onglets et overlayers tetiere  
        $('.mainNavItem').each(function(i) {
            var $this = $(this);

            //Mouse hover
            $this.hover(function() {
                if ($this.hasClass('jqNoOverLayer')) {
                    $this.find('.universLink').addClass('currentLink')
                                        .addClass('activeLink');
                }
                else {
                    $this.find('.universLink').removeClass('currentLink')
                                  .addClass('activeLink');
                    $this.find('.navLayer').show();
                }
                /*$('#bigpic').hide();
                $('#manufacturer_list').hide();
                $('#banner').hide();*/
            },
        function() {
            $this.find('.navLayer').hide();
            $('#bigpic').show();
             $('#manufacturer_list').show();
            $('#banner').show();
            if ($this.hasClass('jqCurrentLink')) {
                $this.find('.universLink').addClass('currentLink');
            } else {
                $this.find('.universLink').removeClass('activeLink');
            }

            if ($this.hasClass('jqNoOverLayer')) {
                $this.find('.universLink').removeClass('currentLink')
                                        .removeClass('activeLink');
            }
        });
        });

        $('#ifTravellingSearchBar').attr("src", "http://cdiscount.service-voyages.com/showsearchform-light?iframe=true");

        /**
        * Applying a mouse over effect on images
        */
        if (typeof $.fn.picHover != 'undefined') {
            $('.jq-picHover').picHover();
        }

        /**
        * Fix the css z-index bug on Ie7 and previous version
        */
        if (typeof $.fn.fixZIndex != 'undefined') {
            $('.jq-fixZIndex').fixZIndex();
        }
        /**
        * Infobulle
        *
        * to call the infobull, put the class .infobulle in the link where you want it appear
        * 
        * @see                 js/layout_R2.js
        * 
        * <code>
        *   <span class="infobulle"></span>
        * </code>
        *
        * @author  Nicolas Goueset <nicolas.goueset@cdiscount.com>
        * @version 1.0
        */
        $(".callinfobulle").mouseover(function(){
            if($(this).attr("title")=="") return false;
        
            $("body").append('<span class="infobulle"></span>');
            var bulle = $(".infobulle:last");
            bulle.append($(this).attr("title"));
            $(this).attr("title","");
            var posTop = $(this).offset().top-$(this).height();
            var posLeft = $(this).offset().left+$(this).width()/2-bulle.width()/2;
            bulle.css({
                left:posLeft,
                top:posTop-7,
                opacity:0
            });
            bulle.animate({
                top:posTop-7,
                opacity:0.99
            });
        });

       
    });


    //
})(jQuery);
//



