/**
* @classDescription Carousel Management Class.
*/
var Carousel = {

    /**
    * Initing carousel - Check if carousel load is needed, sets options values and launch carousel. 
    * @method
    */
    init: function() {

        if (jQuery('.innerCarousel').length > 0) {

            // variables
            var itemToCreate, controls, items, btnArray = [], indexCurrent, itemReference;

            // removing default behaviour for carousel action buttons
            jQuery('#productDisplay #nextMain, #productDisplay #prevMain, .controls a').live('click', function(event) {
                event.preventDefault();
            });

            // generating bottom controls
            itemToCreate = Math.ceil(jQuery('#productCarousel li').length / 3);
            controls = '<div class="controls size-' + itemToCreate + '"><ul>';

            if (itemToCreate > 1) {
                for (var i = 0; i < itemToCreate; i++) {

                    // new control to add
                    controls += '<li><a href="#" class="' + i + '">Page ' + (i + 1) + '</a></li>';

                    // keeping new created items xpath path
                    btnArray.push('.controls .' + i);
                    btnArray.push('');
                    btnArray.push('');
                }
            }
            controls += '</ul></div>';
            btnArray = btnArray.slice(0, jQuery('#productCarousel li').length);

            // appending controls
            jQuery('#productDisplay').append(controls);
            jQuery('.controls .0').addClass('active');

            var options = {
                circular: false,
                visible: 3,
                scroll: 3,
                speed: 500,
                btnGo: btnArray
            }

            // removing controls if less than 3 items are present
            if (jQuery('#productDisplay .innerCarousel li').length < 4) {
                jQuery('#productDisplay #prevMain, #productDisplay #nextMain').hide();
            }


            // launching carousel
            Carousel.load(jQuery('#productDisplay .innerCarousel'), options);

        }
    },
    /**
    * Load carousel. 
    * @method
    * @param	{Object}	obj			Carousel jQuery object.
    * @param	{Array}		options		Options array
    */
    load: function(obj, options) {

        jQuery(obj).jCarouselLite({
            // generic parameters
            btnNext: '.next',
            btnPrev: '.prev',

            // options set while initing carousel
            circular: options.circular,
            visible: options.visible,
            scroll: options.scroll,
            speed: options.speed,
            btnGo: options.btnGo,
            afterEnd: function(a) {
                jQuery(".controls .active").removeClass("active");
                var indexItem = jQuery("#productCarousel li").index(jQuery(a));
                indexItem = Math.ceil(indexItem / 3);
                jQuery(".controls li a." + indexItem).addClass("active");
            }
        });
    }
}



/**
* @classDescription Product page Management Class.
*/
var Product = {
    /**
    * Initing product page elements - Quantity management and zoom 
    * @method
    */
    init: function() {
        if (jQuery('#fiche-produit')) {

            // inits product quantity controls
            //Product.quantity.init();

            // inits product zoom
            Product.zoom();

        }


    },
    quantity: {
        /**
        * Inits quantity methods 
        * @method
        */
        init: function() {

            // Binding links
            jQuery('.quantite a').bind('click', function(event) {
                // Preventing default behaviour
                event.preventDefault();

                var link = jQuery(this);

                // attributing action
                switch (jQuery(this).attr('class')) {
                    case 'more':
                        Product.quantity.add(link);
                        break;
                    case 'less':
                        Product.quantity.remove(link);
                        break;
                };
                link.blur();
            });

            // Binding input
            jQuery('.quantite input').bind('focus', function() {
                jQuery(this).blur();
            });


        },
        /**
        * Add 1 to current quantity. 
        * @method
        * @param	{OBJECT}	link	Clicked link
        */
        add: function(link) {

            var quantity = jQuery(link).siblings('input').val();
            quantity++;

            jQuery(link).siblings('input').val(quantity);
        },
        /**
        * Remove 1 to current quantity unless quantity equals to 1. 
        * @method
        * @param	{OBJECT}	link	Clicked link
        */
        remove: function(link) {

            var quantity = jQuery(link).siblings('input').val();

            if (quantity > 1) {
                quantity--;
                jQuery(link).siblings('input').val(quantity);
            }


        }
    },
    /**
    * Inits product zoom 
    * @method
    */
    zoom: function() {
        if ($('.cloud-zoom, .cloud-zoom-gallery').length != 0) $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
    }
}


