
//#################//
//### FONCTIONS ###//
//#################//

var initShadowMenu = function(){
	$(".twoCols .dropshadow").wrap("<div class='wrap0'><div class='wrap1'><div class='wrap2'>" +
"<div class='wrap3'></div></div></div></div>");
	$(".threeCols .dropshadow").wrap("<div class='wrap0'><div class='wrap1bis'><div class='wrap2'>" +
"<div class='wrap3'></div></div></div></div>");
}




//Formulaires
var initInputForm = function(form, idInput){
	if(form)
		form.reset();
	var el = $('#'+idInput);
	var searchHeaderValue = el.val();
	el.blur(function(){processInputFormBlur.call($(this),searchHeaderValue);});
	el.focus(function(){processInputFormFocus.call($(this),searchHeaderValue);});
}
	var processInputFormBlur = function(searchHeaderValue){
		if($(this).val()=='')	$(this).val(searchHeaderValue);
	}
	var processInputFormFocus = function(searchHeaderValue){
		if($(this).val()==searchHeaderValue)	$(this).val('');
	}

//Slideshow Header
var initSlideshowHeader = function(){
	var el = $('#slideshowHeader');
	if(el.length>0 && $('#slideshowHeader ul').children().size()>1)
		el.Horinaja({capture:'slideshowHeader',delai:0.3,duree:5,pagination:true});
}

//Accordéons

var initAccordeon = function(){
	var el = $('#accordeon');
	if(el.length>0)
		el.accordion({active:0, fillSpace:true});
	
	var elMenuLeft = $('#accordeonMenuLeft');
	if(elMenuLeft.length>0)
		elMenuLeft.accordion({active:'.on', navigation:true, navigationFilter:redirectLeftMenu, autoHeight:false});
		
	var elFAQ = $('#accordeonFAQ');
	if(elFAQ.length>0)
		elFAQ.accordion({ active:0});

	var elFiliale = $('#accordeonFiliale');
	if(elFiliale.length>0)
		elFiliale.accordion({active:0, autoHeight:false});
}
	var redirectLeftMenu = function(){
		$(this).click(function(){
			window.location.href=$(this).attr('href');
		});
	}

//Menu principal
var showSousmenu = function(el,idSousmenu){
	$(el).css('z-index','1000');
	$(el).children('a').addClass("on");
	$('#'+idSousmenu).css('display','');
}

var hideSousmenu = function(el,idSousmenu){
	$(el).css('z-index','10');
	$(el).children('a').removeClass("on");
	$('#'+idSousmenu).css('display','none');
}

//Resize Image Homepage
var initResizeBkgHome = function(){
	$(window).resize(resizeBkgHome);
	resizeBkgHome();
}
	var resizeBkgHome = function (){
		var paramRatioGlobal = 148;
		var global = $('#global');
		var img = $('#imgBkg');
		if(img.length){
			var ratioGlobal = global.width()/(global.height()-paramRatioGlobal);
			//var imgHeight = (img.height()>0)? img.height() : 832 ;
			var ratioImg = img.width()/ img.height();
			if(ratioImg>ratioGlobal){
				img.addClass('imgHeight');
				img.removeClass('imgWidth');
			}else{
				img.addClass('imgWidth');
				img.removeClass('imgHeight');
			}
		}
	}

//FlipFlap Homepage
var initFlipflap = function(){
	var el = $('#preview');
	if(el.length>0){
		el.click(flipflapHomeContent);
	}
}
	var flipflapHomeContent = function(){
		var preview = $('#preview');
		var imgBkg = $('#imgBkg');
		if(preview.height()==50){
			preview.animate({height:'180px'});
			imgBkg.animate({top:'-130'});
		}else{
			preview.animate({height:'50px'});
			imgBkg.animate({top:'0'});
		}
	}

//Slideshow de la homepage
var initSlideshowsHomepage  = function(){
	initCarouselHomepage();
	initSlideshowHPFooter();
}

var initCarouselHomepage = function(){
	var el = $("#slideHomepageTarget");
	if(el.length){
		el.jcarousel({scroll:1});
	}
}

var initSlideshowHPFooter = function(){
	var el = $("#slideHomepagePush");
	if(el.length){
		el.jcarousel({
						itemLoadCallback: function(){ $("#slideHomepagePush").children().eq(0).addClass('first');}
					});
	}
}

//Lien Xml des Flux RSS
var toggleXmlRss = function(el,id){
	var xml = $('#'+id);
	if(xml.length){
		if( $(el).hasClass('on') ){
			$(el).removeClass('on');
			xml.css('display','none');
		}else{
			$(el).addClass('on');
			xml.css('display','block');
		}
	}
}

//Navigation des mois de la page "Calendrier-Agenda Club Actionnaires"
var initSlideNavMois = function(){
	var el = $("#slideNav");
	if(el.length){
			el.jcarousel({size:el.children().size()});
	}
}

