//Variables globales
var largeurFondImage;
var hauteurFondImage;
var menuOuvert;
var nextMenu;
var espacementNotes;
var espacementBoites;
var testCSS;

$(document).ready(function() {
	checkForCSS('allIsReady();');
});

function checkForCSS(f) {
	if($('#cssLoaded').css('display')=='none') {
		clearTimeout(testCSS);
		eval(f);
	}
	else {
		testCSS = window.setTimeout(function(){ checkForCSS('AllIsReady();'); },100);
	}
}

function allIsReady() {
	menuOuvert = false;
	espacementNotes = 10;
	espacementBoites = 28;
	
	//On récupère la taille de l'image de fond
	tailleImage();

	//On positionne les pictos
	positionnerPictos();
	
	//On positionne les notes et les cadres d'images si besoin
	positionnerNotes();
	positionnerCadresImages();
	
	//On positionne les colonnes
	positionnerTout();
	$(window).resize(positionnerTout);
	
	//On vérifie si un menu doit être ouvert
	verifierMenuOuvert();
	
	//On vérifie si on a besoin d'être loggué
	verifierLogin();
	
	//On crée les ancres pour les paragraphes si besoin
	ancresParagraphes();
} 

function positionnerTout() {
	if(jQuery.browser.safari && document.readyState != "complete") {
		setTimeout(arguments.callee, 50);
		return;
	}
	
	$("#menuGaucheListe div ul li ul.sousMenu").each(function() {
	    $(this).css('display','none');
	});
	$("#menuGaucheListe").hide();
	if($("#menuDroiteListe").length>0) {
		$("#menuDroiteListe").hide();
	}
	
	if($("#fondImage").width()>=1023) {
		$(window).unbind('scroll');
		if($("#menuGaucheBox").css('position')=="absolute") {
			$("#menuGaucheBox").css('position','fixed');
			$("#menuGaucheBox").css('top', 5);
			if($("#menuDroiteBox").length>0) {
				$("#menuDroiteBox").css('position','fixed');
				$("#menuDroiteBox").css('top', 5);
			}
		}
		$("#fondImage").css('width','100%');
		var xMenuGauche = (($("#fondImage").width() - 1023) * 0.5) + 5;
		$("#menuGaucheBox").css('left', xMenuGauche);
		var xColonneCentrale = ($("#fondImage").width() * 0.5) - 295;
		var xColonneDroite = xColonneCentrale + 605;
		$("div.pageCorps .colonneCentrale").css('left', xColonneCentrale);
		$("div.pageCorps .colonneDroite").css('left', xColonneDroite);
	}
	else {
		$(window).bind('scroll',scrollElements);
		if(buggySafariMobile()) { 
			$("#fondImage").css('position','absolute');
			if($("#fondTrame").length>0) { $("#fondTrame").css('position','absolute'); }
		}
		$("#menuGaucheBox").css('position','absolute');
		if($("#menuDroiteBox").length>0) { $("#menuDroiteBox").css('position','absolute'); }
		$("#menuGaucheBox").css('left', 5);
		var xColonneCentrale = 215;
		$("div.pageCorps .colonneCentrale").css('left', 215);
		$("div.pageCorps .colonneDroite").css('left', 820);
		
		if($(window).width()<1023) {
			$("#fondImage").width(1022);
			scrollElements();
		}
		else {
			$("#fondImage").css('width','100%');
		}
	}
	if($('.conteneurBoites').length>0) {
		$('.conteneurBoites').each(function() {
			var largeurImage = $(this).children(":first").children(":first").naturalWidth();
			$(this).css('left', xColonneCentrale - largeurImage + 652);
		});
	}
	
}

function ancresParagraphes() {
	if($('.colonneCentrale div p').length>0 && $('.colonneDroite #menuDroiteBox').length>0) {
		//alert($('.colonneCentrale div p').length);
		var currentURL = $('#currentURL').val();
		var listeAncres = "";
		var sepa = "";
		$('.colonneCentrale div p').each(function(index){
			$(this).prepend($('<a name="paragraphe_'+(index+1)+'"></a>'));
			listeAncres += '<a href="'+currentURL+'#paragraphe_'+(index+1)+'">'+sepa+(index+1)+'</a>';
			sepa = " ";
		});
		if($('#menuDroiteListe ul li').length>0) {
			if($('#menuDroiteListe ul li.active').length>0) {
				$('#menuDroiteListe ul li.active').append($('<div class="ancresParagraphes">'+listeAncres+'</div>'));
			}
			else {
				$('#menuDroiteListe ul').children('li:first-child').append($('<div class="ancresParagraphes">'+listeAncres+'</div>'));
			}
		}
		else {
			$('#menuDroiteListe ul').append($('<li><div class="ancresParagraphes">'+listeAncres+'</div></li>'));
		}
	}
}

