$(window).load(function(){
/*
    $('#menu > ul > li').bind('focusin mouseenter', function(){
        menuHover($(this));
    });
*/
	
	
    $('.btFermer').click(function(){
        $("#alertMsg").slideUp();
    });
    
    $('#menu li:last-child').addClass('Last');
    

    //On fixe la taille du visuel
    //$('#middle > #contentTop').height($('#middle > #contentTop > div').outerHeight());

	// On fixe la taille du ul contenu toutes les petites vignettes afin de pouvoir le centrer :)
	$('.center #slideShow ul').css({'width': (129 * $('.center #slideShow ul li').size() ) + ($('.center #slideShow ul li').size()*9)});
	$('.center #slideShow ul').css({'margin': '0 auto'});


    $('.center #slideShow ul li').hover(function hoverIn(){
        $(this).addClass('mouseIn');
        return (false);
    }, function hoverOut() {
        $(this).removeClass('mouseIn');
        return (false);
    });
	
    
    toggleAlertShow();
    
    $.getScript("/fileadmin/templates/tv/js/iepngfix/iepngfix_tilebg.js");


	if($('#niv3 a.glossary,.carrefour_desc a.glossary').size()>0)
	{
		   var contenu = '';
		   var prev = '';
		   $('#niv3 a.glossary,.carrefour_desc a.glossary').each(function(p) {
				   contenu = $(this).find('dfn').text();
				   prev = $(this).prev();
				   $(this).remove();
				   prev.empty().text(contenu);
		   });
		   
	}
   
   if($('h1 a.glossary').size()>0)
   {
		   var contenu = '';
		   var prev = '';
		   $('h1 a.glossary').each(function(p) {
				   contenu = $(this).find('dfn').text();
				   //prev = $(this).prev();`
				   $(this).parent('h1').empty().text(contenu);
				   $(this).remove();
				   
		   });
		   
   }

	
});

// Gestion du menu megadromdown :)
$(document).ready(function(){

	$('#menu > ul > li').mouseenter(function(){
		menuMouseEnter($(this));
	});
	$('#menu > ul > li').mouseleave(function(){
		menuMouseLeave($(this));
	});
	

	$('.sousMenu').each(function(p) {
		var menuItem = $(this);
		var i = 0;
		$('.sousColMenu', menuItem).each(function(menuItem) {

			// On déplace :)
			$('.sousMenu:eq('+p+') .colMenu:eq('+i+')').append( $(this).find('div') );

			// On remove l'élément
			$(this).remove();
			i = (i + 1) % 4;
		});
	});
	
    var text_field = $('#keyWord').val();
    $('#keyWord').bind("focus",function() {
        $(this).val('');
    }).bind("blur",function() {
		var text_field_new = $(this).val();
		if( text_field_new!='' && text_field_new!= text_field){
			$(this).val(text_field_new);
		}else{
			$(this).val(text_field);
		}
    });
    
	
});

function toggleAlertShow(){
    if($("#alertShow").length>0){
        $("#contentTop").hide();
        return;
    }
}