//Resize Texte
var sizeUp = function(){
	var el = $('.main');
	if(el.length){
		var zoomFontSize = getCurrentFontSize(el);
		var pas = 1/10 ;
		var newZoomFontSize = eval(zoomFontSize+pas);
		newZoomFontSize = (newZoomFontSize<2)? newZoomFontSize : zoomFontSize;
		el.css('fontSize',newZoomFontSize+'em');
	}
}
var sizeDown = function(){
	var el = $('.main');
	if(el.length){
		var zoomFontSize = getCurrentFontSize(el);
		var pas =  1/10 ;
		var newZoomFontSize = eval(zoomFontSize-pas);
		newZoomFontSize = (eval(newZoomFontSize)>0.5)? newZoomFontSize : zoomFontSize;
		el.css('fontSize',newZoomFontSize+'em');
	}
}
	var getCurrentFontSize = function(el){
		var fontSize = el.css('fontSize');
		if(!(fontSize.indexOf('em')>0)){
			fontSize = $(parseFloat(el.css('fontSize'))).toEm();
		}
		return parseFloat(fontSize);
	}
	
//Mise à jour de la mise en forme des tableaux
var updateTableau = function(){
	var el = $('.tableau tbody');
	if(el.length){
		el.children().each(function(i){
			if(i%2==0 && i!=0){
				$(this).addClass('even');
			}
		});
	}
}

//Initialisation des tooltips
var initTooltips = function(){
	var i=1;
	var el = $('#tooltip'+i);
	while(el.length){
		applyTooltip(i);
		i++;
	 	el = $('#tooltip'+i);
	}
}
	var applyTooltip = function(i){
		var el = $("#tooltip"+i);
		el.after('<div id="tooltip_txt'+i+'" class="tooltip" style="display:none;"><p>'+el.attr("title")+'</p></div>');
		el.tooltip({id:'#tooltip_txt'+i});
	}
	
//Initialisation du plan du site
var initSiteMap = function(){
	var arrH3 = new Array;
	var arrContent = new Array;
	var arrHeightContent = new Array;
	$('.planDuSite h3').each(function(i){
		//Récupération des éléments
		arrH3[i] = $(this);
		arrContent[i] = $(this).next('div.content');
		arrHeightContent[i] = arrContent[i].height();
		//Mise en forme de l'état initiale
		formatInitState(arrH3[i],arrContent[i]);
		//Apply Event OnClick
		applyToggleSiteMapContent(arrH3[i],arrContent[i],arrHeightContent[i]);	
	});
	//Bouton "Tout voir"
	var seeAllSiteMap = $('#seeAllSiteMap');
	if(seeAllSiteMap.length){
		seeAllSiteMap.click(function(){
			for(var i=0;i<arrH3.length;i++){
				showSiteMapContent(arrH3[i],arrContent[i],arrHeightContent[i])
			}
		});
	}
}
var formatInitState = function(h3,content){
	//On éteint les contenus
	content.height(0).css('overflow','hidden');
	//On ajoute le span pour le picto
	if(content.length)
		h3.append('<span></span>');
}
var applyToggleSiteMapContent = function(el,content,heightContent){
	$(el).click(function(){
		if(content.height()==0){
			showSiteMapContent($(this),content,heightContent);
		}else{
			hideSiteMapContent($(this),content);
		}
	});	
}
var showSiteMapContent = function(el,content,heightContent){
	content.animate({height:heightContent});
	el.addClass('on');
}
var hideSiteMapContent = function(el,content){
	content.animate({height:0});
	el.removeClass('on');
}

//Formulaire Contact
var initFormContact = function(){
	var el = $("#contact");
	var elPopin = $('.popinContact');
	if(el.length && !elPopin.length){
		el.popin({
			width:450,
			height: 620,
			className: "popinContact",
			onExit :function(){
				$('body, html').css('overflow','');	
			}
		});
	}
}

//Formulaire Contact Presse
var initFormContactPresse = function(){
	var el = $("#contactPresse");
	var elPopin = $('.popinContact');
	if(el.length && !elPopin.length){
		el.popin({
			width:450,
			height: 620,
			className: "popinContact",
			onExit :function(){
				$('body, html').css('overflow','');	
			}
		});
	}
}

var showContactFormContent = function(el){
	var valChoix = parseFloat($(el).val());
	var formRebond  = $('#blocRebond');
	var formContact = $('#blocContact');
	switch(valChoix){
		case 1: 
			formRebond.css('display','block');
			formContact.css('display','none');
			break;
		case 2:
			formRebond.css('display','none');
			formContact.css('display','block');	
			break;
		default:
			formRebond.css('display','none');
			formContact.css('display','none');
	}
}

