﻿//
// 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")
        }
    });
}


/**
* Build overlayer menu using a JSON-P response
*
* @author   Thomas Parisot <thomas.parisot@ext.cdiscount.com>
* @version  1.0
* @since    2010-10-26
* @this     window
* @requires jQuery
* @requires BuildMainMenuOverlayersEffects
* @param    {String}  html  HTML response containing div with a 'navlayer-uid-XXX' pattern
*/
function BuildMainMenuOverlayers(html, options) {
    var $ = jQuery,
        $navigation = $('#mainNavigation').addClass('async-loaded'),
        default_options = {
            maxRetry: 5,
            timeout:    700
        };
    options = $.extend({}, default_options, options);

    //DOM not loaded?
    if (options.maxRetry && !$navigation.length) {
        setTimeout(function () {
            --options.maxRetry;
            BuildMainMenuOverlayers(html, options);
        }, options.timeout);

        return;
    }

    //Inject overlayers in each navigation menu
    $containers = $navigation.children('li');
    $(html).find('div.navLayer').each(function () {
        var overlayer = this;

        overlayer.className.replace(/navlayer-uid-(\d+)/, function(m, uid){
            $containers.filter('.univers-uid-' + uid).append(overlayer);
        });
    });

    //Apply hovering effects in a second time
    html = null;
    $containers.each(BuildMainMenuOverlayersEffects);
}
window['BuildMainMenuOverlayers'] = BuildMainMenuOverlayers;

function GetMainMenuOverlayers(url, options) {
    var $ = jQuery;

    $.get(url, function (html) {
        BuildMainMenuOverlayers(html, options);
    });
}

window['GetMainMenuOverlayers'] = GetMainMenuOverlayers;

/**
 * Inserts a new script asynchronuously based on its source URL
 *
 * @author      Thomas Parisot <thomas.parisot@ext.cdiscount.com>
 * @this        window
 * @version     1.0
 * @since       2010-10-26
 */
function InsertAsyncScript(src, elBefore) {
    var d = document,
        script = d.createElement('script'),
        elBefore = elBefore || d.getElementsByTagName('script')[0],
        elBeforeParent = elBefore.parentNode;

    /*
     * Script configuration
     */
    script.type = 'text/javascript';
    script.src = src;

    /*
     * Insertion
     */
    elBeforeParent.insertBefore(script, elBefore);

    return script;
}
window['InsertAsyncScript'] = InsertAsyncScript;

/**
 * Hovering effects builder for the main menu
 * It changes tab colors + reveals the overlayer content.
 * It's a refactored function from the document.ready
 *
 * @author      ?
 * @author      Thomas Parisot <thomas.parisot@ext.cdiscount.com>
 * @this        DomElement  A li.maiNavItem element (a tab)
 * @version     1.1
 * @since       2010-10-26
 */
function BuildMainMenuOverlayersEffects() {
    var $this = $(this);

    //Mouse hover
    $this.bind('mouseover', function () {
        $this.find('a.universLink').not('.currentLink').addClass('activeLink').next().show();
        if ($this.hasClass('jqNoOverLayer')) {
            $this.find('a.universLink').addClass('currentLink activeLink').next().show();
        }
        if ($this.hasClass('jqCurrentLink')) {
            $this.find('a.universLink').next().show();
        }
    })
    .bind('mouseout', function () {
        $this.find('a.universLink').not('.currentLink').removeClass('activeLink').next().hide();
        if ($this.hasClass('jqNoOverLayer')) {
            $this.find('a.universLink').removeClass('currentLink activeLink');
        }
        if ($this.hasClass('jqCurrentLink')) {
            $this.find('a.universLink').next().hide();
        }
    });
}

(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");

            var isActiveTab = container.hasClass('contentareatabsactive');

            if (first == null) {
                first = original;
            }
            else if (first == original) {
                isFirstRowDone = true;
                i = 0;
            }

            if (isFirstRowDone && !isActiveTab) {
                $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;

                if(isActiveTab)
               {
                    $this.html(original);
                    container.css("width", "150px");
               }

                // 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() {
        $('.deleg-c-footer').delegate( { onRedirectClick: function(uri) {
        PopUp(uri, 'FooterLink', screen.availWidth, screen.availHeight, 0, 0, 1, 1, 1, 1, 1, 1, 1);
        } } );

        $('.deleg-c-footer-service').delegate( { onRedirectClick: function(uri) {
        window.location.href = uri;
        } } );

        $('.deleg-c-cdiscount-film').delegate( { onRedirectClick: function(uri) {
        PopUp(uri,'video',440,360,0, 0, 1, 1, 0, 0, 0, 1, 0);
        } } );

    
        historyDisplay();
        $("input.inputMailValue").emptyValue("Votre email");

        // Synchronous overlayers hover effect
        $('#mainNavigation').not('.async-loaded').find('li.mainNavItem').each(BuildMainMenuOverlayersEffects);
        $('#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
            });
        }).mouseleave(function(){
            var bulle = $(".infobulle:last");
            $(this).attr("title",bulle.text());
            bulle.animate(
                {
                    top:bulle.offset().top+7,
                    opacity:0
                },
                50,
                "linear",
                function(){
                    bulle.remove();  
                }
            );
        });

        /**
        * $.refreshArticleCount
        * Allows to refresh the Summary Basket
        *
        * @Requires cdiscount.utils.js
        * @param articleCount : the articles count   
        */
        $.refreshArticleCount = function () {
            if (typeof $.getCookies() != "undefined") {

                var cookieNameInput = $(':input[name=ArticleCountCookieName]');
                if (cookieNameInput.length > 0 && cookieNameInput[0].value != null)
                { 
                    var articleCount = (typeof $.getCookies().articles_count != 'undefined') ? parseInt($.getCookies()[cookieNameInput[0].value]) : 0;
                    if ($("#divNoArticle").length > 0 && $("#divOneArticle").length > 0 && $("#divSeveralArticle").length > 0) {
                        $("#divNoArticle").hide();
                        $("#divOneArticle").hide();
                        $("#divSeveralArticle").hide();
                        switch (articleCount) {
                            case 0:
                                $("#divNoArticle").show();
                                break;
                            case 1:
                                $("#divOneArticle").show();
                                break;
                            default:
                                $("#divSeveralArticle span").text(articleCount);
                                $("#divSeveralArticle").show();
                        }
                    }                        
                }
            }
        }

        $('input.button-continue-shopping-grey').live('click', $.refreshArticleCount);
        var cookieNameInput = $(':input[name=ArticleCountCookieName]');
        if (cookieNameInput.length > 0 && cookieNameInput[0].value != null)
        {
            $.refreshArticleCount();
        }

    });
})(jQuery);


