var isHover = 0;
var select = 0;

//on attend que la page soit chargée
$(document).ready(function()
{ 
	launchDefile();
	$('#atouts_dejelin li').hover(function()
		{
			clearInterval(timeratout);
		},function()
		{
			launchDefile();
		});
		
	sousMenu()
	sousMenuFix();
	search();
	logoHovers();
	styleTags();
	// fancyboxProductAjax();
	AjaxFancyboxProduct();
	galerieProductAjax();
	$('.product_image img.zoomit').wow({'effect':'inOut'});
	targetBlankFacebook();
	labelDelivery();
	filtreRegion();
	// swfImplements();
	if ($('#player').length > 0) flowplayer("player", "http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf", 
	{clip : {autoPlay: false, autoBuffering: true } }); 
		/* js/flowplayer-3.2.7.swf pour akitourne */
	accordeon();
	$('#search_faq_input').emptyFields();
});
	
	

// on attend que la page soit chargée
$(window).load(function()
{
	heightCols(); // uniforme les tailles de colonnes
	smoothScroll($("#panierscroll"),$('#content_right'),$('#content_left'),300,100); // permet de translater le panier e-commerce sur la droite
});

function accordeon()
{
	$('.accordeon h3 a').live('click', function()
	{
	    var onglet = $(this).parents('.accordeon_content').find('.accordeon_onglet');
	    if (!onglet.hasClass('open'))
	    {
			/* var oHeight = onglet.height();
			log(oHeight); */
			$('.accordeon_onglet').slideUp(500, function() { $(this).removeClass('open'); });
			onglet.slideDown(500, function() { $(this).addClass('open'); });
	    }
	    return false;
	});
}

function launchDefile()
{
	timeratout = setInterval(function()
	{
		$('#atouts_dejelin ul').hide();
		nbreAtouts = $('#atouts_dejelin ul li').size();
		heightLi = $('#atouts_dejelin ul li:first').outerHeight();
		select = randomNumber(nbreAtouts);
		// log(select);
		$('#atouts_dejelin ul').show().stop().animate({ top:-(select*(heightLi+10))+'px'},1000);
	},5000);
}

function randomNumber(nbreAtouts)
{
	selectb =  Math.floor(Math.random()*nbreAtouts); // random selection
	if (selectb == select) 
	{
		select = selectb+1
		return select;
		
	}
	else 
	{
		select = selectb;
		return select;
	}
}

function filtreRegion()
{
	$('#filtre_regions a').live('click',function()
	{
		var theRegion = $(this).attr('rel');
		
		$('#filtre_regions a').removeClass('current');
		$(this).addClass('current');
		
		
		if (theRegion != 'All') 
		{
			$('#points_de_vente li').hide(); 
			$('#points_de_vente li.zip_'+theRegion).show();
		}
		else 
			$('#points_de_vente li').show();
		
		heightCols();
		return false;
	});
}

