﻿/**
* jQuery Maxlength plugin
* @version		$Id: jquery.maxlength.js 18 2009-05-16 15:37:08Z emil@anon-design.se $
* @package		jQuery maxlength 1.0.5
* @copyright	Copyright (C) 2009 Emil Stjerneman / http://www.anon-design.se
* @license		GNU/GPL, see LICENSE.txt
*/
(function(A) { A.fn.maxlength = function(B) { var C = jQuery.extend({ events: [], maxCharacters: 10, status: true, statusClass: "status", statusText: "character left", notificationClass: "notification", showAlert: false, alertText: "You have typed too many characters.", slider: false }, B); A.merge(C.events, ["keyup"]); return this.each(function() { var G = A(this); var J = A(this).val().length; function D() { var K = C.maxCharacters - J; if (K < 0) { K = 0 } G.next("div").html(K + " " + C.statusText) } function E() { var K = true; if (J >= C.maxCharacters) { K = false; G.addClass(C.notificationClass); G.val(G.val().substr(0, C.maxCharacters)); I() } else { if (G.hasClass(C.notificationClass)) { G.removeClass(C.notificationClass) } } if (C.status) { D() } } function I() { if (C.showAlert) { alert(C.alertText) } } function F() { var K = false; if (G.is("textarea")) { K = true } else { if (G.filter("input[type=text]")) { K = true } else { if (G.filter("input[type=password]")) { K = true } } } return K } if (!F()) { return false } A.each(C.events, function(K, L) { G.bind(L, function(M) { J = G.val().length; E() }) }); if (C.status) { G.after(A("<div/>").addClass(C.statusClass).html("-")); D() } if (!C.status) { var H = G.next("div." + C.statusClass); if (H) { H.remove() } } if (C.slider) { G.next().hide(); G.focus(function() { G.next().slideDown("fast") }); G.blur(function() { G.next().slideUp("fast") }) } }) } })(jQuery);
var ie7 = (navigator.appVersion.indexOf("MSIE 7.") == -1) ? false : true;