//Contact Presse
var initPopinFormContactPresse = function(){
	var el = $("#contactPresse");
	var elPopin = $('.popinContactPresse');
	if(el.length && !elPopin.length){
		el.popin({
			width:450,
			height: 620,
			className: "popinContactPresse",
			onExit :function(){
				$('body, html').css('overflow','');	
			}
		});
	}
}

//Message d'erreur des formulaires de Contact
var toggleErrorMessageFormContact = function(isShow){
	var a  = window.parent.document.getElementById('aClose');
	var span = window.parent.document.getElementById('spanClose');
	if(isShow){
		if(a)
			a.style.display='none';
		if(span)
			span.style.display='';
		$('.error').addClass('on');
	}else{
		if(a)
			a.style.display='';
		if(span)
			span.style.display='none';
		$('.error').removeClass('on');
	}
}

var closeErrorMessageFormContact = function(){
	toggleErrorMessageFormContact(false);
}

//Layout Partager
var initLayoutPartager = function(){
	var el = $('#partager');
	var layout = $('#layoutPartager');
	var btclose = $('#layoutPartagerClose');
	if(el.length>0 && layout.length>0 && btclose.length>0){
		el.bind('mouseover',function(){
			layout.css('display','');	
			el.addClass('on');
		});
		btclose.click(function(){
			layout.css('display','none');	
			el.removeClass('on');
		});
	}
}

//Navigation page Dirigeants
var initNavDirigeants = function(){
	initNavDirigeants.cur = 1 ;	//élément courant
	var i=1;
	var el = $('#navAlphabet'+i);
	var cont = $('#navAlphabetContent'+i);
	while(el.length>0 && cont.length>0){
		applyNavDirigeant(el,cont,i);
		i++;
		el = $('#navAlphabet'+i);
		cont = $('#navAlphabetContent'+i);
	}
}

var applyNavDirigeant = function(el,cont,i){
	el.click(function(){
		$('#navAlphabetContent'+initNavDirigeants.cur).css('display','none');
		$('#navAlphabet'+initNavDirigeants.cur).removeClass('on');
		cont.css('display','');
		el.addClass('on');
		initNavDirigeants.cur = i;
	});
}

//Slide Axes Prioritaires
var initSlideAxesPrioritaires = function(){
	var el = $("#axePrioritaire");
	if(el.length){
		el.jcarousel({scroll:1});
	}
}

//Accessibilité : remise en forme pour le cas où javascript est activé
var initAccessibilite = function(){
	//Supprimer le bloc "Partage"
	var el = $('#partageAccessibilite');
	if(el.length)
		el.remove();
}

//Navigation XMLPage
var initXMLPage = function(){
	var arrPage = $('.ezxml_page');
	if(arrPage.length){
		//Define Content
		var content = new String();
		content	   += '<div class="articlePager">';
		content	   += '<div class="pagerTitle">Page</div>';
		content	   += '<ul id="pagination">';
		arrElements = new Array();
		arrPage.each(function(i){
			arrElements[i] = $(this);
			var cssClass = '';
			if(i==0){
				cssClass = 'on';
			}else{
				$(this).css('display','none');
			}
			content+=  '<li><a class="xml-page-a xml-page-a-'+eval(i+1)+' '+cssClass+'" href="javascript:showXMLPage('+eval(i+1)+');">'+eval(i+1)+'</a></li>';
		});
		content += '</ul>';
		content += '</div>';
		//Copy Content
		var lastEl = arrPage.last();
		lastEl.after(content);
		//Init params
		initXMLPage.cur = 1;
		initXMLPage.arrXMLPage = $('.ezxml_page');
	}
}

var showXMLPage = function(i){
	if(initXMLPage.cur != i){
		//Affiche la nouvelle page
		initXMLPage.arrXMLPage.eq(eval(i-1)).css('display','block');
		$('.xml-page-a-'+eval(i)).addClass('on');
		//Cache la page précédente
		initXMLPage.arrXMLPage.eq(eval(initXMLPage.cur-1)).css('display','none');
		$('.xml-page-a-'+eval(initXMLPage.cur)).removeClass('on');
		//Reinitialise l'index de page courante
		initXMLPage.cur = i;
	}
}

//Bouton pour fermer la popin Contact
var closePopinContactConfirm = function(){
	var element = window.parent.document.getElementById('aClose');
	if (document.createEvent) {
		//firefox + others
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent('click', true, true );
		element.dispatchEvent(evt);
	}else{
		//for IE
		var evt = document.createEventObject();
		element.fireEvent('onclick',evt);
	}
}

//Popin Player Flash
var initPopinPlayerFlash = function(){
	var el = $(".playerFlash");
	var elPopin = $('.popinPlayerFlash');
	if(el.length && !elPopin.length){
		el.each(function(){
			$(this).popin({
				width:506,
				height: 295,
				className: "popinPlayerFlash",
				onComplete : function(){
					//Reset overflow
					$('.popinPlayerFlash').css('overflow','');
					$('.popinPlayerFlash .popin-content').css('overflow','');
				},
				onExit :function(){
					$('body, html').css('overflow','');
				}
			});
		});
	}
}

