/* ***************************************************************************** APPEL DES FONCTIONS JQUERY AU CHARGEMENT DE LA PAGE */
$(document).ready(function() {
	menuHoverIE();				// fonction simulant le :hover sur le LI pour IE6 pour les menus déroulants
	swapValue();				// fonction effacant la valeur du champ sur le :focus et la réaffiche sur le :blur
	sameHeight();				// fonction permettant a des blocs communs d'avoir la meme taille
	flashHome();				// Initialisation Flash Home Page
	playerVideo();				// Initialisation Flash Player Video
	playerVideo2();				// Initialisation Flash Player Video
	carousel3D();				// Initialisation Carousel 3D
	dernieresPhotosCarousel();	// jCarousel
	semaineProchaineCarousel();	// jCarousel
	cycleDernieresRecettes();	// jQuery Cycle
	cycleSemaineDerniere();		// jQuery Cycle
	cycleDiaporama();			// jQuery Cycle
	cyclePhotos()				// jQuery Cycle
	openNoteZone();				// ouvre et ferme l'espace de notation
	notation();					// gere l'affichage de la notation
	toggleCriteres ();			// interrupteur pour afficher les criteres du formulaire 'rechercher une recette'
	autocomplete() ;			// autocompletion pour les mots clefs du formulaire 'rechercher une recette'
});

/* ***************************************************************************** MENU HOVER IE */
function menuHoverIE(){
    if (document.all) {
        $("#metabarre li, #menu li, #navPhotos li, #navVideos li, #navCandidat li").hoverClass ("sfhover");
    }
}

$.fn.hoverClass = function(c) {
    return this.each(function(){
        $(this).hover( 
            function() { $(this).addClass(c);  },
            function() { $(this).removeClass(c); }
        );
    });
};

/* ***************************************************************************** SWAP VALUE */
function swapValue() {
	swapValues=[];$(".swapValue").each(function(i){swapValues[i]=$(this).val();$(this).focus(function(){if($(this).val()==swapValues[i]){$(this).val("")}}).blur(function(){if($.trim($(this).val())==""){$(this).val(swapValues[i])}})});
}

/* ***************************************************************************** SAME HEIGHT */
function sameHeight() {
	if( $(".sameHeight").size() < 1 ) return false;
	
	var heightBlockMax=0;
	$('.sameHeight').each(function(){ if( $(this).height() > heightBlockMax ) heightBlockMax = $(this).height(); }); // get max height
	$('.sameHeight').each(function(){ $(this).css("height", heightBlockMax + "px"); }); // assign max height
	heightBlockMax=0;
}