/**
* @classDescription Popins Management Class.
*/
Popins = {
    /**
    * Inits popin management 
    * @method
    */
    init: function() {
        jQuery('.popinContainer').appendTo('#regroupPopins');
        // close action
        //jQuery('.close').live('click', function(evt) {
        //evt.preventDefault();
        //Popins.close(jQuery(this));
        //});
        jQuery('.doClose').live('click', function(evt) {
            evt.preventDefault();
            Popins.close(jQuery(this));
        });
        jQuery('.bgPopin').live('click', function(evt) {
            evt.preventDefault();
            Popins.close(jQuery(this));
        });
        $(document).bind('keydown', function(e) {
            var target = e.which;
            if (target == 27) { Popins.close(jQuery('.doClose')); }
        });
        // binding elements that call popins
        jQuery('[class*=popin-]').bind('click', function(evt) {
            // preventing default behaviour
            evt.preventDefault();

            // launching popin
            Popins.launch(jQuery(this));

            // removes focus
            jQuery(this).blur();
        });
		
		$('p.title').append('<span  class="line" />');

    },
    /**
    * Cleans popin states
    * @param	{Object}		Main popin container 
    * @method
    */
    clean: function(obj) {

        switch (jQuery(obj).attr('id')) {

            // clears type1 popin 
            case 'deleteAddress':
                jQuery(obj).find('.doDelete').attr('href', '');
                break;

            // clears type2 popin 
            case 'type2':
                break;
        }
    },
    /**
    * Closes popin 
    * @param	{Object}		Clicked link
    * @method
    */
    close: function(link) {

        jQuery(link).parents('.popinContainer').hide();

        relatedProductId = '';

        // Cleaning popin states
        Popins.clean(jQuery(link).parents('.popinContainer'));
    },
    /**
    * Launches popin 
    * @param	{Object}		Clicked link (jQuery object) 
    * @method
    */
    launch: function(link) {

        // setting popin type
        var elmClass = jQuery(link).attr('class').split(' ');
        var reg = new RegExp(/^popin-/);
        var type = '';

        for (var i = 0; i < elmClass.length; i++) {
            if (elmClass[i].match(reg)) {
                type = elmClass[i].split('popin-')[1];
            }
        }

        // setting popin properties
        Popins.setOpacity();
        Popins.setPosition(jQuery('#' + type));

        // different actions to take for each popin type
        switch (type) {

            // Delete address popin 
            case 'deleteAddress':

                // filling link with right delete value
                //jQuery('#' + type).find('.doDelete').attr('href', jQuery(link).attr('href'));

                break;


            // type2 popin 
            case 'type2':
                break;
        }

        relatedProductId = type;

        // displaying popin
        jQuery('#' + type).show();
    },
    /**
    * Displays popin - simplier launch function. To enable calls as page loads 
    * @param	{Object}		Popin ID
    * @method
    */
    display: function(type) {

        // setting popin properties
        Popins.setOpacity();
        Popins.setPosition(jQuery('#' + type));

        // displaying popin
        jQuery('#' + type).show();
    },
    /**
    * Special method to launch marketing popin
    * @param	{obj}		Popin main container
    * @method
    */
    marketing: function (id) {
        /**
        * Cookie management
        * @method
        */
        var manageCookie = {
            /**
            * Sets up a cookie if not present
            * @method
            */
            setCookie: function () {
                if (!manageCookie.getCookie('annickGoutalMktg')) {
                    // cookie expiry time
                    var date = new Date();
                    date.setTime(date.getTime() + (24 * 60 * 60 * 1000)); // 1 day

                    var expires = '; expires =' + date.toUTCString();

                    // write cookie
                    document.cookie = 'annickGoutalMktg = marketingPopin' + expires + '; path=/';
                    Popins.display(id);
                }
            },
            /**
            * Gets the cookie
            * @method
            */
            getCookie: function (name) {
                var cookieName = name + "=";

                // array of all domain cookies
                var cookieArray = document.cookie.split(';');

                // through all cookies
                for (var i = 0; i < cookieArray.length; i++) {
                    var cookie = cookieArray[i];

                    // removing first character if space until it's not a space anymore
                    while (cookie.charAt(0) == ' ') {
                        cookie = cookie.substring(1, cookie.length);
                    }
                    // if right cookie, then get cookie value and return it
                    if (cookie.indexOf(cookieName) == 0) {
                        return cookie.substring(cookieName.length, cookie.length);
                    }
                }

                // if nothing found, return null
                return null;
            }
        }

        if (jQuery('.launchMarketingPopin').length > 0)
            manageCookie.setCookie();
    },
    /**
    * Sets height for opacity layer
    * @method
    */
    setOpacity: function() {
        jQuery('.bgPopin').css('height', jQuery(document).height());
    },
    /**
    * Calculate and sets popin top position
    * @param	{obj}		Popin main container
    * @method
    */
    setPosition: function(obj) {

        if (jQuery(window).scrollTop() == 0) {
            jQuery(obj).find('.innerPopin:first').css('top', '100px');
        } else {
            jQuery(obj).find('.innerPopin:first').css('top', jQuery(window).scrollTop() + 100);
        }
    }

}