// appel ajax des infos d'un produit
function AjaxFancyboxProduct()
{
	function cutHash(txt)
	{
		var explode = txt.split('#');
		var href = explode[1];
		return href;
	}
	
	$('a.productajax').live('click', function() 
	{
		var ourContent = '.wrap';
		var relGallery = $(this).attr('rel'); // ex : #vapeur-dejelin-8001
		
		var pageToLoad = cutHash($(this).attr('href')); // ex : #vapeur-dejelin-8001
		var aliasPath = pageToLoad.substring(1); // on back le #
		// var divData = $('#ajax_product'); // div où les infos seront chargées
		
		$.ajax(
		{
			type: "GET",
			url: domain+"/do/ajaxProduct.php",
			data: "aliasPath="+aliasPath,
			success: function(jsondata)
			{
				$('#fancybox-overlay')
					.height($(document).height())
					.width($(document).width())
					.css({opacity:0.5})
					.show();
				
				var largeur=$(document).width();
				var positionleft = parseInt(parseInt(parseInt(largeur)/2)-480); 
				var closepositionleft = parseInt(positionleft + 943);
				
				var relativecontent = new Array();
				var iPrev, iNext, iFancy, iMax = 0;
				
				$(ourContent+' .productajax[rel='+relGallery+']').each(function(i){
					relativecontent[i] = cutHash($(this).attr('href'));
					// log(relativecontent[i]);
					if (relativecontent[i] == pageToLoad) iFancy = i; // numéro du slide actuel
					iMax = i;
				});

				// we use fancybox div with our own functions
				$('#fancybox-content')
					.empty()
					.append(jsondata)
					.css({ 'position' : 'fixed', 'top' : '50px', 'left' : positionleft, 'width': '958px', 'height': 'auto' });
				
				$('#fancybox-wrap').show();
				$('#fancybox-close').css({ 'position' : 'fixed', 'top' : '36px', 'left' : closepositionleft }).show();
				
				
				iPrev = parseInt(iFancy-1);
				iNext = parseInt(iFancy+1);
				// log(iPrev+' '+iNext+' '+iMax);
				
				if (iMax > 0) 
				{
					// slide précédent
					if (iPrev == -1) var previousSlide = relativecontent[iMax];
					else var previousSlide = relativecontent[iPrev]; 
					
					// slide suivant
					if (iNext > iMax) var nextSlide = relativecontent[0];
					else var nextSlide = relativecontent[iNext];
					
					$('#fancybox-content a.previous').attr({ 'href' : '#'+previousSlide, 'rel' : relGallery }).show();
					$('#fancybox-content a.next').attr({ 'href' : '#'+nextSlide, 'rel' : relGallery }).show();
				}
				
				$('.product_detail_ajax .details_left').jScrollPane();
				/* 
				// if jsondata est vraiment en json :P
				var dataObject = JSON.parse(jsondata);
				// on modifie les valeurs dans le html
				divData.find('h2').html(dataObject.title);
				divData.find('img.image_illus').attr({ src: dataObject.image2 });
				divData.find('div.colonners').html(dataObject.content4);
				divData.find('.details_right_contenu').html(dataObject.content2);
				divData.find('.details_right_specs').html(dataObject.content3);
				divData.find('.product_imageprice img').attr({ src: dataObject.image });
				divData.find('.eshop_price .price span').html(dataObject.price); 
				divData.show(500); 
				*/
			}
		});
		
		return false; 
	});
	
	// close the fancybox
	$('#fancybox-overlay, #fancybox-close').live('click', function() 
	{
		$('#fancybox-overlay').hide();
		$('#fancybox-wrap').hide(500);
		return false;
	});
}

function galerieProductAjax()
{
	$('.galerie_small').live('click', function()
	{
		if (!$(this).hasClass('current'))
		{
			var idThumb = $(this).attr('id');
			var thisGallery = $(this).parent('.gallery');
			
			var splitId = idThumb.split('_');
			var product = splitId[1];
			var numImg = splitId[2];
			
			var smallImg = 	$('.gallery #sma_'+product+'_'+numImg);
			var bigImg   = 	$('.gallery #big_'+product+'_'+numImg);
			
			thisGallery.find('.galerie_small').removeClass('current');
			smallImg.addClass('current');
			thisGallery.find('.galerie_big').hide();
			bigImg.show();
		}
		return false;
	});
}

function labelDelivery()
{
	$('.delivery_mod .details').click(function()
	{
		var deliveryMod = $(this).parent('.delivery_mod');
		var inputRadio = deliveryMod.find('.choice input');
		var valueCheck = inputRadio.attr('checked');
		if (valueCheck != 'checked') 
		{
			inputRadio.attr('checked','checked');
			$('.delivery_mod .details').attr('id','');
			deliveryMod.find('.details').attr('id','select');
		}
	});
	
	$('.delivery_mod input').change(function()
	{
		var deliveryMod = $(this).parents('.delivery_mod');
		$('.delivery_mod .details').attr('id','');
		deliveryMod.find('.details').attr('id','select');
	});
}

function targetBlankFacebook()
{
	if ($('body#facebookTemplate').length)
	{
		$('body a').attr('target','_blank');
	}
}

function showInvoice()
{
	
	if ($('#invoice').attr('checked') == "checked")
	{	
		$('#invoiceForm').show();
		if ($('#fac_same').attr('checked') == false) $('#invoiceFacForm').hide();
	}
	else
	{		
		$('#invoiceForm').hide();
		$('#invoiceFacForm').hide();
	}
}

function showFac(num)
{
	if ($('#fac_same').attr('checked') == "checked")
	{			
		$('#invoiceFacForm').hide();
	}
	else
	{			
		$('#invoiceFacForm').show();
	}
}

