/* ********************************* INIT */
$(document).ready(function() {
	w9_menu.init();			//menu
	swapValue()	;			//swapValue
	sameHeight();			//sameHeight
	showHover();			//fonction pour afficher / cacher une partie d'une legende (avec la classe h4)
	partenairesM6();		//swfobject
	//aLaUne();				//swfobject
	//scrollALaUne();			// jCarousel
	carousel3D();			//swfobject
	scrollPane();			//jScrollPane
	scrollHoz();			//scrollTo
	jCarouselScrollOne();	//jCarousel
	jCarouselScrollFour();	//jCarousel
	jCarouselHpW9Replay();
	cyclePhotos();			//cycle
	//playerVideo();			//swfobject
	playerVideoSpectacle();	//swfobject
	rssToggle();			//rss
	specialIE6();			//special pour IE6
	account();				//tabs mon compte
	openParent();			//ouvre le lien sur le parent
	changeSelect();			//gestion des onchange sur les selects
	formContact();			//verification du form de contact
	grilleProg();			//carousel grille des programmes
	voteCandidat();
	downloadIE8();
	// cas special
	jQuery("#colR .upPortail:eq(0)").addClass("upDegrade");
});
$(window).bind('load', function () {
	 $("#carouLogo").show();
	 if (jQuery.browser.msie) {
		$("#carouLogo .fade-on").hide();
		$("#carouLogo a").hover(
			function () {
				$(this)
					.find(".fade-on").show().end()
					.find(".fade-off").hide();	
			},
			function () {
				$(this)
					.find(".fade-on").hide().end()
					.find(".fade-off").show();
			}
		);
	 } else {
		$("#carouLogo .fade-on").css("opacity","0");
		$("#carouLogo a").hover(
			function () {
				$(this)
					.find(".fade-on").stop().animate({opacity: 1}, "normal", "linear");
			},
			function () {
				$(this)
					.find(".fade-on").stop().animate({opacity: 0},"normal","linear");
			}
		);
	 }
});
/* ********************************* MENU */
var w9_menu = {
	index: 0,
	init: function(){
		this.handleMain();
		
		if( $("#loadingMenu").size() < 1 )
			this.createLoaderMenu();
		
		this.handleSub();
		this.handleClose();
	},
	handleMain: function(){
		if($('#menuW9 li').size() < 1) return false;
		
		$('#menuW9 li').unbind("click").click(function(){
			w9_menu.index = $('#menuW9 li').index(this);
			
			if ($(this).hasClass("current")) {
				//fermeture
				$('#subMenu').slideUp(function(){
					$('#sub-menu' + w9_menu.index + '-content').empty();
					$("#subMenuRight").empty();
				});
				$('#menuW9 li').removeClass();
			} else {
				//ouverture
				$('#menuW9 li').removeClass();
				$(this).addClass("current");
				$('.subMenu').hide();
				$('#sub-menu' + w9_menu.index + '-content').empty();
				$("#subMenuRight").empty();
				$('#subMenu').slideDown();
				$('#sub-menu' + w9_menu.index).show();
				
				if( $("#sub-menu" + w9_menu.index).size() > 0 ) $("#sub-menu" + w9_menu.index + " .tri a:eq(0)").click();
				
				/* si c'est le guide tv alors...*/
				if(w9_menu.index==2){
					$("#sub-menu" + w9_menu.index + "-content").fadeOut(200, function(){
						$("#loadingMenu").fadeIn(200, function(){
							w9_menu.loadMenu("sub-menu" + w9_menu.index, 0);
						});
					});
				}
			}
			return false;
		});
	},
	handleSub: function(){
		if($('.tri a').size() < 1) return false;
		
		$('.tri a').unbind("click").click(function(){
			$(".tri li").removeClass();
			$(this).parent("li").addClass("ui-tabs-selected");
			
			var href = $(this).attr("href");
			var subMenu = href.slice(1).split("-")[1];
			var menu = $(this).parents("div").attr("id");
			
			$("#subMenuRight").fadeOut(200);
			$("#" + menu + "-content").fadeOut(200, function(){
				$("#loadingMenu").fadeIn(200, function(){
					w9_menu.loadMenu(menu, subMenu);
				});
			});
			
			return false;
		});
	},
	handleClose: function(){
		$('#fermerSousMenu').click(function(){
			$('#subMenu').slideUp(function(){
				$('#sub-menu' + w9_menu.index + '-content').empty();
				$("#subMenuRight").empty();
			});
			$(".plusInfos").hide();
			$('#menuW9 li').removeClass();
			return false;
		});
	},
	loadMenu: function(menu, subMenu){
		switch(menu){
			case "sub-menu0":
				data = "node=programmes&tab=" + subMenu;
				break;
			case "sub-menu1":
				data = "node=videos&tab=" + subMenu;
				break;
			case "sub-menu2":
				data = "node=guidetv&date=";
				break;
			case "sub-menu3":
				data = "node=plus&tab=" + subMenu;
				break;
		}
		
		$.ajax({
			type: "GET",
			url: "/ajax_load.php",
			data: data,
			dataType: "html",
			success: function(data){
				$("#loadingMenu").fadeOut(200);
				
				
				if(menu == "sub-menu2"){
					$("#" + menu + "-content").css({ display: "block", position: "absolute", left: "-9999px" }).html(data);
					$("#jCarouselSemainier")
						.jcarousel({scroll:7, start:8, initCallback: function(carousel){
								carousel.list.css(carousel.lt, '0px');
								//carousel.setup();
								$("#" + menu + "-content").css({ display: "none", position: "static", left: "0" }).fadeIn(500, function(){
									$("#sub-menu2 .containerCol").css({ visibility: "visible" }).hide().fadeIn(500);
									$("#sub-menu2 .containerCol .miseEnAvant li").css({ visibility: "visible" }).hide().fadeIn(500);
									w9_menu.bindCarouselGuideTV();
								});
							}
						})
						.parents(".jCarouselParent")
						.css('left','0');
				} else {
					$("#" + menu + "-content").html(data).fadeIn();
				}
				
				$("#subMenuRight").empty().hide();
				$("#subMenu > #subMenuRight").append( $("#" + menu + "-content .subMenuRight").html() );
				$("#subMenuRight").fadeIn(500, function(){
					w9_menu.handleClose();
				});
				$("#" + menu + "-content > .subMenuRight").remove();
			},
			error: function(error){
				console.log(error);
			}
		});
	},
	bindCarouselGuideTV: function(){
		date = w9_menu.dateToday();
		$("#sub-menu2 .semainier li a[name='" + date + "']").addClass("on");
		
		$("#sub-menu2 .semainier li a").unbind("click").click(function(){
			$("#sub-menu2 .semainier li a").removeClass("on");
			$(this).addClass("on");
			
			href = jQuery(this).attr("href");
			date = href.split("#")[1];
			
			$("#subMenu > #subMenuRight").fadeOut(500);
			$("#sub-menu2 .containerCol .miseEnAvant li").fadeOut(500);
			$("#sub-menu2 .containerCol").fadeOut(500, function(){
				$("#loadingMenu").fadeIn(200, function(){
					$.ajax({
						type: "GET",
						url: "/ajax_load.php",
						data: "node=guidetv&date=" + date,
						dataType: "html",
						success: function(data){
							$("#loadingMenu").fadeOut(200, function(){
								$("#sub-menu2 .containerCol").remove();
								$("#sub-menu2 .semainier").after(data);
								
								$("#subMenuRight").empty().hide();
								$("#subMenu > #subMenuRight").append( $("#sub-menu2-content .subMenuRight").html() );
								$("#subMenuRight").fadeIn(500, function(){
									w9_menu.handleClose();
								});
								$("#sub-menu2-content > .subMenuRight").remove();
								
								$("#sub-menu2 .containerCol").css({ visibility: "visible" }).hide().fadeIn(500);
								$("#sub-menu2 .containerCol .miseEnAvant li").css({ visibility: "visible" }).hide().fadeIn(500);
							});
						}
					});
				});
			});
			
			return false;
		});
	},
	createLoaderMenu: function(){
		loader = document.createElement("div");
		$(loader).attr({ id: "loadingMenu" });
		$("#subMenu").append(loader);
	},
	dateToday: function(){
		dateToday = new Date();
		
		day = dateToday.getDate();
		day = day < 10 ? "0" + day : day;
		month = dateToday.getMonth()+1;
		month = month < 10 ? "0" + month : month;
		year = dateToday.getFullYear();
		
		return day.toString() + month.toString() + year.toString();
	}
};
/* ********************************* SWAP VALUE */
function swapValue() {
	if( $(".swapValue").length < 1 ) return false;
	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").length < 1 ) return false;
	var heightBlockMax=0;
	$('.sameHeight').each(function(){
		if( $(this).height() > heightBlockMax ) heightBlockMax = $(this).height(); 
	}); // get max height
	if ($.browser.msie && $.browser.version == 6.0) { $('.sameHeight').css({'height': heightBlockMax}); }
	$('.sameHeight').css({'min-height': heightBlockMax});
}
/* ********************************* SCROLL HORIZONTAL */
function scrollHoz() {
	if( $(".scrollTo").length < 1 ) return false;
	$(".scrollTo").each(function(i){
		var links = $(this).find(".scrollTo-Links a");
		
		links.click(function(){
			index = links.index(this);
			links.removeClass("current");
			$(this)
				.addClass("current")
				.parents(".scrollTo")
				.find(".scrollTo-Mask")
				.scrollTo( "ul:eq(" + index + ")", 1000, {axis:"x"} );
			return false;
		})
	});
	$(".scrollTo-Links li:first-child a").click();
}
/* ********************************* SHOW HOVER H4 */
function showHover() {
	if( $(".showHover li").length < 1 ) return false;
	$('.showHover li').hover(
		function() {
			$(this).find('.h4').addClass("hover");
			return false;
		},
		function() {
			$(this).find('.h4').removeClass("hover");
			return false;
		}					
	);
}
/* ********************************* FLASH PARTENAIRES M6 */
function partenairesM6() {
	var flashvars = {};
	flashvars.disabledID = "M6"; /*	les autres valeurs sont : W9,PP,TE,MH,MB,MC	*/
	var params = {};
	params.bgcolor = "#7990A0";
	params.allowscriptaccess = "always";
	params.wmode = "transparent";
	var attributes = {};
	attributes.id = "base";
	swfobject.embedSWF("http://www.m6.fr/swf/logodisplay.swf", "flashId1", "340", "45", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
}
/* ********************************* FLASH A LA UNE HOME PAGE */
function aLaUne() {
	
	var flashvars = {};
	flashvars.xmlLink = "xml/config.xml";
	var params = {};
	params.bgcolor = "#000000";
	params.allowscriptaccess = "always";
	params.wmode = "transparent";
	var attributes = {};
	attributes.id = "base";
	swfobject.embedSWF("/swf/homefrontshowv2.swf", "flashId2", "470", "264", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	
	//$("#flashId2").html("Ce flash est desactive, c'est pas un bug !").css("color","white");
}
function scrollALaUne(){
	$(".module_epg_mea_visuel ul li .text").hide();
	$(".module_epg_mea_visuel ul li:eq(0) .text").show();
	
	var firstLoad = false;
	
	$(".module_epg_mea_visuel ul").after("<div id=\"nav-alaune\">").cycle({
		pager: "#nav-alaune",
		//speed: 2500,
		timeout: 7000,
		before: function(currSlideElement, nextSlideElement, options, forwardFlag){
			$(".text", nextSlideElement).hide();
		
			$(".text", currSlideElement).animate({ height: "toggle" },
				function(){
					if( $(".module_epg_mea_visuel ul li").index(nextSlideElement) == 0 && !firstLoad ){
						firstLoad = true;
					} else {
						$(".text", nextSlideElement).hide().animate({ height: "toggle" });
					}
				}
			);
		}
	});
	
/* INUTILE POUR LA PROD - JUSTE POUR LES GABARITS INTEGRATION (N.Terras) */
	$("#AlaUne ul li .text").hide();
	$("#AlaUne ul li:eq(0) .text").show();
	var firstLoad = false;
	$("#AlaUne ul").after("<div id=\"nav-alaune\">").cycle({
		pager: "#nav-alaune",
		//speed: 2500,
		timeout: 7000,
		before: function(currSlideElement, nextSlideElement, options, forwardFlag){
			$(".text", nextSlideElement).hide();
		
			$(".text", currSlideElement).animate({ height: "toggle" },
				function(){
					if( $(".module_epg_mea_visuel ul li").index(nextSlideElement) == 0 && !firstLoad ){
						firstLoad = true;
					} else {
						$(".text", nextSlideElement).hide().animate({ height: "toggle" });
					}
				}
			);
		}
	});
/* INUTILE POUR LA PROD FIN *********************************************** */

}
/* ********************************* FLASH CAROUSEL 3D */
function carousel3D() {
	var flashvars = {};
	flashvars.xmlLink="xml/config_videos.xml";
	var params = {};
	params.quality = "high";
	params.bgcolor = "#ffffff";
	params.allowfullscreen = "true";
	params.allowscriptaccess = "always";
	var attributes = {};
	attributes.id = "M6HomeVideoFeed";
	swfobject.embedSWF("http://groupemsix.vo.llnwd.net/o24/u/m6fr/M6HomeVideoFeed.swf", "flashId3", "701", "392", "9.0.28", "expressInstall.swf", flashvars, params, attributes);
}
/* ***************************************************************************** JCAROUSEL : 1 Element Ã  la fois  */
function jCarouselScrollOne() {
	if( $(".jCarouselScrollOne").length < 1 ) return false;
	$(".jCarouselScrollOne")
		.jcarousel({scroll:1})
	    .parents(".jCarouselParent").css('left','0');
}
/* ***************************************************************************** JCAROUSEL : 4 Elements Ã  la fois  */
function jCarouselScrollFour() {
	if( $(".jCarouselScrollFour").length < 1 ) return false;
	$(".jCarouselScrollFour")
		.jcarousel({scroll:4})
	    .parents(".jCarouselParent").css('left','0');
}
/* ***************************************************************************** JCAROUSEL : 4 Elements Ã  la fois  */
function jCarouselHpW9Replay() {
	if( $(".jCarousel-HP-W9-replay").length < 1 ) return false;
	var nbItem = $(".jCarousel-HP-W9-replay li").length;
	$(".jCarousel-HP-W9-replay")
		.jcarousel({scroll:4, start: nbItem})
	    .parents(".jCarouselParent").css('left','0');
	$(".jCarousel-HP-W9-replay li img").reflect({height:0.5,opacity:0.2});
}
/* ***************************************************************************** CYCLE PHOTOS */
function cyclePhotos() {
	if( $("#listePhotos").length < 1 ) return false;

	var nbrImagesTotal = imagesName.length;
	$('#numPhoto').text('1/' + nbrImagesTotal);
    
    var first = imagesName.pop();
    var second = imagesName.shift();
    var third = imagesName.shift();
    
    var firstTab = first.split('|');
    var secondTab = second.split('|');
    var thirdTab = third.split('|');
         
	$('#listePhotos')
		.append(
			 '<img src="' + imagesPath + firstTab[0] + '" alt="' + firstTab[1] + '" />'
			+'<img src="' + imagesPath + secondTab[0] + '" alt="' + secondTab[1] + '" />'
			+'<img src="' + imagesPath + thirdTab[0] + '" alt="' + secondTab[1] + '" />'
		)
		.cycle({
			fx:'fade',
			startingSlide: 1,
			prev:'#btPrev',
			next:'#btNext',
			timeout: 3000,
			before: onBefore,
			after: onAfter
		})
		.cycle('pause')
		.css('textIndent','0');


    function onBefore(curr, next, opts, fwd) {
            if (!opts.addSlide) return;

            if (opts.slideCount < nbrImagesTotal) {
				var nextImagesName = fwd ? imagesName.shift() : imagesName.pop();
                var nextImagesNameTab = nextImagesName.split('|');
				opts.addSlide('<img src="' + imagesPath + nextImagesNameTab[0] + '" alt="' + nextImagesNameTab[1] + '" />', fwd == false);
			}

		var index = $(this).parent().children().index(this);

		if (index==0) index = nbrImagesTotal;

		var $slide = $(next);
		var w = $slide.outerWidth();
		var h = $slide.outerHeight();
		$slide.css({
			marginTop: (380 / 2) - (h / 2),
			marginLeft: (676 / 2) - (w / 2)
		});
		$('#numPhoto').text((index) + '/' + nbrImagesTotal);
        $('#copyright-galerie').html($slide.attr('alt'));
        
		// Reload iframes
		/*jQuery("#pub-300 iframe")[0].src = jQuery("#pub-300 iframe")[0].src;
		jQuery("#colR .pub-partenaires iframe").each(function(){
			jQuery(this)[0].src = jQuery(this)[0].src;
		});
		jQuery("#pub768 iframe")[0].src = jQuery("#pub768 iframe")[0].src;*/
    };

    function onAfter(curr, next, opts, fwd) {
		var index = $(this).parent().children().index(this);

		if (index==1){
			var $slide = $(this);
            
            $('#copyright-galerie').html($slide.attr('alt'));
            
			setTimeout(function(){
				var w = $slide.outerWidth();
				var h = $slide.outerHeight();
				$slide.css({
					marginTop: (380 / 2) - (h / 2),
					marginLeft: (676 / 2) - (w / 2)
				});
			}, 300);
		}
    };


	$('#btDiaporama').toggle(
		function() {
			$('#listePhotos').cycle('resume');
			$(this)
				.addClass("resume")
				.text("Arrêter le diaporama");
			return false;
		},
		function() {
			$('#listePhotos').cycle('pause');
			$(this)
				.removeClass("resume")
				.text("Lancer le diaporama");
			return false;
		}
	);
}
/* ***************************************************************************** CYCLE : Transitions utilisÃ©s  */
/*
(function($) {
	// scrollHorz
	$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
		$cont.css('overflow','hidden').width();
		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);
*/
/* ****************************************************************************** SCROLL PANE */
function scrollPane(){
	if( $(".scroll-pane").length < 1 ) return false;
	$(".scroll-pane").jScrollPane({showArrows:true, scrollbarWidth :11, dragMaxHeight : 11, animateTo:false});
}
/* ***************************************************************************** FLASH PLAYER VIDEO */
/*
function playerVideo() {
	if( $(".page-videos #playerVideo").length < 1 ) return false;
		flashvars.appWidth = "630";
		flashvars.appHeight = "388";
		flashvars.domaine = "http://www.m6.fr/";
	var params = {};
		params.base = "http://video.m6.fr/players/flash/generic/";
		params.menu = "true";
		params.allowScriptAccess = "always";
		params.bgcolor = "#000";
		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 SPECTACLE*/
function playerVideoSpectacle() {
	if( $(".page-spectacles #playerVideo").length < 1 ) return false;
	var flashvars = {};
		flashvars.appWidth = "382";
		flashvars.appHeight = "215";
		flashvars.xmlLink = "http://www.m6.fr/config-630-388.xml";
		flashvars.domain = "http://www.m6.fr/";
	var params = {};
		params.base = "http://video.m6.fr/players/flash/generic/";
		params.menu = "true";
		params.allowScriptAccess = "always";
	var attributes = {};
	swfobject.embedSWF("http://video.m6.fr/players/flash/generic/m6webtv.swf", "playerVideo", "382", "215", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
}
/* ***************************************************************************** RSS FAQ TOGGLE */
function rssToggle() {
	if( $(".rss h3 a, .faq h2 a").length < 1 ) return false;
	$('.rss h3 a, .faq h2 a').toggle(
		function() {
			$(this).addClass("open").parent().siblings(".hide").show("fast");
			return false;
		},
		function() { 
			$(this).removeClass().parent().siblings(".hide").hide("fast");
			if ( $('#formulaire').css('display') == 'block' && $('.faq h2 a').index(this) == 16) {
				$('#formulaire').hide();
			}
			return false;
		}
	);
}
/* ***************************************************************************** SPECIAL POUR IE6 */
function specialIE6(){
	if ($.browser.msie && $.browser.version == 6.0) {
		/* simule le :hover sur le LI pour IE6 pour les menus dÃ©roulants */
        $("#item-0, #item-1, #item-2, #item-3").hoverClass ("hover"); 
		/* ifixpng : PNG sur IE6  */
		$.ifixpng('/img/pixel.gif');
		$('img[src$=.png], .png, .bloc-3col .degrade, #page-index #lesNews h2, .listes h2').ifixpng();
	}
}
/* ***************************************************************************** MON COMPTE */
function account(){
	if( $("#menu-mon-compte").size() > 0 ) $("#menu-mon-compte").tabs({ selected: 0 });
}
/* ***************************************************************************** OPEN PARENT */
function openParent(){
	jQuery(".thickboxParent").click(function(){
		parent.tb_show("", jQuery(this).attr("href"), "");
		return false;
	});
}
/* ***************************************************************************** GESTION ONCHANGE */
function changeSelect(){
	if( jQuery("#selectSaison").size() > 0 && jQuery("#selectEpisodes").size() > 0 && typeof tabEpisode != "undefined" ){
		jQuery("#selectSaison").change(function(){
			var num = jQuery(this).val();
			
			switch(num){
				case "1":
					var jsonCurrentSaison = tabEpisode.saison1;
					break;
				case "2":
					var jsonCurrentSaison = tabEpisode.saison2;
					break;
				case "3":
					var jsonCurrentSaison = tabEpisode.saison3;
					break;
			}
			
			var len = jsonCurrentSaison.length;
			var options = "";
			for(i=0; i<len; i++) {
				linkEpisode = 'saison-' + jsonCurrentSaison[i].saison + '-episode-' + jsonCurrentSaison[i].num_episode + '-' + jsonCurrentSaison[i].titre_format + '--id=' + jsonCurrentSaison[i].idepisode + '.html';
				options += '<option value="' + linkEpisode + '">Episode ' + jsonCurrentSaison[i].num_episode + ' - ' + jsonCurrentSaison[i].titre + '</option>';
			}
			
			$("#selectEpisodes").html(options);
			$("#selectEpisodes option:first").attr("selected", "selected");
			
			jQuery("#selectEpisodes").change(function(){
				document.location.replace( jQuery(this).val() );
			});
		});
	} else {
		jQuery(".changeSelect").change(function(){
			document.location.replace( jQuery(this).val() );
		});
	}
}
/* ***************************************************************************** FORMULAIRE CONTACT */
function formContact(){
	if(jQuery(".contact form").size < 1) return false;
	
	jQuery(".contact form").submit(function(){
		var error = false;
		
		function showError(elt){
			jQuery(elt).parent("label").addClass("erreur");
			jQuery(elt).addClass("erreur");
			error = true;
		}
		
		function checkEmail(elt){
			var reg = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
			if( !reg.test(jQuery(elt).val()) ){ showError(elt); }
		}
		
		jQuery(".contact form label").removeClass("erreur");
		jQuery(".contact form input, .contact form textarea").removeClass("erreur");
		
		if( jQuery("#nom").val() == "" ){ showError("#nom"); }
		if( jQuery("#prenom").val() == "" ){ showError("#prenom"); }
		jQuery("#email").val() == "" ? showError("#email") : checkEmail("#email");
		if( jQuery("#message").val() == "" ){ showError("#message"); }
		
		if(error){
			jQuery("#erreur").show();
		} else {
			$.ajax({
				type: "POST",
				url: "/contact.php",
				data: jQuery(".contact form").serialize(),
				success: function(data){
					if(data == "OK"){
						jQuery("#erreur").hide();
						jQuery(".contact form").css({ visibility: "hidden" });
						jQuery(".confirmation").fadeIn();
					}
				},
				error: function(error){
					console.log(error);
				}
			});
		}
		
		return false;
	});
}
/* ***************************************************************************** CAROUSEL GRILLE DES PROGRAMMES */
function grilleProg(){
	$("#jCarouselSemainier")
		.jcarousel({scroll:7, start:1, initCallback: function(carousel){
				carousel.list.css(carousel.lt, '0px');
				carousel.setup();
			}
		})
		.parents(".jCarouselParent")
		.css('left','0');
}
/* ********************************************** VOTE CANDIDATS */
function voteCandidat() {
	/* Callback Notation : auto-submit pour la fiche dÃ©tail */
	$('.auto-submit-star').rating({
		callback: function(value, link) {
			var inputs = $(this).parent().find(':input');
			var data = '';
			for(i=0; i<inputs.length; i++) {
				data += inputs[i].name+'='+inputs[i].value+'&'
			}
			$.ajax({
				type: "POST",
				url: "/rating.php",
				data: data+'&vote='+value,
				dataType: "json",
				success: function(data){
					$('#notation-voix').text(data.nb_votes+' voix');
					$("#notation-confim-"+data.id_cm).text("Votre vote a bien Ã©tÃ© enregistrÃ©");
					$('.auto-submit-star').rating('disable');
				},
				error : function(){
					$("#notation-confim").text("Impossible de prendre le vote en compte");
				}
			});
		}
	}); 
	
	/* liste des candidats : affichage des votes */
	$('.notation-lien').click(
		function()
		{
			$(this).parent().parent().parent().parent().find('.notation-liste').slideToggle();
			$('.auto-submit-star').rating('enable');
		});
	
}

/* ***************************************************************************** TELECHARGEMENT IE8 */
function downloadIE8(){
	if( jQuery.browser.msie && (jQuery.browser.version <= 7) )
		jQuery("#ie8").show();
}
function setPub(div, url){
	//document.write = function(t){ $(div).append(t); }
	$(div).append('<iframe src="http://www.m6.fr/pub.php?url=' + url + '" frameborder="0" width="300" height="250" scrolling="no"></iframe>');
}
$.fn.hoverClass = function(c) {
	return this.each(function(){
		$(this).hover( 
			function() { $(this).addClass(c);  },
			function() { $(this).removeClass(c); }
		);
	});
};
if(typeof console != "object"){
	var console = {
		'log':function(){}
	};
}
/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.1  (23/04/2008)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
 
 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */
 
(function($) {
	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/pixel.gif';
	};
	
	var hack = {
		ltie7  : $.browser.msie && $.browser.version < 7,
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};
	
	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			// in case rewriting urls
			var base = $('base').attr('href');
			if (base) {
				// remove anything after the last '/'
				base = base.replace(/\/[^\/]+$/,'/');
			}
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src')) {
					if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
						// use source tag value if set 
						var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
						// apply filter
						$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
						  .attr({src:$.ifixpng.getPixel()})
						  .positionFix();
					}
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					image = (base && image.substring(0,1)!='/') ? base + image : image;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .children().children().positionFix();
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */
	 
	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	 
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};
})(jQuery);
/*
	reflection.js for jQuery v1.02
	(c) 2006-2008 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
(function(a){a.fn.extend({reflect:function(b){b=a.extend({height:0.33,opacity:0.5},b);return this.unreflect().each(function(){var c=this;if(/^img$/i.test(c.tagName)){function d(){var j,g=Math.floor(c.height*b.height),k,f,i;if(a.browser.msie){j=a("<img />").attr("src",c.src).css({width:c.width,height:c.height,marginBottom:-c.height+g,filter:"flipv progid:DXImageTransform.Microsoft.Alpha(opacity="+(b.opacity*100)+", style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy="+(b.height*100)+")"})[0]}else{j=a("<canvas />")[0];if(!j.getContext){return}f=j.getContext("2d");try{a(j).attr({width:c.width,height:g});f.save();f.translate(0,c.height-1);f.scale(1,-1);f.drawImage(c,0,0,c.width,c.height);f.restore();f.globalCompositeOperation="destination-out";i=f.createLinearGradient(0,0,0,g);i.addColorStop(0,"rgba(255, 255, 255, "+(1-b.opacity)+")");i.addColorStop(1,"rgba(255, 255, 255, 1.0)");f.fillStyle=i;f.rect(0,0,c.width,g);f.fill()}catch(h){return}}a(j).css({display:"block",border:0});k=a(/^a$/i.test(c.parentNode.tagName)?"<span />":"<div />").insertAfter(c).append([c,j])[0];k.className=c.className;a.data(c,"reflected",k.style.cssText=c.style.cssText);a(k).css({width:c.width,height:c.height+g,overflow:"hidden"});c.style.cssText="display: block; border: 0px";c.className="reflected"}if(c.complete){d()}else{a(c).load(d)}}})},unreflect:function(){return this.unbind("load").each(function(){var c=this,b=a.data(this,"reflected"),d;if(b!==undefined){d=c.parentNode;c.className=d.className;c.style.cssText=b;a.removeData(c,"reflected");d.parentNode.replaceChild(c,d)}})}})})(jQuery);
/*
	jQuery Crossfade
	http://jqueryfordesigners.com/image-cross-fade-transition/
*/
(function ($) {
    $.fn.crossfade = function (startOptions, endOptions) {
        var defaults = {
            'start' : {
                'type' : 'mouseenter',
                'delay' : 200,
                'callback' : null,
                'condition' : function () { return true; }
            },
            
            'end' : {
                'type' : 'mouseleave',
                'delay' : 200,
                'callback' : null,
                'condition' : function () { return true; }
            }
        };
        
        if (typeof options == 'number') {
            options = {
                'start' : { 'delay' : options },
                'end' : { 'delay' : options }
            };
        }
        
        var settings = {};
        settings.start = $.extend({}, defaults.start, startOptions);
        settings.end = $.extend({}, defaults.end, endOptions);
        // return this;
        return this.each(function (i) { 
            var $$ = $(this);
            var targetImage = $$.css('backgroundImage').replace(/^url|[\(\)"']/g, '');
            var hiddenImage = $$.wrap('<span style="position: relative;"></span>')
                .parent()
                .prepend('<img>')
                .find(':first-child')
                .attr('src', targetImage);
                
            // CSS tweaks to position the starting image correctly
            if ($.browser.msie || $.browser.mozilla) {
                $$.css({
                    'position' : 'absolute', 
                    'left' : 0,
                    'background' : '',
                    'top' : this.offsetTop
                });
            } else if ($.browser.opera && $.browser.version < 9.5) {
                // opera < 9.5 has a render bug - so this is required to get around it
                // we can't apply the 'top' : 0 separately because Mozilla strips
                // the style set originally somehow...
                $$.css({
                    'position' : 'absolute', 
                    'left' : 0,
                    'background' : '',
                    'top' : "0"
                });
            } else {
                $$.css({
                    'position' : 'absolute', 
                    'left' : 0,
                    'background' : ''
                });
            }
            
            if (settings.start.type) {
                $$.bind(settings.start.type, function () {
                    if (settings.start.condition.call(this)) {
                        $(this).stop().animate({
                            opacity: 0
                        }, settings.start.delay);
                    }
                    if (settings.start.callback) return settings.start.callback.call(this);
                });
            }
            
            if (settings.end.type) {
                $$.bind(settings.end.type, function () {
                    if (settings.end.condition.call(this)) {
                        $(this).stop().animate({
                            opacity: 1
                        }, settings.end.delay);
                    }
                    if (settings.end.callback) return settings.end.callback.call(this);
                });
            }
        });
    };
    
})(jQuery);