/**
* @classDescription Utilities Class.
*/
var Utilities = {
    /**
    * Inits Utilities methods
    * @method
    */
    init: function() {
        // input management
        Utilities.clearInputs();

        // set columns in main navigation
        Utilities.setMainNav();

        // secondary navigation management
        Utilities.toggleSecondNav();

        // favorites - select all items
        Utilities.selectAll();

        // gift message
        Utilities.writeMsg();

        // Order recap
        Utilities.toggleRecap();

        // Press lightbox
        Utilities.preview();
    },
    /**
    * Clearing inputs default state
    * @method
    */
    clearInputs: function() {

        // inputs to apply to (takes a jQuery path for each input or group of inputs)
        var inputs = ['#searchArea input:text', '#newsletterArea input:text'];

        for (var i = 0; i < inputs.length; i++) {

            jQuery(inputs[i]).bind('focus', function() {
                if (jQuery(this).val() == jQuery(this).attr('defaultValue')) {
                    jQuery(this).val('');
                }
            })
			.bind('blur', function() {
			    if (jQuery(this).val() == '') {
			        jQuery(this).val(jQuery(this).attr('defaultValue'));
			    }
			});
        }
    },
    /**
    * Selects all products in favorites cart
    * @method
    */
    selectAll: function() {
        jQuery('.cartForm .validation a span').bind('click', function(event) {
            // preventing default behaviour
            event.preventDefault();

            if (jQuery(this).attr('class') == 'selectAll') {
                jQuery('.cartForm .cartArea :checkbox').attr('checked', 'checked');
                jQuery('.cartForm .validation a span').toggle();
            } else {
                jQuery('.cartForm .cartArea :checkbox').attr('checked', '');
                jQuery('.cartForm .validation a span').toggle();
            }



        });
    },
    /**
    * Secondary navigation handling 
    * @method
    */
    toggleSecondNav: function() {
        jQuery('#secondaryNavigation a').bind('click', function(event) {
            // jQuery(this) in a variable for performance
            var link = jQuery(this);


            // preventing default behaviour
            if (link.next().length > 0) {
                event.preventDefault();
            }


            // checking if a same level menu is already active
            link.parent().siblings('.active').find('ul').slideUp().end()
											 .removeClass('active')
											 .find('.active').removeClass('active');


            link.next().find('.active').removeClass('active').end()
					   .find('ul').slideUp().end()
					   .slideToggle().end()
					   .parent().toggleClass('active');


        });
		jQuery('#secondaryNavigationDark a').bind('click', function(event) {
            // jQuery(this) in a variable for performance
            var link = jQuery(this);


            // preventing default behaviour
            if (link.next().length > 0) {
                event.preventDefault();
            }


            // checking if a same level menu is already active
            link.parent().siblings('.active').find('ul').slideUp().end()
											 .removeClass('active')
											 .find('.active').removeClass('active');


            link.next().find('.active').removeClass('active').end()
					   .find('ul').slideUp().end()
					   .slideToggle().end()
					   .parent().toggleClass('active');


        });
		jQuery('#secondaryNavigationLight a').bind('click', function(event) {
            // jQuery(this) in a variable for performance
            var link = jQuery(this);


            // preventing default behaviour
            if (link.next().length > 0) {
                event.preventDefault();
            }


            // checking if a same level menu is already active
            link.parent().siblings('.active').find('ul').slideUp().end()
											 .removeClass('active')
											 .find('.active').removeClass('active');


            link.next().find('.active').removeClass('active').end()
					   .find('ul').slideUp().end()
					   .slideToggle().end()
					   .parent().toggleClass('active');


        });
    },
    /**
    * Set columns in main navigation 
    * @method
    */
    setMainNav: function() {
        var col;
        var subTitleWidth;
        var colWidth;
        var subWidth = 0;
		
		if(!$('#mainNavigation  ul  li div .arrow')[0]) $('#mainNavigation  ul  li > div').prepend('<span class="arrow" />');
		
        $('#mainNavigation  ul  li').bind('mouseenter', function() {
            for (var i = 0; i < $(this).find('div > ul > li').length; i++) {
                if (jQuery.browser.msie) $(this).find('div').css('display', 'block');
                col = $(this).find('ul > li:eq(' + i + ')').children('ul').length;
                subTitleWidth = $(this).find('p').eq(i).width();
                if (subTitleWidth > col * 150) colWidth = subTitleWidth + 13;
                else colWidth = col * 150 + 13;
                subWidth += colWidth;
            }
            $(this).find('div').css('width', subWidth + 10 + 'px');
        });
        $('#mainNavigation  ul  li').bind('mouseleave', function() {
            if (jQuery.browser.msie) $(this).find('div').css('display', 'none');
            subWidth = 0;
            $(this).find('div').css('width', '');
        });
    },
    /**
    * Toggles gift message box 
    * @method
    */
    writeMsg: function() {
        jQuery('.writeMsg :radio').bind('click', function() {

            if (jQuery(this).nextAll('textarea').length > 0) {
                jQuery(this).nextAll('textarea').text(giftText);
                jQuery(this).nextAll('textarea').show('slow');
                jQuery(this).nextAll('.messageHeader').show('slow');
                document.getElementById('allGiftError').style.display = "";

            } else {
                jQuery(this).parents('.writeMsg').find('textarea').hide();
                jQuery(this).parents('.writeMsg').find('.messageHeader').hide();
                document.getElementById('allGiftError').style.display = "none";
                giftText = jQuery(this).parents('.writeMsg').find('textarea').text();
                jQuery(this).parents('.writeMsg').find('textarea').text('');

            }

        });

    },
    toggleRecap: function() {
        jQuery('.recapCart a').bind('click', function(event) {
            event.preventDefault();
            jQuery(this).blur()
						.toggleClass('opened');
            jQuery(this.hash).toggle();
        });
    },
    /**
    * Press lightbox function
    * @method
    */
    preview: function() {

        if (jQuery('.presseList')[0]) {
            // binding bottom link
            jQuery('.presseList .details a').bind('click', function(event) {
                event.preventDefault();
                jQuery(this).parent().prevAll('a').trigger('click');
            });

            jQuery('.presseList li > a').lightBox({
                overlayOpacity: .58,
                containerBorderSize: 17,
                containerResizeSpeed: 650,
                imageBlank: '../img/static/lightbox-blank.gif',
                imageBtnClose: '../img/static/lightbox-btn-close.gif',
                imageBtnPrev: '../img/static/lightbox-btn-prev.gif',
                imageBtnNext: '../img/static/lightbox-btn-next.gif',
                txtOf: '/'
            });
        }
    }
}