var Igor = function() {
    // Fancybox general configuration
    var fancyboxOpt = {
        'padding': 20,
        'speedIn': 600,
        'speedOut': 200,
        'scrolling': 'no',
        'overlayShow': true
    },

    // In the Product Slider, space between the list-item
    PRODUCT_SPACING = 70,

    // Number of visible products at the same time in the slider
    VISIBLE_PRODUCT = 3;

    return {
        // Initialize the carousel in the Home page
        initHome: function() {
            var hSize = $('#h-carousel-slides').find('li').size();

            function pagerFactory(idx, slide) {
                var s = idx > hSize - 1 ? ' style="display:none"' : '';
                return '<li' + s + '><a href="#">' + (idx + 1) + '</a></li>';
            };

            $('#h-carousel-slides').cycle({
                fx: 'scrollLeft',
                timeout: 7000,
                easeIn: 'easeOutBack',
                easeOut: 'easeInBack',
                delay: 0,
                prev: '#h-carousel-prev',
                next: '#h-carousel-next',
                pager: '#h-carousel-nav',
                sync: 0,
                pause: 1,
                cleartype: true, /* remove ie white background due to png. */
                cleartypeNoBg: true,
                pagerAnchorBuilder: pagerFactory
            });

        },



        // Initialize lightbox on the "Bricolage" tutorials
        initBricolage: function() {
            $("#bricolage a").fancybox(fancyboxOpt);
        },


        // Initialize lightbox on the "Bricolage" tutorials
        initColoriage: function() {
            $("#coloriage a").fancybox(fancyboxOpt);
        },


        // Initialize the Product Slider
        initProductSlider: function() {
            // Cache all the element from the slider
            var $listCategories = $('#productCategories').find('a'),
                $listProducts = $('#productDescription'),
                $btnPrev = $('#productNext'),
                $btnNext = $('#productPrev'),
                selectedCat,
                $matchingProducts,
                $fadeArrows = $("#productArrowsBg,#productPrev, #productNext"),
                $fadeSpeed = 1000,
                $ie = $.browser.msie;

            // Get the width of a product list-item for the position when using nav buttons
            productWidth = $('#productDescription ul:eq(0)').find('li:eq(0) a').width() + PRODUCT_SPACING;

            // Get the name of the selected category or get the first one if none found
            if (!$('#productCategories').find('a.active').length) {
                $listCategories.first().addClass('active');
            }
            selectedCat = $listCategories.filter('.active').attr('href').replace('#', '');

            // Show the product items corresponding to the selected category
            $matchingProducts = $('#productDescription').find('a[rel=' + selectedCat + ']');

            // Verify if the total size of products is higher than the "VISIBLE_PRODUCT" constant
            if ($matchingProducts.size() > VISIBLE_PRODUCT) {

                // On page load fade in Arrows
                // PNG glitch when fading
                if ($ie)
                    $fadeArrows.show();
                else
                    $fadeArrows.fadeIn($fadeSpeed);

                // Get the current product index
                var $selectedProductIndex = $matchingProducts.filter('.active').parent().index() + 1;

                // Verify if the selected product is higher than the "VISIBLE_PRODUCT" constant
                if ($selectedProductIndex > VISIBLE_PRODUCT) {

                    // Get the number of hidden products
                    var $hiddenProducts = $selectedProductIndex - VISIBLE_PRODUCT,

                    // New left value for the selected product list
					$newLeftValue = productWidth * $hiddenProducts,

                    // Find the current product list
					$matchingProdList = $('#productDescription').find('ul[data-category="' + selectedCat + '"]');

                    // Set the new Left value to the matching product list
                    $matchingProdList.css({ left: "-" + $newLeftValue + 'px' });
                }
            }

            // PNG glitch when fading
            if ($ie)
                $matchingProducts.parents('ul').show();
            else
                $matchingProducts.parents('ul').fadeIn();

            // Bind the action when a user selects a Category
            $listCategories.bind('click', function(e) {
                var $this = $(this),
                    $matchingProdList,
                    $newProdList,
                    $newProdListTotal;

                e.preventDefault();

                // Handle the styling class on the active category
                $listCategories.removeClass('active');
                $this.addClass('active');

                // Find the current list and animate it with easing out of the view scope
                $matchingProdList = $('#productDescription').find('ul[data-category="' + selectedCat + '"]');
                $matchingProdList.animate({ left: '-800px' }, 600, 'easeInBack', function() {
                    $(this).hide().css({ left: '800px' });

                    // Get the total number of Products of the new list
                    $newProdListTotal = $('#productDescription').find('ul[data-category="' + $this.attr('href').replace('#', '') + '"]').children().size();

                    //FadeIn/FadeOut arrows if more products than "VISIBLE_PRODUCT" constant
                    if ($newProdListTotal > VISIBLE_PRODUCT) {
                        if ($ie)
                            $fadeArrows.show();
                        else
                            $fadeArrows.fadeIn($fadeSpeed);
                    } else {
                        if ($ie)
                            $fadeArrows.hide();
                        else
                            $fadeArrows.fadeOut($fadeSpeed);
                    }

                    // Get the new matching Product List and animate it in the screen
                    $newProdList = $('#productDescription').find('ul[data-category="' + $this.attr('href').replace('#', '') + '"]');
                    $newProdList.css({ left: '800px', display: 'block' }).animate({ left: '0' }, 600, 'easeOutBack');
                });


                // Reset the selected category
                selectedCat = $this.attr('href').replace('#', '');
            });

            // Bind the action on the previous button click
            $btnPrev.bind('click', function(e) {
                var $curList = $listProducts.find('ul:visible'),
                    listLeft = parseInt($curList.css('left'), 10);

                e.preventDefault();

                if (listLeft && listLeft !== 0) {
                    $curList.animate({
                        left: '+=' + productWidth + 'px'
                    }, 800, 'easeOutBack');
                }
            });

            // Bind the action on the next button click
            $btnNext.bind('click', function(e) {
                var $curList = $listProducts.find('ul:visible'),
                    maxWidth = ($curList.find('li').length - VISIBLE_PRODUCT) * productWidth,
                    listLeft = parseInt($curList.css('left'), 10);

                e.preventDefault();

                if (!listLeft)
                    $curList.css({ left: '0px' });

                if ($curList.find('li:visible').length > 3 && parseInt($curList.css('left'), 10) > -(maxWidth)) {
                    $curList.animate({
                        left: '-=' + productWidth + 'px'
                    }, 600, 'easeInBack');
                }
            });

        },


        // Initialize the elements in the right column of the Product's Page
        // Clicking on "Ingredients" or "Nutrition Facts" toggles the matching container with the infos
        initNutritionInfo: function() {
            var $lnkMoreNutritionInfo = $('#lnkIngredients, #lnkNutritionFacts');

            if ($lnkMoreNutritionInfo.length) {
                $lnkMoreNutritionInfo.bind('click', function(e) {
                    var $this = $(e.target), $target = $this.next();

                    $this.toggleClass('active');

                    if ($target.is(':visible')) {
                        $target.fadeOut('fast');
                    } else {
                        $target.fadeIn('slow');
                    }
                });
            }
        },

        initZoomProducts: function() {
            $("#column_right > a").fancybox(fancyboxOpt);
        },

        // Cuisine accordion + lightbox
        initCuisine: function() {
            // accordion

            var hash = window.location.hash.substring(1);

            if (hash != "") {

                hash = parseInt(hash);
                var currOpened = $('#content-main').find('.cuisine-fold-opened');

                $("#" + hash).addClass('cuisine-fold-opened').find('.cuisine-fold-content').show();

            }


            $('#content-main').find('.cuisine-fold-trigger').click(function(e) {

                var $this = $(this),
                    $parent = $this.parent(),
                    $activeClass = 'cuisine-fold-opened';

                if (!$parent.hasClass('cuisine-fold-opened')) {

                    if (!$.browser.msie) {
                        $this.next().slideDown('slow', function() {
                            $this.find('span').fadeIn(function() {
                                $parent.addClass($activeClass);
                            });
                        });
                    } else {
                        $this.next().show();
                        $this.find('span').show();
                        $parent.addClass($activeClass);

                    }
                } else {

                    if (!$.browser.msie) {
                        $this.next().slideUp('slow', function() {
                            $this.find('span').fadeOut(function() {
                                $parent.removeClass($activeClass);
                            });
                        });
                    } else {
                        $this.next().hide();
                        $this.find('span').hide();
                        $parent.removeClass($activeClass);
                    }

                }

                e.preventDefault();
            });

            var fancyboxCuisineOpt = jQuery.extend({}, fancyboxOpt, {
                'width': 770,
                'height': 500,
                'scrolling': 'auto',
                'autoDimensions': false,
                'type': 'iframe'
            });


            $('#content-main a.fancybox-recette').fancybox(fancyboxCuisineOpt);

        },
        initSuggestions: function() {
            $('#suggestions-wrap').find('a.suggestions-trigger').click(function(e) {
                var $this = $(this),
                        $parent = $(this).parent(),
                        $content = $this.next(),
                        activeClass = 'suggestions-opened';

                if ($parent.hasClass(activeClass)) {

                    $(this).siblings('.suggestions-content').slideUp('slow', function() {
                        $(this).parent().removeClass(activeClass);
                    });

                } else {

                    $('#suggestions-wrap li.suggestions-opened .suggestions-content').slideUp('slow', function() {
                        $(this).parent().removeClass(activeClass);
                    });
                    $this.siblings('.suggestions-content').slideToggle('slow', function() {
                        $(this).parent().toggleClass(activeClass);
                    });

                }

                e.preventDefault();

            });


            // toggle expand		
            $(".show").click(function(e) {
                e.preventDefault();

                $(this).next().next().show();
                $(this).hide();
                $(this).next().show();
            });

            $(".hide").click(function(e) {
                e.preventDefault();
                $(this).next().hide();
                $(this).hide();
                $(this).prev().show();
            });


            // fancybox recette
            var fancyboxSuggestionsOpt = jQuery.extend({}, fancyboxOpt, {
                'width': 770,
                'height': 500,
                'scrolling': 'auto',
                'autoDimensions': false,
                'type': 'iframe'
            });


            $('#suggestions-wrap a.fancybox-recette').fancybox(fancyboxSuggestionsOpt);
        },


        initAccordion: function() {
            var text = {
                'fr': {
                    'txtMasquer': 'Masquer la réponse',
                    'txtAfficher': 'Afficher la réponse'
                },

                'en': {
                    'txtMasquer': 'Hide the answer',
                    'txtAfficher': 'Show the answer'

                }
            }

            //Ajoute un bouton voir la réponse apres chaque question
            $('#accordion > div > div').after('<a href="#" class="btAccordion">' + text[$('html').attr('lang')].txtAfficher + '</a>');
            var $btAccordion = $('#accordion .btAccordion'),
            $h4Accordion = $('#accordion h4');


            //Au clic sur un bouton on affiche ou on masque la réponse
            $btAccordion.click(function() {
                var $this = $(this),
                $target = $(this).prev();

                if (!$this.hasClass('h-opened')) {
                    $this.addClass('h-opened');
                    $target.slideDown('slow');
                    $this.html(text[$('html').attr('lang')].txtMasquer);
                }
                else {
                    $this.removeClass('h-opened');
                    $target.slideUp('slow');
                    $this.html(text[$('html').attr('lang')].txtAfficher);
                }
                return false;
            })

            //Au clic sur le titre on fait comme si on cliquait sur le bouton
            $h4Accordion.click(function() {
                $(this).parent().find('.btAccordion').click();
            });
        },

        initPromos: function() {

            var $ulPromo = $('#content-right').find('#promo-list'),
                $liPromo = $ulPromo.find("li"),
                $liPromoLink = $liPromo.find('a'),
                nombreElementRandom = 2,
                nombreMax = $liPromo.size(),
                tableauNombreAleatoire = [];

            //met tes valeurs random dans un tableau
            for (i = 1; i <= nombreElementRandom; i++) {

                var pigeDifferent = false;

                while (pigeDifferent == false) {

                    var chiffrePige = this.pigerAleatoire(nombreMax),
                        index = $.inArray(chiffrePige, tableauNombreAleatoire);

                    if (index == -1) {
                        pigeDifferent = true;
                        tableauNombreAleatoire.push(chiffrePige);
                    }
                }
            }


            //parcours le tableau pour afficher les li tirés
            $.each(
                tableauNombreAleatoire,
                function(intIndex, objValue) {
                    var indexArray = (objValue) - 1;
                    $liPromo.eq(indexArray).show();
                }
            );

            //enleve les li non affiché et ajoute des classes sur les li affichés. 
            $ulPromo.find("li:not(:visible)").remove();
            //$ulPromo.find("li:even").find('a').addClass("p-left");
            $ulPromo.find("li:odd").find('a').addClass("p-right");
        },

        //piger un nombre aléatoire
        pigerAleatoire: function(nbMax) {
            var rand_no = Math.random();
            rand_no = Math.ceil(rand_no * nbMax);
            return (rand_no);
        },

        accordionCuisineInit: function() {
            var $btAccordion = $('#accordionCuisine > a');

            $btAccordion.click(function() {
                var $this = $(this),
                $target = $(this).next();


                if (!$this.hasClass('h-opened')) {
                    $this.addClass('h-opened');
                    if (ie7 == true) {
                        $target.show();
                    }
                    else {
                        $target.slideDown('slow');
                    }
                }
                else {
                    $this.removeClass('h-opened');
                    if (ie7 == true) {
                        $target.hide();

                    }
                    else {
                        $target.slideUp('slow');
                    }
                }

                return false;

            });

        },

        initComment: function() {
            var fancyboxCommentOpt = jQuery.extend({}, fancyboxOpt, {
                'width': 500,
                'height': 300,
                'scrolling': 'auto',
                'autoDimensions': false,
                'type': 'iframe'
            });

            $('#main-ct a.fancybox').fancybox(fancyboxCommentOpt);
        }
    }





} ();

(function($) {

    // check to see if promo element is present
    if ($('#content-right').find('#promo-list').length) {
        Igor.initPromos();
    }

})(jQuery);
