/**
 * @author Nurun
 */
 
var isIE6 = false;

if(GM === undefined) {
	var GM = {};
}

function GManimBottle() {
		
		var flashvars = {
			url_video:"/templates/homepage/swf/bottle_vid.swf"
		};
		var params = {
			wmode: "transparent"
		};
		var attributes = {
			id: "flashContent",
			name: "flashContent" 
		};
		if (evin==0) swfobject.embedSWF("/templates/homepage/swf/bottle.swf", "flashContent", "258", "551", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}



function GMvideo(vFlv) {
	var video = null;
	switch(vFlv){
		case 0:
		video = 'cognacs';
		break;
		case 1:
		video = 'oranges';
		break;
		case 2:
		video = 'recette';
		break;
		case 3:
		video = 'bottling';
		break;	
	}
	
		var flashvars = {
			url_flv: video+'.flv'
		};	
		var params = {
			bgcolor: "#000000",
			wmode: "transparent"
		};
		var attributes = {
			id: "flashVideo",
			name: "flashVideo"
		};
		swfobject.embedSWF("/components/com_expert/views/elaboration/swf/player.swf", "flashVideo", "340", "227", "8", "expressInstall.swf", flashvars, params, attributes);
}

/*function GMcosy() {
	var flashvars = {};
	var params = {
		wmode: "transparent"
	};
	var attributes = {
		id: "flashCosy",
		name: "flashCosy"
	};
	swfobject.embedSWF("/components/com_product/views/cosy/swf/cosy.swf", "flashCosy", "868", "349", "9.0.0", "expressInstall.swf", flashvars, params, attributes);	
}
*/

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion du preloading pour les pages de home de chaque rubrique 					*/
/* -------------------------------------------------------------------------------------------------------------------- */

/* Modification Xavier : Supression du fadeOut
function clearPreload(){
	$("#preloadMask").fadeOut("slow",function(){
		$(this).remove();
	});
}
*/
function clearPreload(){
	$("#preloadMask").remove();
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion de l'affichage de la liste "select a country" sur la dispatch			*/
/* -------------------------------------------------------------------------------------------------------------------- */

var countrySelect = {
	init:function(){
		if (!$('countryList')) {return}
		$('.firstItem a').click(function(){
			countrySelect.showList($(this));
			return false;
		})
		$('body').click(function(){
			countrySelect.hideList();
		})
	},
	showList:function(arg){
		arg.parent().parent().next().addClass('open');
	},
	hideList:function(){
		setTimeout(function(){$('.open').removeClass('open');},200)
	}
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion de l'affichage des pop in terms and conditions et privacy policy 			*/
/* -------------------------------------------------------------------------------------------------------------------- */
function displayPopin(){
	
	$('.termsAndConditions, #accept a').click(
		function(e){
			if (this.href.indexOf('ajax=true') < 0) {
				this.href += '&ajax=true';
			}
		    $.get(this.href, function(datas) {
		            $('#popinMaskWrapper').css('display', 'block');
		            $('#popinMaskWrapper #popinContentText').empty();
		            $('#popinMaskWrapper #popinContentText').html(datas);
		            addScrollToContainer();

            });
            e.preventDefault();
		}
	);

	$('.popinAge .privacyPolicy').click(function(e){
			if (this.href.indexOf('ajax=true') < 0) {
				this.href += '&ajax=true';
			}
		    $.get(this.href, function(datas) {
		            $('#popinMaskWrapper').css('display', 'block');
		            $('#popinContentText').empty();
		            $('#popinContentText').html(datas);
		            addScrollToContainer();
            });
            e.preventDefault();
		});

	/*
	$('#subMenu li.last a').click(
	    function(e){
            e.preventDefault();
            GM.clickOnLegalConditions = true;
            $.get(this.href + '&ajax=true', function(datas) {
                $('#popinMaskWrapper').css('display', 'block');
                $('#popinContentText').empty();
                $('#popinContentText').html(datas);
                addScrollToContainer();
            });
	    }
	);*/
	
	$('#popin .close, #popin .back').click(
		function(){	
			$('#popinMaskWrapper').css('display', 'none');
			if($('#dispatchPopin')){
				if($('#yearREP')) {$('#yearREP').remove();}
				if($('#monthREP')) {$('#monthREP').remove();}
				if($('#dayREP')) {$('#dayREP').remove();}
				GM.FauxFields.Factory
				({
					context: 'dispatchPopin',
					field: 'select',
					maxHeight: 200
				});
				controlBirth.init();	
			}
			
		}
	);
	
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion du positionnement du footer selon la taille de l'ecran 				*/
/* -------------------------------------------------------------------------------------------------------------------- */
function footerPositioning(){
	
	// Avec FF et IE7 : positionnement du footer par rapport au bottom
	if(typeof document.body.style.maxHeight != 'undefined'){
		var heightScreen = document.body.clientHeight;
		if(document.body.id=='news')var heightImage = 966;
		else var heightImage = 840;
		var posBottom = (heightScreen - heightImage) / 2 ;

		if(posBottom > 0) $('#footer').css('bottom', posBottom);
		else $('#footer').css('bottom', 0);
	}
	// Avec IE6 : positionnement du footer par rapport au top
	/* else {
		if(document.body.id!='news'){
			var heightImage = 840;
			var heightFooter = $('#footer').height()-1;
			var posTop = (heightScreen - heightImage) / 2;
			
			if(posTop > 0) $('#footer').css('top', heightScreen - posTop - heightFooter);
			else  $('#footer').css('top', document.body.scrollTop+(document.body.clientHeight - heightFooter));
		}
	}*/
	
	else{
		if(document.body.id!='news'){
			var heightScreen = document.documentElement.clientHeight;
			var heightImage = 840;
			var heightFooter = $('#footer').height()-1;
			var posTop = (heightScreen - heightImage) / 2;
			
			if(posTop > 0) {
				$('#footer').css('top', heightScreen - posTop - heightFooter- 1) ;
			}
			else if(document.documentElement.scrollTop + heightScreen <= ($('#page').height() + $('#footer').height())){
				$('#footer').css('top', document.documentElement.scrollTop + heightScreen - heightFooter- 1);
			}
			else {
				$('#footer').css('top', heightScreen - heightFooter- 1);
			}
		}
	}
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion du rollover du menu 								*/
/* -------------------------------------------------------------------------------------------------------------------- */
var rollOverMainMenu = {
	init:function(){
		$('#navigation ul li a').hover(
			// Over
			function(){	
				if(!$(this).children('img').hasClass('on')){
					if(typeof document.body.style.maxHeight != 'undefined'){
						var imageName = $(this).children('img').attr('src');
						var newImageName= imageName.replace( /-off/, '-on' );
						$(this).children('img').attr({src : newImageName});
					}
					else{
						var imageName = $(this).children('img').css("filter");
						var newImageName= imageName.replace( /-off/, '-on' );
						$(this).children('img').css("filter", newImageName);
					}
				}
			},
			
			// Out
			function(){
				if(!$(this).children('img').hasClass('on')){
					if(typeof document.body.style.maxHeight != 'undefined'){
						var imageName = $(this).children('img').attr('src');
						var newImageName= imageName.replace( /-on/, '-off' );
						$(this).children('img').attr({src : newImageName});
					}
					else{
						var imageName = $(this).children('img').css("filter");
						var newImageName= imageName.replace( /-on/, '-off' );				
						$(this).children('img').css("filter", newImageName);
					}
				}
			}
		);
	}
}

var rollOverMenuProducts = {
	init:function(){
		$('#cocktailsContent .btnLinks .btnLink .btnLinkCenter a').hover(
			// Over
			function(){	
				if(typeof document.body.style.maxHeight != 'undefined'){
					var imageName = $(this).children('img').attr('src');
					if(imageName.search('_on') > 0){
						var newImageName= imageName.replace( /_on/, '_off' );
						$(this).children('img.menu').attr("src",newImageName);
					}
				}
				else{
					var imageName = $(this).children('img').css("filter");
					if(imageName.search('_on') > 0){
						var newImageName= imageName.replace( /_on/, '_off' );
						$(this).children('img.menu').css("filter", newImageName);
					}
				}
			},
			//Out
			function(){
				if(typeof document.body.style.maxHeight != 'undefined'){
					var imageName = $(this).children('img').attr('src');
					if(imageName.search('_off') > 0){
						var newImageName= imageName.replace( /_off/, '_on' );
						$(this).children('img.menu').attr({src : newImageName});
					}
				}
				else{
					var imageName = $(this).children('img').css("filter");
					if(imageName.search('_off') > 0){
						var newImageName= imageName.replace( /_off/, '_on' );				
						$(this).children('img.menu').css("filter", newImageName);
					}
				}
			}
		);
	}
}


var rollOverMenuExperts = {
	init:function(){
		$('#mainContent #threeExperts ul li a').hover(
			// Over
			function(){	
				if(typeof document.body.style.maxHeight != 'undefined'){
					var imageName = $(this).children('img').attr('src');
					if(imageName.search('-off') > 0){
						var newImageName= imageName.replace( /-off/, '-on' );
						$(this).children('img').attr("src",newImageName);
					}
				}
				else{
					var imageName = $(this).children('img').css("filter");
					if(imageName.search('-off') > 0){
						var newImageName= imageName.replace( /-off/, '-on' );
						$(this).children('img').css("filter", newImageName);
					}
				}
			},
			//Out
			function(){
				if(typeof document.body.style.maxHeight != 'undefined'){
					var imageName = $(this).children('img').attr('src');
					if(imageName.search('-on') > 0){
						var newImageName= imageName.replace( /-on/, '-off' );
						$(this).children('img').attr({src : newImageName});
					}
				}
				else{
					var imageName = $(this).children('img').css("filter");
					if(imageName.search('-on') > 0){
						var newImageName= imageName.replace( /-on/, '-off' );				
						$(this).children('img').css("filter", newImageName);
					}
				}
			}
		);
		
		$('#content #pushContent ul li a').hover(
			// Over
			function(){	
				if(typeof document.body.style.maxHeight != 'undefined'){
					var imageName = $(this).children('img').attr('src');
					if(imageName.search('-off') > 0){
						var newImageName= imageName.replace( /-off/, '-on' );
						$(this).children('img').attr("src",newImageName);
					}
				}
				else{
					var imageName = $(this).children('img').css("filter");
					if(imageName.search('-off') > 0){
						var newImageName= imageName.replace( /-off/, '-on' );
						$(this).children('img').css("filter", newImageName);
					}
				}
			},
			//Out
			function(){
				if(typeof document.body.style.maxHeight != 'undefined'){
					var imageName = $(this).children('img').attr('src');
					if(imageName.search('-on') > 0){
						var newImageName= imageName.replace( /-on/, '-off' );
						$(this).children('img').attr({src : newImageName});
					}
				}
				else{
					var imageName = $(this).children('img').css("filter");
					if(imageName.search('-on') > 0){
						var newImageName= imageName.replace( /-on/, '-off' );				
						$(this).children('img').css("filter", newImageName);
					}
				}
			}
		);
	}
}

var rollOverHome = {

	init:function(){
	    //var lksToRoll = document.getElementById('push').getElementsByTagName('ul')[0].getElementsByTagName('a');
	    var lksToRoll = $('#push > ul a img').parent();
		
	    for(var i=0;i<lksToRoll.length; i++) {
			lksToRoll[i].onmouseover = function(){
				rollOverHome.over(this);
			}
			lksToRoll[i].onmouseout = function(){
				rollOverHome.out(this);
			}
		}
	},
	over:function(arg){
		var imgSrc = arg.getElementsByTagName('img')[0].src;
		var imgSrcIE = arg.getElementsByTagName('img')[0];
		if (imgSrc.indexOf('-on') < 0) {
			arg.getElementsByTagName('img')[0].src = arg.getElementsByTagName('img')[0].src.replace('.png', '-on.png');
			if(imgSrcIE.style.filter){
				var imgFilter = imgSrcIE.style.filter.replace('.png','-on.png');
				imgSrcIE.style.filter = imgFilter;				
			}
		}
	},
	out:function(arg){
		var imgSrc = arg.getElementsByTagName('img')[0].src;
		var imgSrcIE = arg.getElementsByTagName('img')[0];
		if (imgSrc.indexOf('-on') >= 0) {
			arg.getElementsByTagName('img')[0].src = arg.getElementsByTagName('img')[0].src.replace('-on.png','.png');		
		}		
		if(imgSrcIE.style.filter && imgSrcIE.style.filter.indexOf('-on') >= 0){
			var imgFilter = imgSrcIE.style.filter.replace('-on.png','.png');
			imgSrcIE.style.filter = imgFilter;				
		}			
	}
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion du rollover/rollout des vignettes dans la home de genuine 				*/
/* -------------------------------------------------------------------------------------------------------------------- */
var rollOverHomeGenuine = {
	init : function(){
		$('#frame li').hover(
			// Over
			function(){
				if(!$(this).hasClass('on')){
					$(this).children('h2').children('img.frame').removeClass('hideframe');
					$(this).addClass('on');
				}
			},
			
			// Out
			function(){
				$(this).children('h2').children('img.frame').addClass('hideframe');
				$(this).removeClass('on');
			}
		);
	}
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion du rollover/rollout des vignettes dans la home de secrets 				*/
/* -------------------------------------------------------------------------------------------------------------------- */
var rollOverHomeSecret = {
	init : function(){
		$('#pushContent li a').hover(
			// Over
			function(){
				if(!$(this).hasClass('on')){
					$(this).children('img.frame').removeClass('hideframe');
					$(this).addClass('on');
				}
			},
			
			// Out
			function(){
				$(this).children('img.frame').addClass('hideframe');
				$(this).removeClass('on');
			}
		);
	}
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion de l'affichage des popins experts			 					*/
/* -------------------------------------------------------------------------------------------------------------------- */
function  displayExpertPopin(){
	// Gere l'affichage des reponses
	$('#threeExperts a').click(	
	
		function(){
			var htmlHeight = document.documentElement.scrollHeight;
			$('#expertPopinMaskWrapper').css({ left: "0", height: htmlHeight+"px"});
			$('#expertPopin .'+ $(this).attr('class')).css({ left: "0"});

		}
	);
	$('#expertPopinMaskWrapper .close').click(
		function(){
			$('#expertPopinMaskWrapper').css({ left: "-99999px"});
			$('#expertPopin .expert01, #expertPopin .expert02, #expertPopin .expert03').css({ left:"-999999px"});
		}
	);
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion de l'affichage des bouteilles limited editions		 					*/
/* -------------------------------------------------------------------------------------------------------------------- */
function  displayBottle(){
	// Gere l'affichage des reponses
	$('#sideContent ul a').click(
		function(){
			var year = $(this).attr('class');
			$('#mainContent .current').removeClass('current');
			$('#mainContent .' + year).addClass('current');
			$('#mainContent .bottle').attr("src", '/images/product/limited_editions/bottle' + year + '.png');
			if (typeof document.body.style.maxHeight == 'undefined') {
				for( var i= 0, els= $('#mainContent h2 .png'), elsLen= els.size(); i< elsLen; i++ ) {
					var el= els.get(i);
					el.style.background= 'none';
					el.style.filter= 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + el.src + '", sizingMethod="image")';
					el.src= '/templates/general/img/px.gif';
				}
			}
		}
	);
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion de l'affichage de la FAQ dans la page contact 					*/
/* -------------------------------------------------------------------------------------------------------------------- */
function  displayAnswer(){
	// Gere l'affichage des reponses
	$('#accordionFAQ .contentWrapper a').click(
		function(){
			// Si le bloc n'est pas ouvert on l'ouvre
			if($(this).parent().children('.answer').css('display')=="none"){
				// On ferme d'abord toutes les reponses eventuellement ouvertes
				$('.answer').css({ display: "none"});
				// On ouvre la reponse
				$(this).parent().children('.answer').css({ display: "block"});
			}
			// Sinon on le ferme
			else{
				$(this).parent().children('.answer').css({ display: "none"});
			}
			
			// Et on recalcule la taille du scroll
			$(this).parent().parent().parent('.scroll').each(function(){
				var id = BOX.getStoreId(this);
				scrollsCache[id].compute();
			});
		}
	);
	
	// Gere l'affiche les blocs de questions
	$("#accordionFAQ .title").click(
		function() {
			if($(this).next().css("display") == 'none'){
				// On ferme le bloc courant ouvert
				$(this).parent().parent().children().children(".contentWrapper").slideUp("slow");
				$(this).parent().parent().children().children(".title").removeClass("on").addClass("off");
				
				// On ouvre le bloc selectionne
				$(this).next().slideDown("slow");
				$(this).removeClass("off").addClass("on");
			}
		}
	).next().hide();
	
	// Par default la premiere rubrique est ouverte
	$("#accordionFAQ .on").next().slideDown("slow");
	
	
	$("#accordionFAQ2 .title").click(
		function() {
			if($(this).next().css("display") == 'none'){
				// On ferme le bloc courant ouvert
				$(this).parent().parent().children().children("#wrapperFormMessage").slideUp("slow");
				$(this).parent().parent().children().children(".title").removeClass("on").addClass("off");
				
				// On ouvre le bloc selectionne
				$(this).next().slideDown("slow");
				$(this).removeClass("off").addClass("on");
				
				$(this).parent().children().children().children('.scroll').each(function(){
					var id = BOX.getStoreId(this);
					scrollsCache[id].compute();
				});
			}
		}
	).next().hide();
	
	// Par default la premiere rubrique est ouverte
	$("#accordionFAQ2 .on").next().slideDown("slow");
	
	// Gere la mise a jour des topics
	$("#country").change(
	function() {
		$.ajax({
			type: "GET",
			url: '/index.php?option=com_faq&view=faq&display=topics&country_id='+this.value,
			success: function(retour) {
				$("topicSelect").html('');
				var t = '';
				t += '<select id="topic" name="topic_id" >';
				t += retour;
				t += '</select>';
				$("#topicSelect").html(t);
				GM.FauxFields.Factory
				({
					context: 'topicSelect',
					field: 'select',
					maxHeight: 120
				});
				
				return;
			},
			dataType: "html"
		});
		return false;
	}
	);
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion de l'affichage de l'accordeon de liens 					*/
/* -------------------------------------------------------------------------------------------------------------------- */
function  displayLinks(){
	// Gere l'affiche les blocs de liens
	$("#accordionLinks .title").click(function() {
		if($(this).next().css("display") == 'none'){
			// On ferme le bloc courant ouvert
			$(this.parentNode.parentNode)
				.find("div.contentWrapper").slideUp("slow")
				.end()
				.find("div.title").removeClass("on").addClass("off");
			
			// On ouvre le bloc selectionne
			$(this).next().slideDown("slow");
			$(this).removeClass("off").addClass("on");
			$(this).parent().find("div.scroll").each(function(){
				var id = BOX.getStoreId(this);
				scrollsCache[id].compute();
			});
		}
		return false;
	}).next().hide();
	
	// Par default la premiere rubrique est ouverte
	$("#accordionLinks .on").next().slideDown("slow");
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion de l'affichage de l'accordeon de produits de la page Gamme 					*/
/* -------------------------------------------------------------------------------------------------------------------- */
function  displayAccordionProducts() {
    $("#ssnavigation .level1 a").click(function() {
        
        if ($(this).parent().attr('id') == "extract") {
            $(".accordion").removeClass("on").addClass("off");
            $("#accordionExtract").removeClass("off").addClass("on");
			$("#accordionExtract").children('div:first').find('.title').click();
        } 
        if ($(this).parent().attr('id') == "liqueur") {
            $(".accordion").removeClass("on").addClass("off");
            $("#accordionLiqueurs").removeClass("off").addClass("on");
			$("#accordionLiqueurs").children('div:first').find('.title').click();
        }
        
        // All tabs off
        $("#ssnavigation .level1 a").removeClass("on").addClass("off");
        $("#ssnavigation .level1 a").each(function() {
            var imageName = $(this).find('> img').attr('src');
            var newImageName = imageName.replace( /-on/, '-off' );
            $(this).find('> img').attr({src : newImageName});
        });
        // Clicked tab on
        $(this).removeClass("off").addClass("on");
        var imageName = $(this).find('> img').attr('src');
        var newImageName = imageName.replace( /-off/, '-on' ).replace( /-over/, '-on' );
        $(this).find('> img').attr({src : newImageName});
            
        // @affected : ie6
		if (isIE6) {
		    
		    // All tabs off
            $("#ssnavigation .level1 a").each(function() {
                var imageName = $(this).find('> img').css("filter");
                var newImageName = imageName.replace( /-on/, '-off' );
                $(this).find('> img').css("filter", newImageName);
            });
            // All tabs on
            var imageName = $(this).children('img').css("filter");
            var newImageName = imageName.replace( /-off/, '-on' ).replace( /-over/, '-on' );
            $(this).children('img').css("filter", newImageName);
		}
        return false;
		
    });
    $("#ssnavigation .level1 a").hover(function() {
        var imageName = $(this).find('> img').attr('src');
        var newImageName = imageName.replace( /-off/, '-over' );
        $(this).find('> img').attr({src : newImageName});
        // @affected : ie6
        if (isIE6) {
            var imageName = $(this).children('img').css("filter");
            var newImageName = imageName.replace( /-off/, '-over');
            $(this).children('img').css("filter", newImageName);
        }
    }, 
    function() {
        var imageName = $(this).find('> img').attr('src');
        var newImageName = imageName.replace( /-over/, '-off' );
        $(this).find('> img').attr({src : newImageName});
        // @affected : ie6
        if (isIE6) {
            var imageName = $(this).children('img').css("filter");
            var newImageName = imageName.replace( /-over/, '-off');
            $(this).children('img').css("filter", newImageName);
        }
    });
    
	// Gere l'affiche les blocs 
	$(".accordion .title").click(function() {
	    var that = this;
		if($(that).next().css("display") == 'none'){
			// On ferme le bloc courant ouvert
			$(that.parentNode.parentNode)
				.find("div.contentWrapper").slideUp("slow")
				.end()
				.find("h2.title").removeClass("on").addClass("off");
			
			// On ouvre le bloc selectionne
			$(that).next().slideDown("slow", function() {
			    $(that).parent().find("div.scroll").each(function(){
    				var id = BOX.getStoreId(this);
    				scrollsCache[id].compute();
    			});
			});
			$(that).removeClass("off").addClass("on");
		}
		return false;
	}).next().hide();
	
	// Open the appropriate tab and accordion according to the param (Ex: #liqueur01)
    var paramProduit = String( window.location ).split('#')[1];
	if (paramProduit == undefined){
		paramProduit = $("#ssnavigation").next().children()[0].id;
	}
    if (paramProduit != undefined) {
        // All Tabs off
        $("#ssnavigation .level1 a").each(function() {
            var imageName = $(this).find('> img').attr('src');
            var newImageName = imageName.replace( /-on/, '-off' );
            $(this).find('> img').attr({src : newImageName});
        });
        if ($("#accordionLiqueurs #" + paramProduit).length > 0) {
            $("#accordionLiqueurs").removeClass("off").addClass("on");
            $("#liqueur a").removeClass("off").addClass("on");
            $("#accordionExtract").removeClass("on").addClass("off");
            $("#extract a").removeClass("on").addClass("off");
            
            // Tab on
            var imageName = $("#liqueur a").find('> img').attr('src');
            var newImageName = imageName.replace( /-off/, '-on' );
            $("#liqueur a").find('> img').attr({src : newImageName});
            
        }
        if ($("#accordionExtract #" + paramProduit).length > 0) {
            $("#accordionLiqueurs").removeClass("on").addClass("off");
            $("#liqueur a").removeClass("on").addClass("off");
            $("#accordionExtract").removeClass("off").addClass("on");
            $("#extract a").removeClass("off").addClass("on");
            
            // Clicked tab on
            var imageName = $("#extract a").find('> img').attr('src');
            var newImageName = imageName.replace( /-off/, '-on' );
            $("#extract a").find('> img').attr({src : newImageName});
        }
        $(".accordion h2").removeClass("on").addClass("off");
        $(".accordion #" + paramProduit + " h2").removeClass("off").addClass("on");
    }
    $(".accordion .on").next().slideDown("slow");
    
}




/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion de l'affichage de l'image avec la class reflect dans news/promotions				*/
/* -------------------------------------------------------------------------------------------------------------------- */
function positionImgFocus(){
	var Focus = document.getElementById('focus');
	var hImg = Focus.getElementsByTagName('img')[0];
	if(hImg!=null){
		var result = 297-hImg.height;
		var divR = Focus.getElementsByTagName('div')[0];
		divR.style.top=result+'px';
		divR.style.position='absolute';
		hImg.style.marginBottom=7+'px';
	}
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Gestion formulaire de la popin dispatch				*/
/* -------------------------------------------------------------------------------------------------------------------- */
var controlBirth = {
	init : function(){
		$('#dispatchPopin #submit').click(function(){
			var year = $('#year').val();
			var month = $('#month').val();
			var day  = $('#day').val();
			controlBirth.showMonthDay();
			$('p.error').remove();
			if( year == '' ){
				$('fieldset.birthdate fieldset').append('<p class="error">'+l10n.generic.formAgeIncomplete+'</p>').addClass('highlight');
				return false;
			/*} else if(year != '' && month == '' || day == '' && controlBirth.equalYear()){
				console.log('equal');
				$('div.action').append('<p class="error">'+l10n.generic.formAgeIncomplete+'</p>');
				return false;*/
			} else {
				controlBirth.checkAge(year,month,day);
				return false;
			}
		});
		$('#questpopin .step1 a').click(function(){
			document.location.href=this.href;
		});
		$('#year').change(function(){
			controlBirth.showMonthDay();
		});
	},
	checkAge : function(y,m,d){
		var ok = 0;
		var date = new Date();
		var thisY = date.getFullYear();
		var a = thisY - y;
		var l = $('#age').val();
		if (a < l) { 
			ok = 0;	//ok++	
		} else if (a == l){
			if(m == '' || d =='') {
				$('fieldset.birthdate fieldset').append('<p class="error">'+l10n.generic.formAgeIncomplete+'</p>').addClass('highlight');
				return false;
			}
			var thisM = date.getMonth() + 1;
			if ( thisM > m  ) { //if ( thisM < m  ) {
				ok++;
			}
		 
			if ( thisM == m ) {
				var thisD = date.getDate();
				if ( thisD >= d ) {
					ok++;	
				}
			}
		} else if (a > l){
			ok++;
		}
		
		if(ok==0){ //if(ok!=0){
			$('fieldset.birthdate fieldset').append('<p class="error">'+l10n.generic.tooYoung+'</p>').addClass('highlight');
			return false;
		} else {
			$('#dispatchPopin').submit();
		}
	},
	equalYear : function(){
		var d = new Date();
		var age = d.getFullYear() - $('#year').val();
		var agerequired = $('#age').val();
		if(age ==agerequired){ //if(age >=agerequired){
		
			if($.browser.msie){
			//var test = $('.selectAge .select:first-child');
			//alert(test);
			$('.selectAge .select:first-child').css("left","90px");
				if ($('.selectAge .select:first-child').hasClass('selectYear')){
					$('.selectYear').css("left","85px");
				}
			$('.selectAge .select:nth-child(2)').css("left","165px");
			$('.selectAge .select:nth-child(3)').css("left","260px");
			}
			
			return true;
		} else {
			return false;	
		}
	},
	showMonthDay : function(){
		if($('html').attr("lang") != "fr-fr") {
			$('#month').parent().addClass('off').css("left","-10000px");
			$('#day').parent().addClass('off').css("left","-10000px");	
			
			if(($.browser.msie) && ($('html').attr("lang") != "fr-fr")){
				$('.selectAge .select:nth-child(1)').css("left","185px");
			}
			
			if(controlBirth.equalYear()){
				$('#month').parent().removeClass('off').css("left","165px");
				$('#day').parent().removeClass('off').css("left","260px");	
			}
		}
	}
}

/* -------------------------------------------------------------------------------------------------------------------- */
/* Global Events manager									*/
/* -------------------------------------------------------------------------------------------------------------------- */

$(document).ready(
	function() {
	
	if(!document.getElementById("#questpopinMaskWrapper")){
		$("#questpopinMaskWrapper").css("display","block");
	}
	
	var isIE7 = false;	
	var strChUserAgent = navigator.userAgent;
	var intSplitStart = strChUserAgent.indexOf("(",0);
	var intSplitEnd = strChUserAgent.indexOf(")",0);
	var strChStart = strChUserAgent.substring(0,intSplitStart);
	var strChMid = strChUserAgent.substring(intSplitStart, intSplitEnd);
	var strChEnd = strChUserAgent.substring(strChEnd); 
	
	if(strChMid.indexOf("MSIE 7") != -1)
	isIE7 = true; 
	
	if(($.browser.msie) && ($('html').attr("lang") != "fr-fr")){
		$('.selectAge .select:nth-child(1)').css("left","185px");
	}
	
	
	//if(isIE6 || isIE7){
	if(($.browser.msie) && ($('html').attr("lang") == "fr-fr")){
		//var test = $('.selectAge .select:first-child');
		$('.selectAge .select:first-child').css("left","90px");
			if ($('.selectAge .select:first-child').hasClass('selectYear')){
				$('.selectYear').css("left","85px");
			}
		$('.selectAge .select:nth-child(2)').css("left","165px");
		$('.selectAge .select:nth-child(3)').css("left","260px");
	}
		// Pour ne pas avoir de loading en cas de javascript desactive
		if($('body').hasClass('home')){
			$('html').attr('id', 'js');
		}
		if($('#dispatchPopin')){
			GM.FauxFields.Factory
			({
				context: 'dispatchPopin',
				field: 'select',
				maxHeight: 200
			});
		controlBirth.init();	
	};
		
		// Positionnement du footer
		footerPositioning();
		$(window).resize(footerPositioning).scroll(footerPositioning);
	
		// Creation d'un scroll si besoin
		if ($('body').hasClass('hasScroll')) {
			addScrollToContainer();
		}
		if ($('body').hasClass('home')) {
			//addScrollToContainer();
		}
		
		if(document.getElementById('accordionLiqueurs')){
			addScrollToContainer('#accordionLiqueurs');
		}
		if(document.getElementById('accordionExtract')){
			addScrollToContainer('#accordionExtract');
		}
        

		// Initialisation du rollover/rollout du menu principal
		rollOverMainMenu.init();
		
		// Initialisation des popin de terms and conditions et privacy policy
		displayPopin();
		
		// Initialisation du contenu du formulaire de newsletter (vide le contenu au clic)
		if ($('#newsletterForm').length > 0)
		{
            if ($('#newsletterForm .text input').val() == '') {
                $('#newsletterForm .text input').val(l10n['generic']['newsletterRegistrationLabel']);
            }
            $('#newsletterForm .text input').focus( function(){
                if ($(this).val() == l10n['generic']['newsletterRegistrationLabel']) {
                    $(this).val('');
                }
            }); 
	    }

        // Inscription à la newsletter
	    $('#newsletterForm').submit(function(){
	        // Verifie la validite de l'email
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (!filter.test($('#newsletterForm .text input').val())) {
				$('#popinNewsletterMaskWrapper').css('display', 'block'); 
               	$('#popinNewsletterMaskWrapper #popinContent p').empty();
				$('#popinNewsletterMaskWrapper #popinContent p').append(l10n['generic']['newsletterEmailInvalid']);
				$('#popinNewsletterMaskWrapper .close').focus();
				$('#popinNewsletterMaskWrapper .close').click(function(){
	                $('#newsletterForm .text input').focus();
				});
                return false;
            }

            var urlvar = new Array();
            urlvar['email'] = $('#newsletterForm .text input').val(); 
            /*urlvar['option'] = 'com_newsletter';
            urlvar['task'] = 'subscribe';
            urlvar['template'] = 'system';
            urlvar['pro'] = '1';*/
            
	    	$.post( '/index.php?option=com_newsletter&task=subscribe&template=system&email=' + urlvar['email'] ,  urlvar,
                function(data){
                	$('#popinNewsletterMaskWrapper').css('display', 'block'); 
                	$('#popinNewsletterMaskWrapper #popinContent p').empty();
                	if (data == 1) {
						$('#popinNewsletterMaskWrapper #popinContent p').append(l10n['generic']['newsletterRegistrationOK']);
                	} else {
                		$('#popinNewsletterMaskWrapper #popinContent p').append(l10n['generic']['newsletterRegistrationKO']);
                	}
					$('#popinNewsletterMaskWrapper .close').focus();
                	$('#newsletterForm .text input').val(l10n['generic']['newsletterRegistrationLabel']);
                }
                
	        );
	    	
	    	return false;
	    });
	    
	    // Fermeture de la popin newsletter
    	$('#popinNewsletterMaskWrapper .close').click(
    		function(){	
    			$('#popinNewsletterMaskWrapper').css('display', 'none');
    		}
    	);
    	

    	
		// Ajout du select du choix du pays dans le footer
		
		/*GM.FauxFields.Factory
		({
			context: 'footerContent',
			field: 'select',
			maxHeight: 200
		});*/
		
		//liens externes
		$('.externalLink').click(function() { 
			var isLoaded;
			window.open(this,'external');
			isLoaded = true;
			return false;
		} );

		// Dispatch
		/*if(document.body.id=='dispatch'){
			var dispatchSelects = GM.FauxFields.Factory
			({
				context: 'page',
				field: 'select',
				maxHeight: 120
			});
			dispatchSelects.collection.country.update(dispatchSelects.collection.country.items[0]);
			
			$('#validate').click(function(){
				formValidation.submission();
				return false;
			});
			
			countrySelect.init();
			
			
			$("#footerContent").ajaxSuccess(function(request, settings){
			    if (!GM.clickOnLegalConditions) {
    				if(isIE6){
    					PNGKiller('footerContent');
    				}
			    } else {
			        GM.clickOnLegalConditions = false;
			    }
			});
		}*/
			
		// Home
		if(document.body.id=='home'){
			rollOverHome.init();
			countrySelect.init();
			/* Modification Xavier : Je deplace GManimBottle() dans window.onload*/
			/*if (evin==0) GManimBottle();*/
			/*Fin Modification Xavier*/
			
		}	

		// Genuine
		else if(document.body.id=='genuine'){
			if($('body').hasClass('home')){
				rollOverHomeGenuine.init();
			}
			else if(document.getElementById('infoGenuineMomentPart1')){
				GM.FauxFields.Factory
				({
					context: 'infoGenuineMomentPart2',
					field: 'select',
					maxHeight: 120
					
				});
				GM.FauxFields.Factory
				({
					context: 'accept',
					field: 'checkbox'
				});
				shareMyGenuineMoment.init();
			} 
			else if(document.getElementById('languageGenuineMomentList')){
				GM.FauxFields.Factory
				({
					context: 'momentListWrapper',
					field: 'select',
					maxHeight: 200
				});
			}
			if(document.getElementById('formContainer')){
				shareMyGenuineMoment.init();	
			}
			countrySelect.init();
		}

		// Cocktails
		else if(document.body.id=='cocktails'){
			//impression Cocktails
			var Pprint = "height=550,width=650,toolbar=no, menubar=no, location=no, resizable=no, scrollbars=yes, status=no";
			$("#cockailSheetFrame").ajaxSuccess(function(request, settings){
				$('.print').click(function() { 
					window.open(this,'print',Pprint);
					return false;
				} );
			});
			
			$('.print').click(function() { 
				window.open(this,'print',Pprint);
				return false;
			} );
			
			if($('body').hasClass('home')){
				getCocktails.init();
				updateCaroussel.init();
				rollOverCocktail.init();
				rollOverMenuProducts.init();
				
				$('#ssnavigation ul.level2 li a').click(function(){
					$('#ssnavigation ul.level2 li a').removeClass('selected');
					$(this).addClass('selected');
				 });
				$('#ssnavigation ul.level1 li.level1').click(function(){
					$('#ssnavigation ul.level2 li a').removeClass('selected');
				 });
			}
			else{
				updateCocktailSheet.init();
				sendToAFriend.init();
				GM.FauxFields.Factory
				({
					context: 'sendPopin',
					field: 'checkbox'
				});
			}
			countrySelect.init();
		}		
		
		// Secrets
		else if(document.body.id=='secrets'){	
			if($('body').hasClass('home')){
				rollOverHomeSecret.init();
				
				rollOverMenuExperts.init();
				displayExpertPopin();
			}
			countrySelect.init();
			if( $('input').length > 0 ) {
				GM.FauxFields.Factory
				({
				context: 'quizz',
				field: 'radio'
				});
			}
			if($('body').hasClass('elaboration')){
				/*var Simg = $('span.on img').eq(1).attr("src").toLowerCase();
				if(Simg.indexOf('cognacs') >= 0){
					video = 'cognacs';
				} else if(Simg.indexOf('oranges') >= 0){
					video = 'oranges';
				} else if(Simg.indexOf('recipe') >= 0){
					video = 'recette';
				} else if(Simg.indexOf('bottling') >= 0){
					video = 'bottling';
				}*/
				
				GMvideo(0);
				updateElaborationSheet.init();
		  	}	
			if($('body').hasClass('expertAnswerQuestion')){		
				addScrollToContainer();
			}
			if($('body').hasClass('answerQuestion')){
				updateAnswerSheet.init();
			}
		}

		// Products
		else if(document.body.id=='products'){		
			countrySelect.init();
			if ($('body').hasClass('home')) {
				addScrollToContainer('#sideContent');
			}
			if (document.getElementById('flashCosy')) {
				GMcosy();
			}
			if($('body').hasClass('limitedCollection')){
				displayBottle();
			}
			if($('body').hasClass('productDetail')){
				updateProductSheet.init();
			}

			if($('body').hasClass('productAvailability')){
				var productSelects = GM.FauxFields.Factory
				({
					context: 'selectContent',
					field: 'select',
					maxHeight: 200
				});
				
				productSelects.collection.country.addListener('change', function() {
					if(this.lastIndex) {
						productSelects.collection.product.update(productSelects.collection.product.items[0]);
					}
				});
				
				productSelects.collection.product.addListener('change', function() {
					if(this.lastIndex) {
						productSelects.collection.country.update(productSelects.collection.country.items[0]);
					}
				});
			}
			if (document.getElementById('accordionLiqueurs')) {
				displayAccordionProducts();
			}
		}
        // News
		else if(document.body.id == 'news'){

            if ($('#newsBlock .newsList').length > 0) { // PRO
                
                $('#popinNews .close, #popinNews .back').click (
                	function(){	
                		$('#popinNewsMaskWrapper').css('display', 'none');
                	}
                );
                
                $('.newsList a.openPopin').click (
                	function(){	
                		var newsId = $(this).attr('class').split('newsId[')[1].replace(']','');
            	    	$.post('/index.php?option=com_newspro&view=details&template=system&id=' + newsId,
                            function(data){                        
                                $('#popinNewsMaskWrapper').css('display', 'block');
                	            $('#popinNewsContent').empty();
						        $('#popinNewsContent').append(data);
                                addScrollToContainer($('#popinNewsContent'));
                            }
            	        );
                	}
                );
            } else { // NOT PRO
    			/*if ($('body').hasClass('home')) {
    				addScrollToContainer();
    			}   */             
            }

		}
		
		// Adverts
		else if(document.body.id=='advertising') {
			updateAdvertSheet.init();
			countrySelect.init();
		}

		// Contact
		else if(document.getElementById('contact')){
			countrySelect.init();
			addScrollToContainer("#faq");
			addScrollToContainer("#message");
			displayAnswer();
			GM.FauxFields.Factory
			({
				context: 'formMessage',
				field: 'select',
				maxHeight: 200
			});
			GM.FauxFields.Factory
				({
				context: 'formMessage',
				field: 'radio'
			});
            formMessage.validation();
		} 		
		
		// Links
		else if(document.getElementById('links')){
			displayLinks();
			countrySelect.init();
		}

		
		if(document.getElementById('popinJob')) {
    		GM.FauxFields.Factory
    		({
    			context: 'jobForm',
    			field: 'select',
    			maxHeight: 200
    		});
	    }
	    
	    // Gestion des evenements lors du choix de job dans la popin job de la home pro
	    if ($('#jobForm').length > 0) {

	    	$('#jobForm #job').change(function(){	    		
	    		if ($('#jobForm #job').val() != '') {
	    			$('#jobForm').submit();
	    		}
	    	});

	    	$('#jobForm').submit(function(){
	    		$('.popinJobWrapper').removeClass('popinJobWrapper').addClass('popinJobWrapperHidden');
	    	});
	    }
	}	
);

//Validation du formulaire contact

var formMessage = {

    validation : function() {
        $('#formMessage .submitInput').click(function () {
            var list= new Array();
            if(!$('#email').attr('value') || !validEmail($('#email').attr('value'))){
                list.push('email');
            }
            if(!$('#country').attr('value')){
                list.push('country');
            }
            if(!$('#topic').attr('value')){
                list.push('topic');
            }
            if(document.getElementById('formMessage').message.value == ''){
                list.push('message2');
            }
            if (!$('#accordionFAQ2').length) {
                //version pro
                if(!$('#profile').attr('value')){
                    list.push('profile');
                }
            }
            if(list.length>0){
                warningLabels(list);
                $('.alert').html(l10n.generic.formIncomplete);                
                return false;
            } else {
                formMessage.sendDatas();
                return false;
            }
        });
    },
    
    sendDatas : function() {
        var formAction = $('#formMessage').attr('action');
        var country = $('#country').attr('value');
        var topic = $('#topic').attr('value');
        var message = document.getElementById('formMessage').message.value;
        var email = $('#email').attr('value');
        if ($('#accordionFAQ2').length) {
            //version grand public
            $.post(formAction,{email: email, country_id: country, topic_id: topic, message: message},formMessage.display);
        } else {
            //version pro
            var profile = $('#profile').attr('value');
            $.post(formAction,{email: email, country_id: country, topic_id: topic, message: message, profile_id: profile},formMessage.display);
        }
    },
    
    display : function(cnt) {
        if ($('#accordionFAQ2').length) {
            //version grand public
            $('#formMessage').parent().parent().hide();
            $('#accordionFAQ2 .content').append(cnt);
        } else {
            //version pro
            $('#formMessage').hide();
            $('#wrapperFormMessage').append(cnt);
        }
    }
}

// gestion des erreur de chargement de fichiers, qui bloquent la disparition du mask de loading
GM.isLoadedCorectly = false;
setTimeout(function(){
	//alert("force hide ! --> "+GM.isLoadedCorectly);
	if(GM.isLoadedCorectly==false){
		
		// Fade out du loading
		if ($('body').hasClass('home')) {
			clearPreload();
		}
		// Home
		if (document.body.id == 'home') {
			if(document.getElementById('focus')){
				addReflections('focus',0.5);
				if(!document.getElementById('mainPushWrapper2')){
					positionImgFocus();
				}
			} else {
				addReflections();
			}
		}
	}
},10000);	

window.onload = function(){
	GM.isLoadedCorectly = true;
	
	// Fade out du loading
	if ($('body').hasClass('home')) {
		/* Modification Xavier : Supression du setTimeout()
		setTimeout('clearPreload()',1000);
		*/
		clearPreload();
		/* FIN Modification Xavier*/
	}
	
	// Home
	if (document.body.id == 'home') {
		/* Modification Xavier : Supression du setTimeout()*/
		if (evin==0) GManimBottle();
		/* FIN Modification Xavier*/
		if(document.getElementById('focus')){
			addReflections('focus',0.5);
			if(!document.getElementById('mainPushWrapper2')){
				positionImgFocus();
			}
		} else {
			addReflections();
		}
	}

}

function showPopin()
    {
        document.getElementById('popIn').className="blockon";
		document.body.className = "home productDetail windowObscur";
	}
function closePopin()
    {
        document.getElementById('popIn').className="blockoff";
		document.body.className = "home productDetail";
    }
	
	
	
var scriptsProductsCollection = {
	init: function () {
	
		// ouverture popup
		$('.popin').click(function () {
			if($(this).attr('href')) {
			window.open($(this).attr('href'),'pop','width=1024,height=800,toolbar=1,menubar=1,location=1,status=1,scrollbars=1,resizable=1,directories=1');
			return false;
		}});
		
		// Popin
		$("#closePopin").click(function(){
			$("#popIn").hide();
			$("#overlay").hide();
			return false;
		});
		/*
		$(window).resize(function(){
			scriptsProductsCollection.setPopinPosition();
		});
		$(window).resize();*/

		// Terms
		scriptsProductsCollection.managePopin();
		$('body').ajaxComplete(function(event,request, settings){
			scriptsProductsCollection.managePopin();
		});

		
		$("#popIn").hide();
	},
	managePopin: function () {
		$("a[href$=#visual]").unbind('click');
		$("a[href$=#visual]").click(function(){
			var imageOk = false;
			if ( $.browser.msie ) {
				if(jQuery.browser.version == '6.0') {
					var test = $(this).find('.visuPopin img').css('filter');
					test = test.split('src=');
					test = test[test.length-1];
					test = test.split('", ');
					test = test[0];
				} else {
					var test = document.getElementById("imagePopin").src;
				}
			} else {
				var test = $(this).find('.visuPopin img').attr('src');	
			}
			if((test.indexOf(".jpg") > -1) || (test.indexOf(".jpeg") > -1) || (test.indexOf(".gif") > -1) || (test.indexOf(".png") > -1)) {
				imageOk = true;
			}
			if(imageOk){
				
				if($('.windowObscur').length == 0) {
					$('body').append('<div class="windowObscur"></div>');
				}
				if($('.popinContainer').length == 0) {
					$('body').append('<div class="popinContainer"></div>');
				}
				$('.popinContainer').empty();
				
				var image = $(this).find('.visuPopin').html();
				$('.popinContainer').append('<a href="#" class="closePopin">'+image+'</a>');
				
				var imageWidth = $('.visuPopin img').width();
				var imageHeight = $('.visuPopin img').height();
				var borderWidth = 6;
				
				$('.popinContainer').append('<div class="popinBackground"></div>');
				var backgroundWidth = imageWidth+(borderWidth*2);
				var backgroundHeight = imageHeight+(borderWidth*2);
				$('.popinBackground').css({
					'width': backgroundWidth +'px',
					'height':backgroundHeight+'px'
				});
				
				var marginLeftPopin = -((imageWidth/2)+borderWidth);
				var marginTopPopin = -((imageHeight/2)+borderWidth);
				$('.popinContainer').css('margin-left', marginLeftPopin+'px');
				$('.popinContainer').css('margin-top', marginTopPopin+'px');
				$('.popinContainer a').css({
					'left':borderWidth+'px',
					'top':borderWidth+'px'
				});
				
				
				$('.popinContainer .closePopin').click(function () {
					$('.windowObscur, .popinContainer').remove();
					return false;
				});
				
			}
			return false;
		});
	},
	setPopinPosition: function(){
		var popins = ["popIn"];
		for(var i = 0; i < popins.length; i++){
			var popin = popins[i];
			
			var x = ($(window).width() - $("#"+popin).width() ) / 2;
			$("#"+popin).css("left", x+"px");
		}
	}
}
$(document).ready(
	scriptsProductsCollection.init
);

function xitiNext() {
	if (document.getElementById("xNext")==null){
		var elt = document.getElementById("next");
		var bal = document.createElement("noscript");
		var img = document.createElement("img");
		elt = elt.appendChild(bal);
		elt = elt.appendChild(img);
		elt.id="xNext";
		elt.src="tag page accueil";
		elt.width="1"; elt.height="1";
	} else {
		document.getElementById("xNext").src="tag suivant";
	}
}

function xitiPrev(xprod) {
	
	//alert(xprod);
	if (document.getElementById("xPrev")==null){
		var elt = document.getElementById("prev");
		var bal = document.createElement("noscript");
		var img = document.createElement("img");
		elt = elt.appendChild(bal);
		elt = elt.appendChild(img);
		elt.id="xPrev";
		elt.src="tag page accueil";
		elt.width="1"; elt.height="1";
	} else {
		document.getElementById("xNext").src="tag precedent";
	}
}






