/**
* @classDescription Salespoints Class.
*/
var Salespoints = {
    /**
    * Inits Salespoints methods
    * @method
    */
    init: function() {

        // binding items 
        jQuery('.salesPoints li ul:not(.addressNav) li').live('click', function() {

            jQuery(this).siblings().removeClass('active').end()
						.addClass('active');

        });

        if (jQuery('.salesPoints').length) {
            Salespoints.buildShopLists('../ressources/shops.xml');
            Salespoints.buildRetailerLists('../ressources/retailers.xml');
        }

    },
    /**
    * Building salespoints shops lists
    * @method
    * @param	{String}	file		File url
    */
    buildShopLists: function(file) {

        jQuery('.addressNav li:first').hide();

        // binding previous/next navigation
        jQuery('.addressNav li a').bind('click', function(event) {
            event.preventDefault();

            var link = jQuery(this);
            var shopList = link.parents(':eq(1)').next();
            var prevItem = jQuery(shopList).find('.current').prev();
            var nextItem = jQuery(shopList).find('.current').next();

            jQuery(shopList).find('.current').fadeOut(300, function() {
                jQuery(this).removeClass('current');

                switch (link.parent().attr('class').split(' ')[0]) {

                    case 'prev':

                        if (prevItem.prev().length == 0) {
                            link.parent().hide();
                            link.parent().next().show();
                        } else {
                            link.parent().show()
										 .removeClass('end');
                            link.parent().next().show();
                        }

                        prevItem.fadeIn(450, function() {
                            jQuery(this).addClass('current');
                        });
                        break;
                    case 'next':

                        if (nextItem.next().length == 0) {
                            link.parent().hide();
                            link.parent().prev().show()
												.addClass('end');
                        } else {
                            link.parent().show();
                            link.parent().prev().show()
												.removeClass('end');
                        }


                        nextItem.fadeIn(450, function() {
                            jQuery(this).addClass('current');
                        });
                        break;
                }
            });
        });
		
        // getting data
        jQuery.ajax({
            url: file,
            dataType: 'json',
            complete: function(data) {

                var shops = jQuery(data.responseXML);

                // Building countries
                var countries = Salespoints.toSimpleList(shops.find('country'));

                // appending countries
                jQuery('.salesPoints:first .countries').append(countries);
                jQuery('.salesPoints:first .countries li').each(function(i) {


                    // cities
                    jQuery(this).data('cities', shops.find('country:eq(' + i + ') cities > city'))
								.bind('click', function() {

								    // cleaning
								    jQuery('.salesPoints:first .cities ul, .salesPoints:first .addresses ul:not(.addressNav)').remove();
								    jQuery('.salesPoints:first .addressNav').hide()
																			.find('li:first').hide().removeClass('end').end()
																			.find('li:last').show();

								    // Building cities list
								    var cities = jQuery(this).data('cities');

								    cities = Salespoints.toSimpleList(cities);
								    jQuery('.salesPoints:first .cities').append(cities);

								    jQuery('.salesPoints:first .cities li').each(function(j) {

								        jQuery(this).data('shops', shops.find('country:eq(' + i + ') cities > city:eq(' + j + ') stores > store'))
													.bind('click', function() {

													    // cleaning
													    jQuery('.salesPoints:first .addresses ul:not(.addressNav)').remove();
													    jQuery('.salesPoints:first .addressNav').hide()
																								.find('li:first').hide().removeClass('end').end()
																								.find('li:last').show();

													    // Building store list
													    var boutiques = jQuery(this).data('shops');
													    boutiques = Salespoints.toShopList(boutiques);

													    if (jQuery(this).data('shops').length > 1) {
													        jQuery('.salesPoints:first .addressNav').show();
													    } else {
													        jQuery('.salesPoints:first .addressNav').hide();
													    }

													    jQuery('.salesPoints:first .addresses').append(boutiques)
																							   .find('ul:last li:first').addClass('current');
																							   
														if($('.address li').length > 1) $('.otherstore').show();
														else $('.otherstore').hide();
														
														$('.otherstore').click(function() {
															if($('.address .current').index() < $('.address li').length - 1) {
																$('.addressNav .next a').triggerHandler('click');
															}
															else {
																$('.address li.current').removeClass('current').fadeOut(400, function() {
																	$('.address li:first').addClass('current').fadeIn(400);
																});
																$('.addressNav .prev').hide();
																$('.addressNav .next').show();
																
															}
														});
													});
								    });
								});
                });
            }
        });
    },
    /**
    * Building salespoints shops lists
    * @method
    * @param	{String}	file		File url
    */
    buildRetailerLists: function(file) {

        // getting data
        jQuery.ajax({
            url: file,
            dataType: 'json',
            complete: function(data) {

                var shops = jQuery(data.responseXML);

                // Building countries
                var countries = Salespoints.toSimpleList(shops.find('country'));

                // appending countries
                jQuery('.otherSalesPoints:first .countries').append(countries);
                jQuery('.otherSalesPoints:first .countries li').each(function(i) {


                    // cities
                    jQuery(this).data('cities', shops.find('country:eq(' + i + ') cities > city'))
								.bind('click', function() {

								    // cleaning
								    jQuery('.otherSalesPoints .cities ul, .otherSalesPoints .shops ul, .otherSalesPoints .addresses div').remove();

								    // Building cities list
								    var cities = jQuery(this).data('cities');

								    cities = Salespoints.toSimpleList(cities);
								    jQuery('.otherSalesPoints .cities').append(cities);

								    jQuery('.otherSalesPoints .cities li').each(function(j) {

								        jQuery(this).data('shops', shops.find('country:eq(' + i + ') cities > city:eq(' + j + ') stores > store'))
													.bind('click', function() {

													    // cleaning
													    jQuery('.otherSalesPoints .shops ul, .otherSalesPoints .addresses div').remove();

													    // Building store list
													    var boutiques = Salespoints.toSimpleList(jQuery(this).data('shops'));
													    jQuery('.otherSalesPoints .shops').append(boutiques);

													    jQuery('.otherSalesPoints .shops li').each(function(k) {

													        jQuery(this).data('boutique', shops.find('country:eq(' + i + ') cities > city:eq(' + j + ') stores > store:eq(' + k + ')'))
																		.bind('click', function() {

																		    //cleaning
																		    jQuery('.otherSalesPoints .addresses div').remove();

																		    // building shop details
																		    var boutique = Salespoints.toRetailerItem(jQuery(this).data('boutique'));
																		    jQuery('.otherSalesPoints .addresses').append(boutique);
																		});
													    });
													});
								    });
								});
                });
            }
        });
    },
    /**
    * Builds item lists
    * @method
    * @param	{Object}	tree		XML tree
    */
    toSimpleList: function(tree) {

        var set = '';
        var name;

        jQuery(tree).each(function(i) {
            name = jQuery(this).find('name:eq(0)').text();
            set = set + '<li>' + name + '</li>';
        });

        set = '<ul>' + set + '</ul>';

        return set;
    },
    /**
    * Builds shop list
    * @method
    * @param	{Object}	tree		XML tree
    */
    toShopList: function(tree) {

        var set = '';
        var obj, name, address, zip, city, phoneLabel, phoneNumber, scheduleLabel, scheduleTime, photo;

        jQuery(tree).each(function(i) {
            obj = jQuery(this);

            name = obj.find('name').text();
            address = obj.find('address').text();
            zip = obj.find('zip').text();
            city = obj.find('city').text();
            phoneLabel = obj.find('phoneLabel').text();
            phoneNumber = obj.find('phoneNumber').text();
            scheduleLabel = obj.find('scheduleLabel').text();
            scheduleTime = obj.find('scheduleTime').text();
            picture = obj.find('picture').text();

            set = set + '<li><address><strong>' + name + '</strong>' + address + '<br />' + zip + ' ' + city + '</address><p>' + phoneLabel + ' ' + phoneNumber + '</p><p>' + scheduleLabel + '<br />' + scheduleTime + '</p><img src="../img/salespoints/' + picture + '" alt="' + name + '"/></li>';

        });

        set = '<ul class="address">' + set + '</ul>';
		
        return set;
		
		
    },
    /**
    * Builds shop item
    * @method
    * @param	{Object}	tree		JSON tree
    */
    toRetailerItem: function(tree) {

        var set = '';
        var obj, name, address, zip, city, phoneLabel, phoneNumber, scheduleLabel, scheduleTime, photo;

        obj = jQuery(tree);
        name = obj.find('name').text();
        address = obj.find('address').text();
        zip = obj.find('zip').text();
        city = obj.find('city').text();
        phoneLabel = obj.find('phoneLabel').text();
        phoneNumber = obj.find('phoneNumber').text();
        scheduleLabel = obj.find('scheduleLabel').text();
        scheduleTime = obj.find('scheduleTime').text();

        set = set + '<div><address><strong>' + name + '</strong>' + address + '<br />' + zip + ' ' + city + '</address><p>' + phoneLabel + ' ' + phoneNumber + '</p><p>' + scheduleLabel + '<br />' + scheduleTime + '</p></div>';     
	   return set;
    }
}

