// Encodé en UTF-8

$(document).ready(function() {

	// Check if page is in iframe
	/*var isInIFrame = (window.location != window.parent.location) ? true : false;
	
	if(isInIFrame) $('body').addClass('fancy');*/
	
	// tous les liens externes s'ouvrent dans une nouvelle fenêtre et ont la classe "ext"
	$("a.ext, a[rel='ext']").click(function(event){
		event.preventDefault();
		window.open(this.href);
	}); 
	
	// Demande de confirmation sur tous les liens qui ont la class "del"
	$("a.del, .del").live('click',function(){
		var answer = confirm("<?php echo $_l['main']['confirm'] ?>");
		return answer;
	}); 
		
	// Fermeture de message top error
	$("#message-top a.close").click(function(event){
		event.preventDefault();
	})
	$("#message-top a.close").click(function () {
		$("#message-top").stop().stop();
		$("#message-top").animate({
			height: 'toggle'
		}, 'slow');
	});
	
	// Fermeture de message top success
	$("#message-top.ok")
	.animate({
		opacity: 1.0
	}, 4000)
	.animate({
		height: 'toggle'
	}, 'slow');
	// Actualisation du captcha
	
	$("img#captcha").click(function() {
		$(this).attr('src','');			
		$(this).attr('src','/captcha.jpg?v='+Math.random());
	});
	
	// RECIPES TOOLTIP
	$('ul.recipes-list li h2').hide();
	$('ul.recipes-list').addClass('recipes-list-js');
	
	$('ul.recipes-list li a.img').mouseenter(function() {
		
		$(this).parent().find('h2:not(:animated)').fadeIn(300);
	
	}).mouseleave(function() {
		
		$(this).parent().find('h2').fadeOut(300);
		
	});
	
	// PARTNERS TOOLTIP
	$('ul.partners-list li h2').hide();
	$('ul.partners-list').addClass('partners-list-js');
	
	$('ul.partners-list li a.img').mouseenter(function() {
		
		$(this).parent().find('h2:not(:animated)').fadeIn(300);
	
	}).mouseleave(function() {
		
		$(this).parent().find('h2').fadeOut(300);
		
	});
	
	// 10 POINTS JS LIST
	$('ol.points-list').addClass('points-list-js');
	$('ol.points-list-js li').each(function(i) {
		
		var content = $(this).html();
		var imgTitle = $(this).find('h2').text();
		var imgHref = $(this).find('img').attr('src').replace('raw', 'thumb');
		
		// AFFICHER le point correspondant à une ancre s'il y a une ancre
		if(window.location.hash) {
			var ancre=window.location.hash;
			ancre = ancre.substr(2);
			var point = ancre.split('-');
			point = point[0];
			
			var nbPoint = $('ol.points-list-js li').length;
			var ancreOk = (point <= nbPoint)? true:false;
			
		}
		

		$(this).html('');
		$(this).append('<img src="' + imgHref + '" width="132" height="132" alt="' + imgTitle + '" /><span class="mask"></span>');
		
		
		if((i == 0 && !ancreOk) || (ancreOk && i == (point-1))) {
			$('#point-detail').html(content).find('h2').prepend('<span class="number">' + (i+1) + '</span>');
		}

		
		$(this).find('.mask').click(function() {
		
			$('#point-detail').html(content);
			$('#point-detail').find('h2').prepend('<span class="number">' + (i+1) + '</span>');
			
		});
		
	});
	
	
	
	// NO LABEL FORM
	$('form.no-label input.text').each(function() {
		
		var obj = $(this);
		var objLabel = $(this).parent().find('label');
		var objParent = $(this).parent();
		
		// GET LABEL TEXT
		objParent.addClass('auto-label');
		
		if(obj.val() != '') {
			objLabel.hide();
		}
		
		// SET/REMOVE INPUT TEXT
		objLabel.click(function() {
			
			if( obj.val() == '' ) {
				objLabel.hide();
				obj.focus();
			}
			
		});
		obj.focus(function() {
			
			if( obj.val() == '' ) {
				objLabel.hide();
			}
			
		}).blur(function() {
			
			if( obj.val() == '' ) {
				objLabel.show();
			}
			
		});
		
	});
	
	var time = setInterval(function() {
		$('form.no-label input.text').each(function() {
			if( $(this).val() != '' ) {
				$(this).prev('label').hide();
			}
		});
	}, 5);
	
	// FANCYBOX CONTEST
	$('a.contest').click(function(ev) {
		ev.preventDefault();
		
		$.fancybox({
			'autoScale' : false,
			'height' : 600,
			'href' : $(this).attr('href') + '?fancy=fancy',
			'overlayColor' : '#fff',
			'overlayOpacity' : 0.65,
			'padding' : 0,
			'type' : 'iframe',
			'width' : 640
		});
	});
	
	
	// SLIDESHOW HOME
	//Navigation
	$('#slideshow .prev, #slideshow .next').live('click', function(event) {
		event.preventDefault();
		
		if($(this).hasClass('prev')) {
			slideshowHome(true);
		}else{
			slideshowHome(false);
		}

	});
	
	
	// IE6 FIX
	var ie6 = 	(	
		parseInt(navigator.appVersion) == 4
		&&
		navigator.appVersion.indexOf("MSIE 6.0") != -1
		&&
		navigator.appName == 'Microsoft Internet Explorer'
		);

	if ($.browser.msie && (ie6)) {
		
		$(document).find("img[src$=.png]").each(function() {
			var imgSrc = $(this).attr('src');
			var blankSrc = '/images/theme/blank.gif';
			
			$(this).attr('src', blankSrc);
			$(this).css({
				'background-image'	: 'none',
				'filter'			: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + imgSrc + '",sizingMethod="scale")'
			});
					
		});
	}
	
	$('.search-select').bind("change",function(e){
		var oThis = $(this);
		var value = oThis.val();
		var name = oThis.attr("name");
		var path = oThis.closest("form").attr("action");
		var url = "http://"+window.location.host+path+"?"+name+"="+value;
		window.location.href=url;
		
		return false;
	});
	
	$('a.print-recipe').click(function(ev) {
		ev.preventDefault();
		window.print();
	});
	
	
	
	/////////////////////////////////////////////////////
	//////////////////// CONCOURS////////////////////////
	/////////////////////////////////////////////////////
	
	var contestForm = $('#contest-form');
	var step0 = $('.step-0',contestForm);
	var step1 = $('.step-1',contestForm);
	var step2 = $('.step-2',contestForm);
	var sendForm = false;
	var contestErrorMsg = '';
	var contestError = false;
	var contestMailValue = '';
	
	// Générer les boutons d'interface
	$('#launchContestPlaceHolder').html('<p class="step-navigation"><a href="#" id="launchContest" class="next">'+"<?php l('contest.steps.start-contest'); ?>"+'</a></p>');
	$('#toStep2PlacerHolder').html('<p class="step-navigation"><a href="#" class="prev" id="backStep0">'+"<?php l('contest.steps.prev-step'); ?>"+'</a><a href="#" class="next" id="goStep2">'+"<?php l('contest.steps.next-step'); ?>"+'</a></p>');
	
	// Event Binding
	contestForm.bind("click",contestControls);
	
	$('a',contestForm).bind("click",function(e){
		e.preventDefault();
	});
	
	contestForm.bind("submit",function(e){
		if(!sendForm){
			e.preventDefault();
		}
		else{
	//console.log("go");
	}
	});
	
	// Cacher toutes les étapes sauf la première
	showBox(step0);
	
	// Events
	function contestControls(e){
		var target = $(e.target);
		var targetId = target.attr("id");
		var nbQuestions = $('.question',contestForm).length;
		
		if(targetId != ""){	
			switch(targetId){
				case 'launchContest':
					showBox(step1);
					break;

				case 'backStep0':
					showBox(step0);
					break;

				case 'backStep1':
					showBox(step1);
					break;

				case 'goStep2':
					// Récupération du type de question subsidiaire
					var contestSubsidiaryMode = "<?php e($_site['contest_subsidiary_mode'] ); ?>";
					contestError = false;
					contestErrorMsg = '';
					
					var errorAjaxMsg = '';
					var asyncValidation = false;
					
					// Validation étape 1
					
					// Vérifier si on a répondu à toutes les questions
					if($('input[name^=contest_answer]:checked',contestForm).length < 3){
						contestErrorMsg = "<p>"+"<?php e($_l['contest']['error-nb-questions']); ?>"+"</p>";
						contestError = true;
					}
					
					// Vérifier si on a bien répondu quelque chose pour la question subsidiaire
					if ($('#contest-subsidiary').val() == ""){			
						contestErrorMsg+= "<p>"+"<?php e($_l['contest']['error-no-subsidiary']); ?>"+"</p>";
						contestError = true;
					}
					else if(contestSubsidiaryMode == 'int' && !is_numeric($('#contest-subsidiary').val())){ // Vérifier si il s'agit bien d'un nombre (si on est en mode int - voir config)
						contestErrorMsg+= "<p>"+"<?php e($_l['contest']['error-subsidiary-not-int']); ?>"+"</p>";
						contestError = true;
					}
					
					if(contestError){
						showContestErrors(contestErrorMsg);

					}
					else{
						showBox(step2);
					}
					break;
				
				case 'submitContest':
					
					// Validation étape 2
					contestError = false;
					contestMailValue = $('#subscribe-email').val();
					
					// Validation email + est-ce que l'utilisateur existe déjà ?
					
					if (contestMailValue == ""){			
						contestErrorMsg+="<p>"+"<?php printf($_l['admin']['error-field-empty'],$_l['contest']['email']); ?>"+"</p>";
						contestError = true;
					}
					else if(!emailIsValid(contestMailValue)){
						contestErrorMsg+="<p>"+"<?php e($_l['contest']['error-email']); ?>"+"</p>";
						contestError = true;
					}
					else{
						asyncValidation = true;
						
						var jXHR = $.ajax({
							url:'/fr/ajax/contest-user-exists/',
							type: 'post',
							data: {
								'email':contestMailValue
							},
							dataType : 'text'
						});
					}
					
					if(asyncValidation){ // Si il y a eu check ajax
					
						// Si l'utilisateur n'existe pas déjà, continuer la validation du reste du formulaire
						// Sinon afficher l'erreur provenant de la requête ajax
						jXHR.success(function(data){
							if(data == '1'){
								errorAjaxMsg="<p>"+"<?php e($_l['contest']['error-user-exists']); ?>"+"</p>";
								showContestErrors(errorAjaxMsg);
							}
							else{
								contestValidation();
							}

						});
					}
					else{ //  Si pas de test ajax, continuer la validation 
						contestValidation();
					}
				
					break;
			}
		}
		
	//return false;
	}
	

	// Functions
	function showBox(step){
		$("fieldset",contestForm).hide();
		$(step,contestForm).show();
	}
	
	function showContestErrors(errorMsg){
		$.fancybox(errorMsg,{
			'autoDimensions'  : false,
			'overlayColor' : '#fff',
			'overlayOpacity' : 0.65,
			'height' : 100,
			'width' : 300
		});
	}
	
	function contestValidation(){
		contestErrorMsg = '';
		
		// prénom
		if ($('#subscribe-lastname').val() == ""){			
			contestErrorMsg+="<p>"+"<?php printf($_l['admin']['error-field-empty'],$_l['contest']['lastname']); ?>"+"</p>";
			contestError = true;
		}

		// nom
		if ($('#subscribe-firstname').val() == ""){			
			contestErrorMsg+= "<p>"+"<?php printf($_l['admin']['error-field-empty'],$_l['contest']['firstname']); ?>"+"</p>";
			contestError = true;
		}

		// Adresse
		if ($('#subscribe-address').val() == ""){			
			contestErrorMsg+="<p>"+"<?php printf($_l['admin']['error-field-empty'],$_l['contest']['address']); ?>"+"</p>";
			contestError = true;
		}

		// email
		if (contestMailValue == ""){			
			contestErrorMsg+="<p>"+"<?php printf($_l['admin']['error-field-empty'],$_l['contest']['email']); ?>"+"</p>";
			contestError = true;
		}
		else if(!emailIsValid(contestMailValue)){
			contestErrorMsg+="<p>"+"<?php e($_l['contest']['error-email']); ?>"+"</p>";
			contestError = true;
		}

		// ville
		if ($('#subscribe-city').val() == ""){			
			contestErrorMsg+="<p>"+"<?php printf($_l['admin']['error-field-empty'],$_l['contest']['city']); ?>"+"</p>";
			contestError = true;
		}

		// code postal
		if ($('#subscribe-zipcode').val() == ""){			
			contestErrorMsg+="<p>"+"<?php printf($_l['admin']['error-field-empty'],$_l['contest']['zipcode']); ?>"+"</p>";
			contestError = true;
		}

		if(contestError){
			showContestErrors(contestErrorMsg);
		}
		else{
			sendForm = true;
			contestForm.submit();
		}
	}
	
	// VIDEO BOX
	var flashvars = {};
	flashvars.base = "http://<?php echo($_SERVER['SERVER_NAME']) ?>/swf/VideoPlayer/";
	flashvars.defaultvid = "2";
	flashvars.lang = "<?php e($lang) ?>";
	flashvars.videoXml = "http://<?php echo($_SERVER['SERVER_NAME']) ?>/swf/VideoPlayer/XML/<?php e($lang) ?>/video_assets.xml";
	var params = {};
	params.quality = "best";
	params.scale = "noscale";
	params.salign = "tl";
	params.wmode = "window";
	params.bgcolor = "#fff";
	params.allowfullscreen = "true";
	var attributes = {
		id: "main"
	};
	swfobject.embedSWF("/swf/VideoPlayer/EXP/VideoPlayer.swf", "video-player", "530", "460", "10", "/swf/VideoPlayer/EXP/js/expressInstall.swf", flashvars, params, attributes);

	$("#nav-0 li.videos a, body.home .cta-box a.videos").click(function(ev) {
		ev.preventDefault();
		$.fancybox({
			'height' : 465,
			'href' : $(this).attr('href') + '?fancy=video',
			'overlayColor' : '#fff',
			'overlayOpacity' : 0.65,
			'padding' : 0,
			'type' : 'iframe',
			'width' : 530
		});
	});
	
});