function verifFormLocation()
{
	$(this).submit(function()
	{
		var formReturn = false;
		if ($('#delivery option:selected').length)
		{
			var textOption = $('#delivery option:selected').text();
			if (textOption != "") { formReturn = true; }
			else alert('Vous devez selectionner un mode de livraison');
		}
		else 
		{ 
			alert('Vous devez selectionner un mode de livraison');
		}
		return formReturn;
	});
	
	
	/*
		$('#form_publi_mag').submit(function()
		{
			var formReturn = true;
			var nbreCaracteres = $('#form_publi_mag textarea#message').val().length;
			if (nbreCaracteres < 112) { alert('Votre annonce ne comporte pas assez de signes... (112 minimum)'); formReturn = false; }
			if (nbreCaracteres > 196) { alert('Votre annonce comporte trop de signes... (196 maximum)'); formReturn = false; }
			return formReturn;
		});
	*/
}

function fancyboxProductAjax()
{
	$('.eshop_gamme li.product a.moreinfos').each(function()
	{
		href = $(this).attr('href'); splitthis = href.split('#'); $(this).attr('href','#'+splitthis[1]);
	});
	
	$('#ajax_product').css({ 'display':'none', 'height':'auto', 'overflow':'visible'});
	
	$("a.moreinfos[rel=gallery_product]").fancybox(
	{
		'titlePosition'		: 'null',
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'showNavArrows'		: false,
		'cyclic'			: true,
		'onComplete'		: function() 
		{ 
			var hrefProduct = $(this).attr('href');
			if ($('.colonners[rel!=done]').length) 
			{ 
				$(hrefProduct+' .colonners').columnize( { columns:2, lastNeverTallest : true, doneFunc : function() { $(hrefProduct+' .colonners').attr('rel','done'); } }); 
			} 
		}
	});
}

function smoothScroll(objectMoving,translationZone,fixedZone,speed,delay)
{
	if(objectMoving.length)
	{
		// hauteur de la zone de translation
		var heightTranslationZone = translationZone.outerHeight(); 	
		
		// hauteur de la zone fixe
		var heightFixedZone = fixedZone.outerHeight(); 	
		
		// hauteur de l'object dynamique
		var heightObjectMoving = objectMoving.height(); 	
		
		// position initial de l'élément
		var offsetObjectTop = objectMoving.offset().top; 
		
		var timeout = setTimeout(function(){},10) ;
		
		$(document).scroll( function() 
		{
			clearTimeout(timeout);
			timeout = setTimeout(scrollMenu, delay);
		});
		
		var scrollMenu = function() 
		{
			if (objectMoving.length && heightFixedZone > heightObjectMoving)
			{
				// quand on scrolle...
				var positionWindow = $(document).scrollTop();
				
				if (positionWindow < offsetObjectTop) 
				{ objectMoving.animate({ top:0 },speed,'linear'); }
				
				if (positionWindow > offsetObjectTop && positionWindow < (offsetObjectTop+(heightTranslationZone - heightObjectMoving))) 
				{ objectMoving.animate({ top:(positionWindow-offsetObjectTop) },speed,'linear'); }
				
				if (positionWindow >= (offsetObjectTop+(heightTranslationZone - heightObjectMoving))) 
				{ objectMoving.animate({ top:(heightTranslationZone - heightObjectMoving) },speed,'linear'); }
			}
			else // fix problème : hauteur colonne gauche < hauteur colonne droite
			{
				translationZone.height(heightObjectMoving);
			}
		}
	}
}

function styleTags()
{
		if ($('#tags').length)
		{
				$('#tags a')
						.each
						(
								function()
								{
										var value = $(this).attr('class').substr(1);
										value /=100;
										var color = 180-(Math.floor(120*value));
										var size = 10+Math.floor(15*value);
										$(this).css({'color':'rgb('+color+','+color+','+color+')','font-size':size+'px'});
								}
						)
				
				
		}
}