//Function to display popin from EndRequestHandler
function showPopinIfExists(popinId) {
    var currentPopin = document.getElementById(popinId);

    if (currentPopin != null) {
        Popins.display(popinId);
    }
}

//Function to display popin from EndRequestHandler if another div has not a specific content.
function showPopinWithCheck(popinId, checkDivId, divContent) {
    var currentPopin = document.getElementById(popinId);
    var currentCheckDiv = document.getElementById(checkDivId);

    if (currentPopin != null && currentCheckDiv != null) {
        if (currentCheckDiv.innerHTML != divContent)
            Popins.display(popinId);
    }
}

function showGiftInfo() {
    /*document.getElementById('giftMessageUpdate').style.display = "block";*/
    document.getElementById('showGiftInfo').style.display = "none";
    document.getElementById('hideGiftInfo').style.display = "block";
}

function hideGiftInfo() {
    /*document.getElementById('giftMessageUpdate').style.display = "none";*/
    document.getElementById('showGiftInfo').style.display = "block";
    document.getElementById('hideGiftInfo').style.display = "none";
}

function showGiftMessage() {
    document.getElementById('giftMessageUpdate').style.display = "block";
    document.getElementById('showGiftMessage').style.display = "none";
    /* document.getElementById('hideGiftMessage').style.display = "block";*/
}