/** Moteur de recherche, suggestion JS **/
jQuery(document).ready(function(){
	var language = document.location.pathname.split('/');
	if( language[1] == 'en' ) { language[1] = '1'; } else { language[1] = '0'; }
	var tx_solr_suggestUrl = "http://"+window.location.hostname+"/?eID=tx_solr_suggest&id=136&L="+language[1];

	// Change back to the old behavoir of autocomplete
	// http://jqueryui.com/docs/Upgrade_Guide_184#Autocomplete
	jQuery.ui.autocomplete.prototype._renderItem = function( ul, item ) {
			return jQuery( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a>" + item.label + "</a>" )
				.appendTo( ul );
		};

	jQuery('#searchFormId #keyWord').autocomplete(
		{
			source: function(request, response) {
				jQuery.ajax({
					url: tx_solr_suggestUrl,
					dataType: 'json',
					data: {
							// TODO
						term: request.term.toLowerCase()
					},
					success: function(data) {
						var rs     = [],
							output = [];

						jQuery.each(data, function(term, termIndex) {
							var unformatted_label = term + ' <span class="result_count">(' + data[term] + ')</span>';
							output.push({
								label : unformatted_label.replace(new RegExp('(?![^&;]+;)(?!<[^<>]*)(' +
									jQuery.ui.autocomplete.escapeRegex(request.term) +
									')(?![^<>]*>)(?![^&;]+;)', 'gi'), '<strong>$1</strong>'),
								value : term
							});
						});

						response(output);
					}
				})
			},
			select: function(event, ui) {
				this.value = ui.item.value;
				jQuery(event.target).closest('form').submit();
			},
			delay: 0,
			minLength: 3
		}
	);
});

/** Gestion de la tooltip glossaire **/
$(document).ready(function()
{

	if($(".itemSlider").length>0){
		$(window).resize(function(){
			$(".itemSlider.imgShow").each(function(){
				centerItemSlider($(this))
			});
			centerslider($(".GroupSliderContent"));
		}).trigger("resize");	
	}


    $('.center #slideShow ul li').click(function() {
       $('.center #slideShow ul li.selected').removeClass('selected');
       $(this).addClass('selected');
       loadMiddleVisuel($(this).index());
	   $('html:not(:animated),body:not(:animated)').animate({scrollTop: 0},'slow');
       return (false);
    });
	
	// Make sure to only match links to wikipedia with a rel tag
	$('a.glossary dfn').each(function()
	{
		var urlAjax = $(this).parent().attr('href');
		// We make use of the .each() loop to gain access to each element via the "this" keyword...
		$(this).qtip(
		{
			content: {
				// Set the text to an image HTML string with the correct src URL to the loading image you want to use
				text: '<img class="throbber" src="/fileadmin/templates/tv/images/throbber.gif" alt="Loading..." />',
				ajax: {
					url: urlAjax // Use the rel attribute of each element for the url to load
				},
				title: {
					text: '<a href="'+$(this).parent().attr('href')+'" title="'+$(this).text()+'">'+$(this).text()+'</a>', // Give the tooltip a title using each elements text
					button: true
				}
			},
			position: {
				at: 'bottom left', // Position the tooltip above the link
				my: 'top left'
				//viewport: $(window) // Keep the tooltip on-screen at all times
			},
			show: {
			  //event: 'click',
		      solo: true // Hide tooltips within the .qtips element when shown
		      //ready: true
		   },
			hide: {
				event: 'unfocus',
				delay: 500,
				fixed: true
			},
			events: {
				focus: function(event, api) {
				},
				show: function(event, api) {
				}
			},
			style: {
				classes: 'ui-tooltip-wiki ui-tooltip-light ui-tooltip-shadow'
			}
		});
		
	})

	// Make sure it doesn't follow the link when we click it
	.hover(function(event) { event.preventDefault(); });

});

/** Page Carrefour, rollover des blocs **/
$(window).load(function(){
/*
	    $(".center .linkMedia li").mouseover(function() { 
	        $(this).find(".carrefour_desc").fadeIn('normal'); 
	        $(this).hover(function() {
	            }, function(){
	                $(this).find(".carrefour_desc").fadeOut('normal'); 
	            });
	    });
*/
	    $(".center .linkMedia li").hover(function() { 
	        $(this).find(".carrefour_desc").fadeIn(600); 
	    },function(){
			 $(this).find(".carrefour_desc").stop(true,true).fadeOut(400); 
		});
});

/** Homepage, les blocs, rollOvers (x3) **/
$(window).load(function(){

	$("#home .block .aHover").each(function() {
		$(this).removeClass("aHover");
		var imgHover = $(this).find('img');
		var aImgHover = $(this).parent().find(".imgHover");
		
		imgHover.addClass('aHover');
		aImgHover.append(imgHover);
		$(this).remove();
		
		// IE6 c'est le mal donc on doit faire ca en JS, alors que pour les autres navigateurs la feuille de styles suffit
		
		/*
		if ($.browser.msie && parseInt($.browser.version, 10) < 7)
		{
			aImgHover.find('.aHover').css({
					'border'	: '2px solid white',
					'position'	: 'absolute',
					'top'		: '-20px',
					'left'		: '-38px',
					'z-index'	: '10'
				});
			
			aImgHover.mouseenter(function() {
				$(this).find('.aHover').show();
			}).mouseleave(function () {
				$(this).find('.aHover').hide();
			});
		}
		*/
	});
	
	$("#home .block .imgHover").hover(function (){
	
		var imgW = 369;
		var imgH = 185;

		$(this).find('.aHover').stop()
			.animate({
				marginTop: '-'+imgH/2+'px', 
				marginLeft: '-'+imgW/2+'px',
				top: '75px', /*ie*/
				left: '50%', 
				width: '369px', 
				height: '185px',
				zIndex: 100,
				opacity:1
			}, 200);	
	
    }, function () {
	
		var imgW = 300;
		var imgH = 150;

		$(this).find('.aHover').stop()
			.animate({
				marginTop: '-'+imgH/2+'px', 
				marginLeft: '-'+imgW/2+'px',
				top: '75px', /*ie*/
				left: '50%', 
				width: '300px', 
				height: '150px',
				opacity:0
			}, 200);	
			
    });
    
	
	
});




/** Pour la gestion du submit du moteur de recherche solr **/
$(document).ready(function(){
	$('#searchFormId').submit(function(){
		if( $("#tx_solr_type :selected").val() == '') {
			$("#tx_solr_type").remove();
		}
	});
});

function loadMiddleVisuel(idx)
{
	var itemSlider = $('#middle #contentTop .itemSlider').eq(idx);
	if(!itemSlider.is(":visible")){
		$('#middle > #contentTop > div > .GroupSliderContent').fadeOut('fast', function() {
			$('#middle #contentTop .itemSlider').hide();
			$('#middle #contentTop .itemSlider').eq(idx).show();
			$('#middle > #contentTop > div > .GroupSliderContent').fadeIn('fast', function() {
				//$('#middle > #contentTop').height( $('#middle > #contentTop').outerHeight() );
			});
		});
	}
}

//Savoir si on est sur IE
var IE6 = /msie|MSIE 6/.test(navigator.userAgent);
var IE7 = /msie|MSIE 7/.test(navigator.userAgent);
var IE = /msie|MSIE/.test(navigator.userAgent);

//Pour le menu

/*
var effetEnCours = false;

function menuHover(element){
    
	if (element.find('ul').length > 0 && !effetEnCours){	
		effetEnCours = true;
		
		var elementMenu = element.find('.listsousMenu'); 
		$('.listsousMenu').hide();
		if (IE6){
			hideSelect();
		}
		elementMenu.slideDown('fast', function() {			
			effetEnCours = false;
		
			element.siblings().bind('focusin', function(){
				elementMenu.slideUp('fast');
				element.siblings().unbind('focusin');
			});
		
			elementMenu.bind('mouseleave', function(){
				elementMenu.slideUp('fast', function () {
					if (IE6)
						showSelect();
				});
				elementMenu.unbind('focusin');
			});		
			

			$('html').bind('click', function(){
				elementMenu.slideUp('fast', function () {
					if (IE6)
						showSelect();
				});
				$('html').unbind('click');		 
			});	

		});
	}
	else {
		return false;
	}
}
*/
    
function menuMouseEnter(element){
    
	if (element.find('ul').length > 0){	
		var elementMenu = element.find('.listsousMenu'); 
		var elementsOhter = element.siblings().find('.listsousMenu'); 
		if(elementsOhter.is(":visible")){
			elementsOhter.stop(true,true).fadeOut(300);
			elementMenu.fadeIn(500);
		}else{
			elementMenu.slideDown(500);
		}
	}
}

function menuMouseLeave(element){
    
	if (element.find('ul').length > 0){	
		var elementMenu = element.find('.listsousMenu'); 
		elementMenu.stop(true,true).slideUp(300);
	}

}

	
	
// Internet Explorer 6
function hideSelect(){
if(document.all)//POUR IE, TELLEMENT BIEN CODE...CACHE LES SELECT QUI APPRAISSENT AU DESSUS
	{
	allSelect = document.getElementsByTagName('SELECT');
		for(i=0;i<allSelect.length;i++)
		allSelect[i].style.visibility="hidden";
	}
 }
function showSelect (){
if(document.all)//POUR IE, TELLEMENT BIEN CODE...
		{
		allSelect = document.getElementsByTagName('SELECT');
			for(i=0;i<allSelect.length;i++)
			allSelect[i].style.visibility="visible";
		}
} 

function openLayer(layer){
    initializeLayer(layer);     
    $(layer).fadeIn('slow');    
    bindLayerEvents(layer);
    if (IE6)
       hideSelect();      
}

function initializeLayer(layer) {
	if(typeof backPopin == 'undefined'){
           backPopin = $('<div>', {
               id:  'backPopin'
               }).appendTo('body');
       }

       var xHeight = $(document).height();
       var xWidth = $(window).width();

       $(backPopin).css({
           'width':xWidth,
           'height':xHeight,
           'opacity': 0.7
           
       });
       $(backPopin).fadeIn("slow");
       centerThis(layer);
}

function bindLayerEvents(layer) {
	//On ecoute le background, le clavier et les boutons fermer
    $('#backPopin, .closeLayerBt').bind('click', function (event){
        event.preventDefault();
        closeLayer(layer);
        $('#backPopin, .closeLayerBt').unbind();
    });
    $(document).keypress(function(e){
        if(e.keyCode==27){
            closeLayer(layer);
            $(this).unbind('keypress');
        }
    });
}

/**Fonction pour avoir la mÃªme hauteur de bloc**/
function sizeHeightBox(Elements) {	
	var sizeHeight = 0;
	
    $(Elements).each(function () {		  
		 if (sizeHeight <= $(this).height())
			 sizeHeight = $(this).height();
    });
    $(Elements).each(function () {		  
			 $(this).css('height', sizeHeight);
   });
};

//rÃ©cuperation d'une taille d'un Ã©lement pour que le second soit Ã©gal  
function twoElementsWidth(elementRef, elementChild, diff){     
  if (! IE6) 
    $(elementChild).css('width', ($(elementRef).width() + (typeof diff!= 'undefined' ? diff : 0)));              
 }

function closeLayer(id){
        $(backPopin).fadeOut('slow');
        $(id).fadeOut('slow');
        if (IE6)
          showSelect();
}

/***Pour centrer un layer au mileu de l'ecran ***/
function centerThis(element) {
	var windowHeight = $(window).height();
	var windowWidth = $(window).width();
	var elementHeight = $(element).height();
	var elementWidth = $(element).width();	

	var elementTop, elementLeft;

	if (windowHeight <= elementHeight) {
		elementTop = $(window).scrollTop();
	} else {
		elementTop = ((windowHeight - elementHeight) / 2) + $(window).scrollTop();
	}

	if (windowWidth <= elementWidth) {
		elementLeft = $(window).scrollLeft();
	} else {
		elementLeft = ((windowWidth - elementWidth) / 2) + $(window).scrollLeft();
	}			
	$(element).css({
			'position': 'absolute',
			'z-index': '101',
			'top': elementTop,
			'left': elementLeft
	});		
}

function paginateVideoLayer(layer) {
	var pagination = $('<div/>', {
      'class' : 'pagination'
    })
    .css({
    	height : '43px',
    	paddingTop : '10px',
      width : '854px'
    });
    
    pagination.appendTo($(layer));
    
    var nbVideos = 6;
    var linkWidth = parseFloat(pagination.width()) / (nbVideos + 2);
    
    var linkPrevious = $('<a/>', {
    	'class' : 'previous',
    	href : '#'
    })
    .css({
    	'float' : 'left',
    	height : pagination.height(),
    	textAlign : 'center',
    	width : linkWidth
    })
    .html('Prec.');
    
    var linkNext = $('<a/>', {
    	'class' : 'next',
    	href : '#'
    })
    .css({
    	'float' : 'left',
    	height : pagination.height(),
    	textAlign : 'center',
    	width : linkWidth
    })
    .html('Suiv.');
    
    linkPrevious.appendTo(pagination);
    
    var linksVideos = $('<div/>', {
    	'class' : 'videos'
    })
    .css({
    	'float' : 'left',
    	height : pagination.height(),
    	overflow : 'hidden',
    	position : 'relative',
    	width : linkWidth * nbVideos
    });
    
    var positionLink = 0;
    
    var images = [];
    
    $('#video-infos > div[class*=item]').each(function() {
    	var linkVideo = $('<a/>', {
    		'class' : 'video',
    		href : '#'
	    })
	    .css({
	    	height : pagination.height(),
    		left : positionLink + 'px',
			position : 'absolute',
    		textAlign : 'center',
	    	width : linkWidth
	    })
	    .click(function() {
			indexVideo = $(this).index();
			playVideo(indexVideo);
			return false;
	    });
	    
	    positionLink += linkWidth;
		var attrImg = $(this).find('.vdo_title').text();
   		$(this).find('img').clone().appendTo(linkVideo)
			.css({'width': '65', 'height': 'auto'})
			.attr({	alt:	attrImg,
					title:  attrImg});
    
    	linkVideo.appendTo(linksVideos);
   	});

    var videos = linksVideos.find('a.video');

	var paginationMoving = false;
	
    linkPrevious.click(function() {
    	if (parseFloat(videos.first().css('left')) < 0 && !paginationMoving)
    	{
    		paginationMoving = true;
    		linksVideos.find('a.video').animate({ left: '+=' + linkWidth }, 'fast', function() { paginationMoving = false; });
    	}
    	return false;
    });
    
    linkNext.click(function() {
    	if (parseFloat(videos.first().css('left')) > (nbVideos - videos.length) * linkWidth && !paginationMoving)
    	{
    		paginationMoving = true;
    		linksVideos.find('a.video').animate({ left: '-=' + linkWidth }, 'fast', function() { paginationMoving = false; });
    	}
    	return false;
    });
    
    linksVideos.appendTo(pagination);
    linkNext.appendTo(pagination);
}

/**Fonction Ajax pour la selection des avions*/
function ajax(handler, target){
	var _handler = $(handler);
	var _target = $(target);
	
	_handler.find('a').click(function(event){
		var urlTab = $(this).attr('href');
		
		if(! IE6){		
			event.preventDefault();				
			
			if($(this).parent().hasClass('selected') == false){					
				$(".ad-gallery, .ad-preloads").remove();
				_handler.find('li').removeClass('selected');
				$(this).parent().addClass('selected');
				var loader = $('<img>', {  
					 src:            'fileadmin/templates/tv/images/ajax-loader.gif',  
					 alt:           'Chargement',
					 css: {
						position:   'relative',
						left:       '49%'
					}
				});
				$($('#breadCrumb').find('a').last()).html($(this).text());
				$($('#breadCrumb').find('a').last()).attr('href', $(this).attr('href'));
				_target.animate({opacity: 'toggle'}, '400', function(){
					_target.html(loader).animate({opacity: 'toggle'}, '400', function(){
						$.get(urlTab, function(data) {							
							var $response = $(data).find(target);
							var $title = $(data).filter('title').text();
							document.title = $title;							
							 if ( history.pushState){
								history.pushState({}, $title, urlTab);								
							}
							_target.animate({opacity: 'toggle'}, '400', function(){
								_target.html($response).animate({opacity: 'toggle'}, '400', function(){
								initGallery();									
								}); 
							});	
						});			
					});					
				});			
			}
		}
	});	
}


function centerItemSlider (item) {
	var item = (item.is(":not(img)")) ? item.find("img:first") : item;
	
	if(item.width()>$(window).width()){
		var extraWidth = (item.width()-$(window).width())/2;
		item.css({"left":"-"+extraWidth+"px","position":"relative"});
	}else{
		item.css({"left":"auto"});
	}
}

function centerslider (slider) {
	slider.css({"overflow":"hidden"});
	var windowWidth = $(window).width();
	
	if($(window).width() <= 982){
		slider.css({"overflow":"hidden","width":"982px"});
	}else{
		slider.css({"overflow":"hidden","width":windowWidth+"px"});
	}

}


function addArrow (el) {
	var hasArrow = el.parent(".arrow").length>0;
	var hasSubList = el.next("ul").length>0;
	var arrow = $("<span class='arrow'></span>");
	if(hasSubList){
		if(!hasArrow){
			el.wrap(arrow);
		}
	}else{
		el.addClass("empty");
	}
}

function collapse (el) {
	var subList = el.next("ul");
	var otherSubList = el.parent().siblings().find("ul:visible");
	var otherArrow = el.parent().siblings().find(".arrow.active");
	var subListActive = subList.is(":visible");
	if(!subListActive){
		el.addClass("active");
		otherArrow.removeClass("active");
		otherSubList.slideUp(500);
		subList.slideDown(500);
	}else{
		el.removeClass("active");
		subList.slideUp(500);
	}
}

//#sitemap
$(document).ready(function(){
	$("#sitemap > ul > li > ul > li > a").each(function(){
		var $this = $(this);
		addArrow($this);
	})
	$("#sitemap > ul > li > ul > li > .arrow").click(function(){
		var $this = $(this);
		collapse($this);
		
	})
	$(".fonctionWeb li:eq(1)").hide();
});
	
	