function logoHovers()
{
		$('#logo_club.hoverable a')
				.hover
				(
						function()
						{
								$(this).find('img').stop(true,true).fadeOut();
						}
						,function()
						{
								$(this).find('img').stop(true,true).fadeIn();
						}
				);
				
		if ($('#logoDejelin a').find('img').length)
		{
				$('#logoDejelin a').find('#hover').hide();
				
				$('#logoDejelin a')
						.hover
						(
								function()
								{
										$(this).find('#hover').stop(true,true).fadeIn();
										$(this).find('#normal').stop(true,true).fadeOut();
								}
								,function()
								{
										$(this).find('#normal').stop(true,true).fadeIn();
										$(this).find('#hover').stop(true,true).fadeOut();
								}
						)
		
		}
		
}

function heightCols()
{
		var colLeft = $('#content_left_wrap');
		var colLeft2 = $('#content_left');
		var colRight = $('#content_right');
		
		var leftHeight = colLeft.outerHeight();
		var rightHeight = colRight.height();
		
		if (leftHeight > rightHeight)
		{
				colRight.height(leftHeight-17-2);
				$('#content_right #fb_box').css({'position':'absolute','bottom':'0','left':'14px'});
		}
		else
		{
				// colLeft.height(rightHeight-50-30-2);
				colLeft2.height(rightHeight-50-30);
		}
}

function search()
{
		$('#search_text').emptyFields();
		$('#form_newsletter input.text').emptyFields();
}

function showBand(SousMenu) // descend la bande blanche
{
	$('#band')
		.stop(true, true)
		.animate
		(
				{'height':'23px'}
				,100
				,function()
				{	
					SousMenu.stop(true,true).show(50).css('overflow','visible'); 
				}
		);
}

function hideBand() // cache la bande blanche
{
	$('#band')
		.stop(true, true)
		.animate({'height':'1px'},10, function() 
		{
			$('.menuElement .sous_menu').stop(true,true).hide();
		});
}

function sousMenuFix() // pour afficher le sous-menu de l'onglet current qd on n'est pas sur le menu
{
	var currentExist = 0;
	$('.menuElement .sous_menu').each(function(i) // on vérifie tous les sous-menus
	{	
		   if($(this).hasClass('current')) // si il y en a un avec la class current
		   {	
				showBand($(this)); currentExist++;
		   }
		   else // sinon on cache le sous-menu
		   {	$(this).hide();		}
	});
	
	if(currentExist == 0) // pas de sous menu, on cache la bande
	{ 
		hideBand();
	}
}
					
function sousMenu()
{
	$('#menu').mouseleave
	(
		function()
		{
			sousMenuFix();
		}
	);
				
	//2eme niveau
	$('.menuElement')
	.mouseenter // on entre sur un onglet
	(
		function()
			{
				var menuElement = $(this);
				var idMenuElement = menuElement.attr('id');
				if (!menuElement.find('ul.current').length) isHover=1; // on a été sur un autre menu
				
				// si l'onglet a un sous menu, on affiche ce sous-menu
				if (menuElement.find('ul').length > 0) 
				{
					// si l'onglet n'est pas le menu current (fix lag) ou si on a déjà été sur un autre menu
					if (!menuElement.find('ul.current').length || isHover>0) 
					{
						if (menuElement.find('ul.current').length) isHover=0;
						
						var child = menuElement.find('ul:first');
						var idMenuElement = menuElement.attr('id');
						
						$('#band')
							.stop(true, true)
							.animate
							(
									{'height':'23px'}
									,100
									,function()
									{
										$('.menuElement .sous_menu').hide();
										child.stop(true, true);
										child.show(50).css('overflow','visible');
									}
							);
					}
				}
				else // sinon on cache les possibles sous-menus ouverts
				{
					hideBand();
				}
			}
	)
			
			
	//3eme niveau
	$('.sous_menuElement')
			.hover
			(
					function()
					{
							if ($(this).find('ul').length)
							{
									$(this).find('ul:first').show();
							}
					}
					,function()
					{
							if ($(this).find('ul').length)
							{
									$(this).find('ul:first').hide();
							}
					}
			);
	
}


function swfImplements()
{
	//alert('implements');
	if ($('#vidBox').length)
	{
		//alert('oj');
		var zvid=$('#vidBox').attr('rel');
		var flashvars = {vid:zvid,width:"272"};
		var params = {allowFullScreen:"true",wmode:"transparent"};
		var attributes = {};
		swfobject.embedSWF(domain+"/files/flash/videoPlayer.swf?vid="+zvid+"&width="+272, "vidBox", "272", "163", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	}
	
	
	 
 }