function hideGiftMessage() {
    document.getElementById('giftMessageUpdate').style.display = "none";
    document.getElementById('showGiftMessage').style.display = "block";
    /* document.getElementById('hideGiftMessage').style.display = "none";*/
}

function SetKialaPanel() {
    jQuery('.kialaSpan').each(function() {
        jQuery(this).parent().append(jQuery('.fixKiala'));
    });
}

function ClickShippingAnchor() {
    jQuery('.shippingAnchor').click();
}

function ProductList() {
    $('#productDisplay #prevMain, #productDisplay #nextMain').hide();

    // Optionnel
    var products_nb = $('#productDisplay .innerCarousel li').length
    product_height = 0
    maxHeight = 0
    marginTop = 0;

    for (var i = 0; i < products_nb; i++) {
        product_height = $('#productDisplay .innerCarousel li:eq(' + i + ') p').height() - ($('#productDisplay .innerCarousel li:eq(' + i + ') p strong').height() + $('#productDisplay .innerCarousel li:eq(' + i + ') p a').height());
        if (maxHeight < product_height) maxHeight = product_height;
    }
    for (var i = 0; i < products_nb; i++) {
        product_height = $('#productDisplay .innerCarousel li:eq(' + i + ') p').height() - ($('#productDisplay .innerCarousel li:eq(' + i + ') p strong').height() + $('#productDisplay .innerCarousel li:eq(' + i + ') p a').height());
        marginTop = maxHeight - product_height;
        if (marginTop > 0) $('#productDisplay .innerCarousel li:eq(' + i + ') p strong').css('margin-top', marginTop);
    }
}