//adds .naturalWidth() and .naturalHeight() methods to jQuery
//for retreaving a normalized naturalWidth and naturalHeight.
(function($){
var
props = ['Width', 'Height'],
prop;

while (prop = props.pop()) {
 (function (natural, prop) {
   $.fn[natural] = (natural in new Image()) ? 
   function () {
     return this[0][natural];
   } : 
   function () {
     var 
     node = this[0],
     img,
     value;

     if (node.tagName.toLowerCase() === 'img') {
       img = new Image();
       img.src = node.src,
       value = img[prop];
     }
     return value;
   };
 }('natural' + prop, prop.toLowerCase()));
}
}(jQuery));

function scrollElements() {
	if($("#fondImage").width()<1023) {
		var topScroll = $(window).scrollTop();
		if(buggySafariMobile()) { 
			$("#fondImage").css('top', topScroll);
			if($("#fondTrame").length>0) { $("#fondTrame").css('top', topScroll); }
		}
		$("#menuGaucheBox").css('top', topScroll + 5);
		if($("#menuDroiteBox").length>0) { $("#menuDroiteBox").css('top', topScroll); }
	}
}

function montrerMenu(button) {
	var elID = $(button).parent().attr('id');
	if($('#'+elID+' .menuListeblanc').length>0) {
		var el = $('#'+elID+' .menuListeblanc');
	}
	else {
		var el = $('#'+elID+' .menuListenoir');
	}
	$('#'+button.id).hide();
	el.show();
	el.mouseleave(function() {
		cacherMenu(this,button);
	});
}

function cacherMenu(el,button) {
	$(el).hide();
	$('#'+button.id).show();
}

function montrerSousMenu(a) {
	if(!menuOuvert) {
		if($(a).hasClass('open')==false) {
			menuOuvert = true;
		}
		$(a).next().slideDown(200);
		if($(a).hasClass('open')==false) {
			$(a).parent().mouseleave(function() {
				cacherSousMenu($(a).next(),a);
			});
		}
	}
	else {
		nextMenu = a;
	}
}

function cacherSousMenu(u,a) {
	nextMenu = null;
	$(u).slideUp(600, function() {
		menuOuvert = false;
		if(nextMenu!=a && nextMenu!=null) {
			montrerSousMenu(nextMenu);
		}
	});
}

function verifierMenuOuvert() {
	if($('.sousMenuLi a.open').length>0) {
		//montrerSousMenu($('.sousMenuLi a.open'));
		$('.sousMenuLi a.open').trigger('mouseover');
	}
}

function tailleImage() {
	var fondImage = document.getElementById("fondImage");
	largeurFondImage = fondImage.firstChild.naturalWidth;
	hauteurFondImage = fondImage.firstChild.naturalHeight;
}

function positionnerPictos() {
	$('.menuPicto').each(function() {
		var aFontHeight = $(this.parentNode).css('font-size');
		aFontHeight = aFontHeight.replace('px','');
		var aLineHeight = $(this.parentNode).css('line-height');
		aLineHeight = aLineHeight.replace('px','');
		var marginTop = ((aLineHeight - aFontHeight) * 0.5) + ((aFontHeight - $(this).height()) * 0.5);
		$(this).css('margin-top',marginTop);
	});
}

function positionnerNotes() {
	if($('.numero_note_dans_texte').length>0) {
		$('.numero_note_dans_texte').each(function(index) {
			var topNote = $('.numero_note_dans_texte')[index].offsetTop;
			$('.numero_note')[index].style.top = topNote+'px';
			if(index!=0) {
				if(topNote<($('.numero_note')[index-1].offsetTop + $('.numero_note')[index-1].offsetHeight)) {
					$('.numero_note')[index].style.top = $('.numero_note')[index-1].offsetTop + $('.numero_note')[index-1].offsetHeight + espacementNotes +'px';
				}
			}
		});
		if($('.colonneCentrale').hasClass('fondBlanc')) { $('.numero_note').addClass('fondBlanc'); }
		if($('.colonneCentrale').hasClass('fondNoir')) { $('.numero_note').addClass('fondNoir'); }
	}
}