//Change Background Homepage
var changeBackgroundHomepage = function(){
	if(typeof(arrBkgHome) != 'undefined' ){
		var iFloat = Math.random()*arrBkgHome.length;
		var i = Math.floor(iFloat);
		$('<img id="imgBkg" />')
    		.attr('src', arrBkgHome[i])
	   	 	.load(function(){
				$('.imgBkgBloc').html($(this));
				resizeBkgHome(); 
			});
	}
}

//Header Bourse
var showHeaderBourse = function(){
	var el = $('#details');
	if(el.length){
		el.addClass('on');
	}
}

var closeHeaderBourse = function(){
	var el = $('#details');
	if(el.length){
		el.removeClass('on');
	}
}

var updateBourseData = function(){
	//Appel AJAX
	$.ajax({
		   	url : '/system/include/header-footer-static/modules/bourse/cours.php',
			cache:false,
			complete : function(xhr,textStatus){
				processUpdateBourseData(xhr.responseText,textStatus);
			}
	});
}

var processUpdateBourseData = function(data,textStatus){
	//Tableau des données
	var arrData = new Array();
	var arrDataLib = Array("ticker", "name", "last", "variation", "date", "previous");
	//Init Xml Parser
	if (window.DOMParser){
	  	parser=new DOMParser();
	  	xmlDoc=parser.parseFromString(data,"text/xml");
	}else{ // Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  	xmlDoc.async="false";
	  	xmlDoc.loadXML(data);
	}
	//Parsing
	var nodeName = '';
	for(var i=0;i<arrDataLib.length;i++){
		nodeName = arrDataLib[i];
		arrData[nodeName] = new Array();
		for(var j=0;j<xmlDoc.getElementsByTagName(nodeName).length;j++){
			if(xmlDoc.getElementsByTagName(nodeName)[j].firstChild){
				arrData[nodeName][j] = xmlDoc.getElementsByTagName(nodeName)[j].firstChild.nodeValue;
			}else{
				arrData[nodeName][j] = '';
			}
		}
	}
	//Traitement
	var classVar = (parseFloat(arrData["variation"][0])>0)? 'plus' : 'moins' ;
	//Output
	$('.headerBourse .resume .titre').html(arrData["name"][0]);
	$('.headerBourse .resume .valeur').html(arrData["last"][0]+'&euro;');
	$('.headerBourse .resume .variable').html(arrData["variation"][0]+'%').addClass(classVar);
}


// toggle links
$(function(){
  $( '.toggle' ).each( function( i, container ){
    var $container = $( container );
    var $trigger   = $container.find( 'a' ).first();
    var $content   = $trigger.nextAll();

    $content.hide();
    $trigger.addClass( 'closed' );
    $trigger.click( function( event ){
      event.stopPropagation();
      if ( $container.hasClass( 'open' ) ){
        $content.slideUp();
        $container.removeClass( 'open' ).addClass( 'closed' );
      }

      else {
        $content.slideDown();
        $container.removeClass( 'closed' ).addClass( 'open' );
      }
    });
  });
});

function createRedirectCookie(nom, valeur) {
	  date=new Date;
	  date.setMonth(date.getMonth()+1);
	  document.cookie=nom+"="+escape(valeur)+
	  ((date==null) ? "" : ("; expires="+date.toGMTString()));
	}

function addFocusOnInputs() {
	$(document).ready(function()
	{
		$('input[type="text"]').addClass("idleField");
   		$('input[type="text"]').focus(function() 
   		{
   			$(this).removeClass("idleField").addClass("focusField");
		    if (this.value == this.defaultValue)
		    { 
		    	this.value = '';
			}
			if(this.value != this.defaultValue)
			{
    			this.select();
    		}
		});
		$('input[type="text"]').blur(function() 
		{
			$(this).removeClass("focusField").addClass("idleField");
		    if ($.trim(this.value) == '')
		    {
		    	this.value = (this.defaultValue ? this.defaultValue : '');
			}
		});
		
		$('textarea').addClass("idleField");
   		$('textarea').focus(function() 
   		{
   			$(this).removeClass("idleField").addClass("focusField");
		    if (this.value == this.defaultValue)
		    { 
		    	this.value = '';
			}
			if(this.value != this.defaultValue)
			{
    			this.select();
    		}
		});
		$('textarea').blur(function() 
		{
			$(this).removeClass("focusField").addClass("idleField");
		    if ($.trim(this.value) == '')
		    {
		    	this.value = (this.defaultValue ? this.defaultValue : '');
			}
		});
	});
}