function setNavigation() {
    var nbMenu = $('#mainNavigation > ul > li').length;
    var menuWidth, totalWidth = 0, liWidth;

    for (var i = 0; i < nbMenu; i++) {
        $('#mainNavigation > ul > li:eq(' + i + ') span').css({'display' : 'inline', 'white-space' : 'nowrap'});
        menuWidth = $('#mainNavigation > ul > li:eq(' + i + ') span').width();
        totalWidth += menuWidth;
    }

    var dw = Math.floor((843 - totalWidth) / nbMenu);

    totalWidth = 0;
    for (var i = 0; i < nbMenu; i++) {
        menuWidth = $('#mainNavigation > ul > li:eq(' + i + ') span').width();
        liWidth = dw + menuWidth;
        totalWidth += liWidth;
        if (totalWidth > 837) liWidth -= (totalWidth - 837);
        $('#mainNavigation > ul > li:eq(' + i + ')').css('width', liWidth);
        $('#mainNavigation > ul > li:eq(' + i + ') > div').css('background-position', '-' + eval(488 - liWidth) + 'px 0');
        $('#mainNavigation > ul > li:eq(' + i + ') span').css('display', 'block');

    }
}

function sampleChoice() {
    if (document.getElementById('sampleChoiceErrorMsg') != null)
        document.getElementById('sampleChoiceErrorMsg').style.display = "none";
    HideSampleChoicePanel();
    $('.servicesArea .inner fieldset div ul li label, .servicesArea .inner fieldset div ul li input').click(function() {
        $('.servicesArea .inner fieldset div ul li input:checked').parents('li').find('img.visuel').addClass('select');
        $('.servicesArea .inner fieldset div ul li input:not(:checked)').parents('li').find('img.visuel').removeClass('select');

        // Coche l'option "non merci" automatiquement si aucun échantillon n'est sélectionné
        if ($('.servicesArea .inner fieldset div ul li input[type=checkbox]:checked').length > 0) $('.servicesArea .inner fieldset div input[type=radio]:first').attr('checked', true);
        else { $('.servicesArea .inner fieldset div input[type=radio]:last').attr('checked', true); }
    });

    // Au choix de l'option "non merci", tous les échantillons sélectionnés se décochent automatiquement
    $('.servicesArea .inner fieldset div input[type=radio]:last').click(function() {
        $('.servicesArea .inner fieldset div ul li input:checked').attr('checked', false);
        $('.servicesArea .inner fieldset div ul li input:not(:checked)').parents('li').find('img.visuel').removeClass('select');
    });

    // Au rechargement de la page, cible les éléments sélectionnés pour ajouter la classe "select"
    $('.servicesArea .inner fieldset div ul li input:checked').parents('li').find('img.visuel').addClass('select');

    // For IE - label doesn't work with image - Permet de cocher la case en cliquant sur l'image
    if (jQuery.browser.msie) {
        $('.servicesArea .inner fieldset div ul li img').click(function() {
            var checkbox = $(this).parent('label').find('input');
            if (checkbox.attr('checked')) checkbox.attr('checked', false);
            else checkbox.attr('checked', true);
        });
    }
    jQuery('.checkSampleCount').bind('click', function() {
        CheckSampleChoice();
    });

    $('.labelSampleCount').each(function() {
        $(this).bind('click', function() {
            CheckSampleChoice($(this).find('.checkSampleCount :checkbox'));
        });
    });
}

function pageLoad(sender, args) {

    // Scripts launch
    jQuery(function(event) {	
    //Carousel.init(); 							// initing carousel
    if ($('#productDisplay')) ProductList(); 	// Remove carousel and show products as a list
        Product.init(); 						// initing product scripts (quantity management, zoom)
        Utilities.init(); 						// initing utilities class (secondary functions like clearing inputs)
        Popins.init(); 							// setting up popins
        Popins.marketing('marketingPopin');     // launch marketing popin
        Salespoints.init(); 					// inits salespoints
        setNavigation();
        if ($('.servicesArea')) sampleChoice();
        
        if (popinToShow != null) {
            showPopinIfExists(popinToShow);
            popinToShow = '';
        }
		
		// JqTransform
		if($('.jqtransformdone').length > 0) $('.jqtransformdone').removeClass('jqtransformdone');
		if($('.form_styled').length > 0) $('.form_styled').jqTransform({ imgPath: '/img/static/' });
		
		// Productlist
		if($('.category #productDisplay')[0]) {
			setTimeout(setProductList, 800);
			autoScrollOnProductList();
		}
		
		// Corpo
		$('#corpo_body .sousNav > li > a').click(function() {
			$(this).siblings('ul').fadeToggle(500, function() {
				$(this).siblings('a').toggleClass('active');
			});
		});
		
		
		
    });
}