//Initialisation des variables de configuration
var slideRatio			= 1.31,
maxSlideWidth		= 210,
minSlideWidth		= 70,
maxSlideHeight		= 160,
minSlideHeight		= (minSlideWidth / slideRatio),
slideWidth			= maxSlideWidth,
slideHeight			= maxSlideHeight,
countSlides			= 5;
redimentionRatio	= ((maxSlideWidth - minSlideWidth) / (countSlides-1))
settingsSlide_1 	= new Array(),
	settingsSlide_2 	= new Array(),
	settingsSlide_3 	= new Array(),
	settingsSlide_4 	= new Array(),
	settingsSlide_5 	= new Array(),
	settingsGo			= new Array(),
	settingsBack		= new Array(),
	allowAnimation 		= true,
	slideSpeed		 	= 500,
	descIndex			= 0,
	slideEasing			= 'easeOutExpo';
	
// Parametre spécifique au slides
// SLIDE 1
settingsSlide_1['left'] = 30;
settingsSlide_1['top'] = 50;
// SLIDE 2
settingsSlide_2['left'] = 250;
settingsSlide_2['top'] = 150;
// SLIDE 3
settingsSlide_3['left'] = 460;
settingsSlide_3['top'] = 160;
// SLIDE 4
settingsSlide_4['left'] = 560;
settingsSlide_4['top'] = 105;
// SLIDE 5
settingsSlide_5['left'] = 560;
settingsSlide_5['top'] = 60;
	