/* ***************************************************************************** FLASH HOMEPAGE */
function flashHome() {
	if( $("#swfHome").length < 1 )	return false;

	var flashvars = {};
		flashvars.xmlLink = "./xml/config-home.xml";
	var params = {};
		params.menu = "false";
		params.quality = "high";
		params.wmode = "transparent";
		params.allowscriptaccess   = "always";
	var attributes = {};
		attributes.id = "base";
	swfobject.embedSWF("m6playerdinerpparfait.swf", "swfHome", "686", "256", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}

/* ***************************************************************************** CAROUSEL 3D */
function carousel3D() {
	if( $(".carousel3D").length < 1 ) return false;
	$(".carousel3D").each(function(i){
		$(this)
			.attr("id", "carousel3D-" + i)
			.find(".prev")
				.attr("id", "prev" + i)
				.click(function() {
					if(pos1[i] > 0) {pos1[i]--;} else {pos1[i] = nbListe[i]-1;}
					if(pos2[i] > 0) {pos2[i]--;} else {pos2[i] = nbListe[i]-1;}
					if(pos3[i] > 0) {pos3[i]--;} else {pos3[i] = nbListe[i]-1;}
					move($(this));
					return false;
				})
			.end()
			.find(".next")
				.attr("id", "prev" + i)
				.click(function() {
					if(pos1[i]< nbListe[i]-1) {pos1[i]++;} else {pos1[i] = 0;}
					if(pos2[i]< nbListe[i]-1) {pos2[i]++;} else {pos2[i] = 0;}
					if(pos3[i]< nbListe[i]-1) {pos3[i]++;} else {pos3[i] = 0;}
					move($(this));
					return false;
				})
			.end()
			.find(".linkLeft")
				.attr("id", "linkLeft" + i)
			.end()
			.find(".linkCenter")
				.attr("id", "linkCenter" + i)
			.end()
			.find(".linkRight")
				.attr("id", "linkRight" + i)
			.end()
			.find(".legende")
				.attr("id", "legende" + i)
			.end()
		
		
		function move(object) {
			imgLeftSrc = $(object).parent().find("li img:eq(" + pos1[i] + ")").attr("src");
			imgCenterSrc = $(object).parent().find("li img:eq(" + pos2[i] + ")").attr("src");
			imgRightSrc = $(object).parent().find("li img:eq(" + pos3[i] + ")").attr("src");
			
			imgLeftLink =   $(object).parent().find("li a:eq(" + pos1[i] + ")").attr("href");
			imgCenterLink = $(object).parent().find("li a:eq(" + pos2[i] + ")").attr("href");
			imgRightLink =  $(object).parent().find("li a:eq(" + pos3[i] + ")").attr("href");
			
			legende = $(object).parent().find("li span:eq(" + pos2[i] + ")").text();
			
			$('#linkLeft' + i ).attr("href", imgLeftLink).find("img").attr("src", imgLeftSrc);
			$('#linkCenter' + i).attr("href", imgCenterLink).find("img").attr("src", imgCenterSrc);
			$('#linkRight' + i).attr("href", imgRightLink).find("img").attr("src", imgRightSrc);
			$('#legende' + i).text(legende).attr("href", imgCenterLink);
		}
		
		var nbListe = new Array();
		var pos1 = new Array();
		var pos2 = new Array();
		var pos3 = new Array();
		var imgLeftSrc = new Array();
		var imgCenterSrc = new Array();
		var imgRightSrc = new Array();
		
		nbListe[i] = $(this).find("li").length;
		pos1[i] = nbListe[i]-1;
		pos2[i] = 0;
		pos3[i] = 1;
		move($(this));
	});
}


/* ***************************************************************************** FLASH PLAYER VIDEO */
function playerVideo() {
	if( $("#playerVideo").length < 1 ) return false;
	var xml=$("#playerVideo_config").val();
	var flashvars = {};
		flashvars.appWidth = "630";
		flashvars.appHeight = "388";
		flashvars.xmlLink = "http://undinerpresqueparfait.m6.fr/xml/"+xml;
		flashvars.domain = "http://undinerpresqueparfait.m6.fr/";
	var params = {};
		params.base = "http://video.m6.fr/players/flash/generic/";
		params.menu = "true";
		params.allowScriptAccess = "always";
		params.wmode = "transparent";
	var attributes = {};
	swfobject.embedSWF("http://video.m6.fr/players/flash/generic/m6webtv_basic.swf", "playerVideo", "630", "388", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
}


/* ***************************************************************************** FLASH PLAYER VIDEO */
function playerVideo2() {
	if( $("#playerVideo2").length < 1 ) return false;
	var xml=$("#playerVideo_config").val();
	var flashvars = {};
		flashvars.appWidth = "414";
		flashvars.appHeight = "277";
		flashvars.xmlLink = "http://undinerpresqueparfait.m6.fr/xml/"+xml;
		flashvars.domain = "http://undinerpresqueparfait.m6.fr/";
	var params = {};
		params.base = "http://video.m6.fr/players/flash/generic/";
		params.menu = "false";
		params.allowScriptAccess = "always";
		params.wmode = "transparent";
	var attributes = {};
	swfobject.embedSWF("http://video.m6.fr/players/flash/generic/m6webtv_basic.swf", "playerVideo2", "414", "277", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
}

/* ***************************************************************************** CAROUSEL DERNIERES PHOTOS  */
function dernieresPhotosCarousel() {

	$('#carousel-1').jCarouselLite({scroll:2, btnNext: "#bNext", btnPrev: "#bPrev"});
	$('#carousel-1').css('left','0');
	
	$('#carousel-2 > ul').jcarousel({scroll:2});	
	$('#carousel-2').css('left','0');
}

/* ***************************************************************************** CAROUSEL SEMAINE PROCHAINE  */
function semaineProchaineCarousel() {
	if($("#semaineProchaineCarousel").size() < 1) 
		return false;
	
	$('#semaineProchaineCarousel > ul').jcarousel({scroll:1});	
	$('#semaineProchaineCarousel').css('left','0');
}

/* ***************************************************************************** CYCLE DERNIERES RECETTES */
function cycleDernieresRecettes() {
	$('#slideShow1').cycle({ 
		speed:       1,
		timeout:     0,
		pager:      '#navCycle1',
		pagerEvent: 'mouseover',
        pagerAnchorBuilder: function(idx, slide) {
            return '#navCycle1 li:eq(' + (idx) + ')';
        }
	});
}

/* ***************************************************************************** CYCLE SEMAINE DERNIERE */
function cycleSemaineDerniere() {
	$('#slideShow2').cycle({ 
		speed:       200, 
		timeout:     0,
		pager:      '#navCycle2',
		pagerEvent: 'mouseover',
        pagerAnchorBuilder: function(idx, slide) {
            return '#navCycle2 li:eq(' + (idx) + ')';
        }
	});
}

/* ***************************************************************************** CYCLE DIAPORAMA */
function cycleDiaporama() {
	$('#slideShow3').cycle({ 
		timeout:     6000,
		pager:      '#navCycle3',
        pagerAnchorBuilder: function(idx, slide) {
            return '#navCycle3 li:eq(' + (idx) + ')';
        }
	});
}

/* ***************************************************************************** CYCLE PHOTOS */
function cyclePhotos() {
	$('.listePhotos').cycle({
		fx: 	 'scrollHorz',
		prev:   '.btPrevious', 
    	next:   '.btNext', 
    	timeout: 3000,
		after:   onAfter,
		pager:  '#sesPhotos',
    	pagerAnchorBuilder: function(idx, slide) {
        	return '#sesPhotos li:eq(' + idx + ') a'; 
    	} 
    }).cycle('pause');
	
	function onAfter(curr, next, opts) {

		var index = $(this).parent().children().index(this);
		$('#titreMedia').html("").append(this.alt); 
		$('.numPhoto').html("").append((index+1) + '/' + opts.slideCount);
		if ($('#pubRectangle')) {
		window.parent.frames['pubRectangle'].location.reload();
		}

		if ($('#pubHeader')) {
		//window.parent.frames['pubHeader'].location.reload();
		}
	}
	
	$('.btDiaporama').toggle(
		function() { 
			$('.listePhotos').cycle('resume');
			$(this).addClass("resume");
			return false;
		},
		function() { 
			$('.listePhotos').cycle('pause');
			$(this).removeClass("resume");
			return false;
		}
	);
}



/* scrollHorz */
(function($) {
	$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
		$cont.css('overflow','hidden').width();
	//    $slides.show();
		opts.before.push(function(curr, next, opts, fwd) {
			$(this).show();
			var currW = curr.offsetWidth, nextW = next.offsetWidth;
			opts.cssBefore = fwd ? { left: nextW } : { left: -nextW };
			opts.animIn.left = 0;
			opts.animOut.left = fwd ? -currW : currW;
			$slides.not(curr).css(opts.cssBefore);
		});
		opts.cssFirst = { left: 0 };
		opts.cssAfter = { display: 'none' }
	};
})(jQuery);

/* ********************************************************************************* OUVERTURE NOTEZONE */


function openNoteZone() {
	if( $(".notation").length < 1 ) return false;
	
	$('.noteClic').click( function() {
		$(this).parent().children('.noteZone').show("slow");
		return false;
	});
	$('.closeNoteZone a').click( function() {
		$(this).parent().parent().hide("slow");
		return false;
	});
};

/* ********************************************************************************* CURSEUR NOTE */
var clicked = new Array();
function notation() {
	if( $(".noteZone").length < 1 ) {
		return false;
	} else {

	$(".noteZone").each(function(i){
		clicked[i] = false;

		$(this)
			.attr("id", "noteZone" + i)
			.find(".star2 a")
			.mouseout(function(){ 
				 if (clicked[i] == false) { 
					$(this).parent().removeClass();
				 }
			})
			.mouseover(function(){
				if (clicked[i] == false) {
					 var index = $(this).parent().children('a').index(this) + 1;
					 $(this).parent().removeClass().addClass('star-' + index);
				}
			})
			.click(function(){
				 if (clicked[i] == false) {
					var index = $('#noteZone' + i +' .star2 span a').index(this) + 1;
					var type = $('#noteZone' + i + ' .starInner').attr('id');
					var id = $('#noteZone' + i +' .star2').attr('id');

//					$(this).parents('#noteZone' + i).children('p').html('Merci pour votre vote,<br />la note attribu&eacute;e est : ' + index);
					$.ajax({  type: "POST",
  							 url: "/modules/vote/vote.php",
  							 data : "type="+type+"&note="+index+"&id="+id,
  							 success: function(msg){
					$('#noteZone' + i + ' p').html('Merci pour votre vote,<br />la note attribu&eacute;e est : ' + (index/2));
					window.location.reload();
     						 }, error: function(msg){
					$('#noteZone' + i + ' p').html('Une erreur est survenue, merci de r&eacute;essayer');
     						 }
  					});
					$(this).parent().removeClass().addClass('star-' + index);
				 }
				 clicked[i] = true;
				 return false;
			})
	});
	}
};

/* ********************************************************************************* TOGGLE CRITERES */
function toggleCriteres() {
	if( $("#plusDeCriteres").length < 1 )	return false;
	
	 var texte = $('#plusDeCriteres').html();
	 $("#plusDeCriteres").toggle(
      function () {
		$('#plusDeCriteres').html("Afficher moins de crit&egrave;res");
        $('#criteresSup').show("slow");
      },
      function () {
	
		$('#plusDeCriteres').html(texte);
        $('#criteresSup').hide("slow");
      }
    );
};

/* ********************************************************************************* AUTOCOMPLETE */
function autocomplete() {
	if( $("#motclefs").length < 1 )	return false;
	$("#motclefs").autocomplete(data);
};

/*********************************************************************************************************/
/* ***************************************************************************** PUBS ET ANNONCES GOOGLE */
ord = Math.random()*10000000000000000;

function google_ad_request_done(google_ads) {
	if (google_ads.length < 1 )	return;
		var s = '';
		s += '<ul class="googleLinks cf">';
		if (google_ads[0].type == 'text') {
			for(i = 0; i < google_ads.length; ++i) {
				s += '<li class="googleAnnonce">' + '<span class="title"><a target="_blank" href=\'' + google_ads[i].url + '\'" onmouseover="window.status=\'Go to ' + google_ads[i].visible_url + '\'" onmouseout="window.status=\'\'">' + google_ads[i].line1 + '</a></span>' + '<span class="data">' + google_ads[i].line2 + '&nbsp;' + google_ads[i].line3 + '<br></span>' + '<span class="link"><a style="" target="_blank" href="' + google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'afficher la page ' + google_ads[i].visible_url + '\';return true">' + google_ads[i].visible_url + '</span></a>';
			}
		}
		s += '</ul>';
		document.write(s);
	return;
}

/************************* commentaires *********************/

function getCommentaire(identifiant, type, page, iframed) {
	$.get("/modules/commentaires/derniers_commentaires.php", {id : identifiant, idt:type, page:page}, function changeTd(getdata) {
		$('#list_comments').fadeOut('fast', function() {
			$('#list_comments').html(getdata);
			$('#list_comments').fadeIn('fast');

			if (iframed == '1') {
				var tag_stat = $('#pubRectangle span').attr('id');
				$('#pubRectangle span').text('').html('');
				$('#pubHeader').text('').html('');
				$('#partenaire1').text('').html('');
				$('#partenaire2').text('').html('');
				$('#pubRectangle span').html('<iframe src="/modules/google/g_iframe.php?banner=col_droite&tag_stat=' + tag_stat + '" width="300" height="250" frameborder="0" scrolling="no"></iframe>');
				$('#pubHeader').html('<iframe src="/modules/google/g_iframe.php?banner=header&tag_stat=' + tag_stat + '" width="728" height="90" frameborder="0" scrolling="no"></iframe>');
				$('#partenaire1').html('<iframe src="/modules/google/g_iframe.php?banner=partenaire1&tag_stat=' + tag_stat + '" width="120" height="90" frameborder="0" scrolling="no"></iframe>');
				$('#partenaire2').html('<iframe src="/modules/google/g_iframe.php?banner=partenaire2&tag_stat=' + tag_stat + '" width="120" height="90" frameborder="0" scrolling="no"></iframe>');
			}
		});

	});
}

function postCommentaire(id) {

    	var auteur_form = document.getElementById('pseudo').value;
	var email_form = document.getElementById('email_comment').value;
	var texte_form = document.getElementById('message').value;
	var url = document.getElementById('url').value;
	var type = document.getElementById('type').value;
	var code = document.getElementById('code').value;

	$.post('/modules/commentaires/commentaire.php?id='+id+'&idt='+type, {auteur_form:auteur_form,email_form:email_form,texte_form:texte_form,code:code,url:url}, function (postdata){

		$('#postCommentResult').html(postdata);
		var img = document.getElementById('cryptogram');
		img.src = 'lib/crypto/cryptographp.php?cfg=0&' + Math.random();
		$('#code').val('');
//		document.getElementById('code').value = '';

		if ($("#msgComment").attr('class') == "ok") {
		$('#pseudo').val('');
		$('#email_comment').val('');
		$('#message').val('');
		getCommentaire(id, type, '1');
		}

		setTimeout("$('#msgComment').fadeOut()", 1000);

	});
}  