function setProductList() {
	
	$('#content .pagination .display li').click(function() {
		if(!$(this).hasClass('selected')) {
			$(this).addClass('selected').siblings().removeClass('selected');
			var view = $(this).attr('id');
			if($(this).attr('id') == "view-large") {
				$('#productDisplay').addClass('large');
				setLargeView();
			}
			else {
				$('#productDisplay').removeClass('large');
				setDefaultView();	
			}
		}
	});
	
	if($('#productDisplay li').length < 3) {
		$('#productDisplay').addClass('large');
		$('#content .pagination .display').hide();
		setLargeView();
	}
	
	
	/* Filter */	
	$('.jqTransformSelectWrapper').click(function() {
		$(this).find('ul').slideToggle(250);
	});
	
	if(!($.browser.msie && parseInt($.browser.version, 10) == 6)) {
		$('.jqTransformSelectWrapper ul').css('visibility', 'hidden').show();
		var liWidth = $('.jqTransformSelectWrapper ul').width();
		$('.jqTransformSelectWrapper span').width(liWidth);
		$('.jqTransformSelectWrapper ul').hide().css('visibility', 'visible');
	}
	$('.jqTransformSelectWrapper ul li').click(function() {
		var productLabel = $(this).text();
		$(this).parent('ul').siblings('span').text(productLabel);
		
		var productType = $(this).attr('filter');
		if(productType == 'all') {
			$('#productDisplay li').show();
		}
		else {
			$('#productDisplay li').hide();
			$('#productDisplay li[filter*="'+ productType +'"]').show();
		}
	});
}

function autoScrollOnProductList() {
	/* Auto scroll */
	$('.category #headerGamme .autoscroll').click(function() {
		var targetOffset = $('#content > h1').offset().top - 20;
		$('html,body').animate({scrollTop: targetOffset}, 600);
	});
}
function setLargeView() {
	$('#productDisplay  li img').each(function() {
		var imgSrc = $(this).attr('src');
			imgSrc = imgSrc.replace('-F.', '-L.');
		$(this).attr('src', imgSrc);
	});
}

function setDefaultView() {
	$('#productDisplay  li img').each(function() {
		var imgSrc = $(this).attr('src');
			imgSrc = imgSrc.replace('-L.', '-F.');
		$(this).attr('src', imgSrc);
	});
}


var Popins;
var popinToShow;
var giftText = '';
var relatedProductId = '';

function Validate(control, maxLines, maxPerLine) {
    var strTemp = "";
    var strLineCounter = 0;
    var strCharCounter = 0;
    for (var i = 0; i < $(control).val().length && strLineCounter < maxLines; i++) {
        var strChar = $(control).val().substring(i, i + 1);
        if (strChar == '\n') {
            strCharCounter = 0;
            strLineCounter += 1;
            if (strLineCounter < maxLines)
                strTemp += strChar;
        }
        else if (strCharCounter == maxPerLine) {
            strLineCounter += 1;
            strCharCounter = 0;
            if (strLineCounter < maxLines) strTemp += '\n' + strChar;
        }
        else {
            strTemp += strChar;
            strCharCounter++;
        }
    }
    if (strTemp != $(control).val()) {
        $(control).val(strTemp);
        document.getElementById('messageError').style.display = "";
        return false;
    }
    return true;
}


String.format = function(text) {
    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there?s nothing to replace
        //just return the original text
        return text;
    }
    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace(new RegExp('\\{' + token + '\\}', 'gi'), arguments[token + 1]);
    }
    return text;
};

//Function to display popin from EndRequestHandler
function ShowPopinIfExists(popinId) {
    var currentPopin = document.getElementById(popinId);

    if (currentPopin != null) {
        Popins.display(popinId);
        return popinId;
    }

    return -1;
}

function HideSampleChoicePanel() {
    if (document.getElementById('sampleChoiceArea') != null)
        document.getElementById('sampleChoiceArea').style.display = "none";
    if (document.getElementById('cartAreaForSampleCount') != null) {
        if (jQuery('.sampleCount').length < 2) {
            document.getElementById('sampleChoiceArea').style.display = "block";
        }
    }
}

function CheckSampleChoice(obj) {
    if (document.getElementById('sampleChoiceErrorMsg') != null)
        document.getElementById('sampleChoiceErrorMsg').style.display = "none";
    var sampleCounter = 0;
    sampleCounter = jQuery('.sampleCount').length;
    sampleCounter += jQuery('.checkSampleCount :checked').length;
    if (sampleCounter > 2) {
        document.getElementById('sampleChoiceErrorMsg').style.display = "";
        if (obj == null)
            return false;
        if (obj.attr('checked'))
            obj.attr('checked', false);
    }
}


function CheckNumberOfSample() {
    if (document.getElementById('sampleChoiceArea') != null) {
        if (jQuery('.sampleCount').length < 1 && jQuery('.checkSampleCount :checked').length < 2) {
            document.getElementById('sampleChoiceErrorMsg').style.display = "";
            return false;
        }
    }
    return true;
}