//Height & Width
for (i=0 ; i < countSlides ; i++){
	var tempWidth = maxSlideWidth - (i*redimentionRatio);
	var tempHeight = tempWidth / slideRatio;
		
	eval("settingsSlide_" + (i+1) + "['width'] = tempWidth");
	eval("settingsSlide_" + (i+1) + "['height'] = tempHeight");
}
	
// Slide go & back
settingsGo['left'] = -20;
settingsGo['top'] = -90;
settingsBack['left'] = 510;
settingsBack['top'] = 0;


//Fonction du slideshow sur la Home Page
function slideshowHome(inverse) { 
	//Si l'animation n'est pas en cours
	if(allowAnimation === true) {
		//Animation en cours
		allowAnimation = false;
		
		var activeIndex = 1;
		
		if(inverse === true) {
			activeIndex = countSlides-1;
		}
		
		
		var activeElement = $($('#slideshow #slide-image li')).eq(activeIndex).attr('id');
		activeElement = activeElement.split('-');
		activeElement = parseInt(activeElement[1]);
		
		var holder = $('#slideshow #slide-desc ul');		

		holder.animate({
			top : -(holder.children().eq(activeElement).position().top)
		}, slideSpeed, slideEasing);

		
		
		//Déplacement de tous les éléments
		$('#slideshow #slide-image li').each(function(i) {
			// i = index de l'élément suivant.
			var index = i;			
			
			//Si le slideshow tourne dans le sens inverse
			if(inverse === true) {
			
				index += 2;

				if(index > countSlides) {
					index = 1;
				}
				
				//On redéfini les coordonnée.
				tempGoLeft = settingsBack['left'];
				tempGoTop = settingsBack['top'];
				tempBackLeft = settingsGo['left'];
				tempBackTop = settingsGo['top'];
				
			} //Sinon déroulement normal
			else{
				
				if(index == 0) {
					index = countSlides;
				}
				
				//On défini les coordonnées
				tempGoLeft = settingsGo['left'];
				tempGoTop = settingsGo['top'];
				tempBackLeft = settingsBack['left'];
				tempBackTop = settingsBack['top'];
				
			}//endif
			
			//Les élément ne se trouvant pas en tête au en queue.
			if((i != 0 && inverse === false) || (i != countSlides-1 && inverse === true)){

			
				$(this).animate({
					left 	:	eval("settingsSlide_" + index + "['left']"),
					top 	:	eval("settingsSlide_" + index + "['top']")
				}, slideSpeed, slideEasing);
				
				$(this).css({
					'z-index' :	parseInt(countSlides-(index-1))
				});
				
				$(' img', this).animate({
					height 	:	eval("settingsSlide_" + index + "['height']"),
					width 	:	eval("settingsSlide_" + index + "['width']")
				}, slideSpeed, slideEasing);
				

			}//Element en tête ou queue
			else{
			
				$(this)
				.animate({
					left 	:	tempGoLeft,
					top 	:	tempGoTop,
					opacity	:	0
				}, slideSpeed/2, slideEasing, function(){
						
					$(' img', this).css({
						height 	:	eval("settingsSlide_" + index + "['height']"),
						width 	:	eval("settingsSlide_" + index + "['width']")
					});
					
					$(this)
					.css({
						left	:	tempBackLeft,
						top		:	tempBackTop,
						'z-index' :	parseInt(countSlides-(index-1))
					})
					.animate({
						left 	:	eval("settingsSlide_" + index + "['left']"),
						top 	:	eval("settingsSlide_" + index + "['top']"),
						opacity	:	1
					}, slideSpeed/2, slideEasing, function(){
						allowAnimation = true;
					});
		
					//Move Element
					if(inverse === true) {
						$('#slideshow #slide-image li').eq(countSlides-1).insertBefore($('#slideshow #slide-image li').eq(0));
					}else{
						$('#slideshow #slide-image li').eq(0).insertAfter($('#slideshow #slide-image li').eq(countSlides-1));
					}
				});
					
			} //endif

	
		});
		
	}
}

function emailIsValid(email) {
	
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
	return email.match(re)
}
	
// Match un nombre en js
function is_numeric(nombre) {
	var exp = new RegExp("^[0-9-.]*$","g");
	return exp.test(nombre);
}
	
// CLEAR AUTOCOMPLETE FOR CHROME
if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 && $('body.admin').length == 0) {
	$(window).load(function(){
		var timer = setTimeout(function() {
			$('input:-webkit-autofill').each(function(){
				$(this).prev('label').hide();
			});
			if($('input:-webkit-autofill').get[0]) {
				clearTimeout(timer);
			}
		}, 5);
	});
}