function positionnerCadresImages() {
	if($('.boite_derriere').length>0) {
		$('.boite_derriere').each(function(index) {
			$('<div class="conteneurBoites" id="conteneurBoites_'+index+'"></div>').appendTo('.pageCorps');
			var topBoite = $(this)[0].parentNode.offsetTop;
			$('#conteneurBoites_'+index+'').css('top',topBoite);
			$(this).next().appendTo('#conteneurBoites_'+index+'');
			$(this).appendTo('#conteneurBoites_'+index+'');
			$('#conteneurBoites_'+index+'').css('position','absolute');
			if(index!=0) {
				if(topBoite<($('#conteneurBoites_' + (index-1))[0].offsetTop + $('#conteneurBoites_' + (index-1))[0].offsetHeight)) {
					$('#conteneurBoites_' + (index))[0].style.top = $('#conteneurBoites_' + (index-1))[0].offsetTop + $('#conteneurBoites_' + (index-1))[0].offsetHeight + espacementBoites +'px';
				}
			}
			$('#conteneurBoites_'+index+'').bind('mouseover',function() {
				$('#conteneurBoites_'+index+' .boite_derriere').hide();
				$('#conteneurBoites_'+index+' .boite_devant').show();
				$('#conteneurBoites_'+index+'').css('z-index','25');
			});
			$('#conteneurBoites_'+index+'').bind('mouseleave',function() {
				$('#conteneurBoites_'+index+' .boite_devant').hide();
				$('#conteneurBoites_'+index+' .boite_derriere').show();
				$('#conteneurBoites_'+index+'').css('z-index','20');
			});
		});
		
	}
}

function verifierLogin() {
	//Affichage de la boite de login
	  if($('#afficheLogin').length>0){
	    if($("#afficheLogin").html()==""){
	      var formHtml="<form id='login' name='login' method='post' action='index.php?affiche_login=1&template=login'>" +
	                     "<input type='hidden' value='login' name='module'>" +
	                     "<input type='hidden' value='login' name='action'>" +
	                     "<fieldset>" +
	                        "<p>" +
	                          "<label>Identifiant :</label>" +
	                          "<input type='text' maxlength='30' size='10' value='' name='login' id='login'>" +
	                        "</p>"+
	                        "<p>" +
	                          "<label>Mot de passe :</label>" +
	                          "<input type='password' maxlength='30' size='10' value='' name='pass' id='pass'>" +
	                        "</p>" + 
	                     "</fieldset>";
	                   "</form>";
	      $("#afficheLogin").html(formHtml);
	      $( "#afficheLogin" ).dialog({
	        title: "Authentification requise",
	        modal: true,
	        open: function(e,ui) {
	          //Active le post du formuliare sur ENTER
	        	$(this).keyup(function(e) {
	              if (e.keyCode == 13) {
	                 $('.ui-dialog-buttonpane button:last').trigger('click');
	              }
	          });
	        },
	        buttons: {
	          "OK": function() {
	            var login = $("input#login").val();  
	            var pass = $("input#pass").val();  
	            var dataString="module=login&action=login&login=" + login + "&pass="+ pass + "&ajaxLogin=1";
	            $.ajax({  
	              type: "POST",  
	              url: $("#login").attr("action"),  
	              data: dataString,  
	              success: function(result) {  
	                  if(result!="FAILED"){
	                    window.location=result;
	                  }else{
	                  	$("#afficheLogin").html("<p class='error'>Erreur d'authentification. Veuillez ré-essayer</p>" + formHtml );
	                  }
	              }  
	            });  
	            
	          }
	        },
	        close: function() {
	          
	        }
	      });
	    }
	  }
	}

function buggySafariMobile() {
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
		return true;
	}
	else { return false; }
}

// fonctions Célio
function MM_changeProp(objId,x,theProp,theValue) { //v9.0
	var obj = null; with (document){ if (getElementById)
	obj = getElementById(objId); }
	if (obj){
		if (theValue == true || theValue == false)
			eval("obj.style."+theProp+"="+theValue);
		else eval("obj.style."+theProp+"='"+theValue+"'");
	}
}
