// compatibilité jQuery / Prototype
//jQuery.noConflict();

//
var background_col = function(){
	var max = 0;
	var cols = $$('.col');
	var fonds = $A();
	
	max = cols.collect(function(col){
		cont_col = col.down('.cont_col');
		var tmp_fond = col.down('.fond_col');
		if(tmp_fond) {
			fonds.push(tmp_fond);
			cont_col.setStyle({'position':'absolute'});
		}
		return cont_col.getDimensions().height; 
	}).max();
	
	max = ((max+3)/10)+'em';
	
	cols.invoke('setStyle', {'height':max});
	fonds.invoke('setStyle', {'height':max});
};

var nav="",navver="",OS="",flNav="type='application/x-shockwave-flash'";


function getEnv(){
	OS=navigator.platform.substr(0,3);
	nav=navigator.appName;
	var nver;
	switch(nav){
	case "Microsoft Internet Explorer":
		var reg=new RegExp("MSIE ([0-9]\.[0-9])");
		nver=navigator.userAgent.match(reg);
		nav="MSIE";
		if(OS=="Win")flNav="classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'";
		break;
	case "Netscape":
		nav="Mozilla";
		var reg=new RegExp("^Mozilla/.*rv:([0-9]\.[0-9])");
		nver=navigator.userAgent.match(reg)
		if(!nver){
			reg=new RegExp("Safari/([0-9.]+)$");
			nver=navigator.userAgent.match(reg)
			if(nver){nav="Safari"}
		}
		break;
	}
	navver=nver?nver[1]:'unknown';
}
Event.observe(window, 'load', getEnv);

function affichFlash(swf,width,height,noflash,params,nowrite){
	if(!params) params = '';
	noflash=(noflash)?"<div class='flashplayer' style='width:"+width+"px;height:"+height+"px;'>La dernière version du plugin <b>Macromedia&reg; Flash<\/b> n'est pas installée.<br><br>Merci de télécharger et d'installer la dernière version disponible <a href='http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&amp;Lang=French&amp;P5_Language=French' target='_blank'><b>ici<\/b><\/a><\/div>":"&nbsp;";
	var flash = "<object "+flNav+" width='"+width+"' height='"+height+"' data='"+swf+"' flashvars='"+params+"'>"+
	"<param name='quality' value='high'><param name='wmode' value='transparent'>"+
	"<param name='movie' value='"+swf+"'>"+
	"<param name='flashvars' value='"+params+"'>"+
	"<param name='allowscriptaccess' value='always'>"+ 
	noflash+"</object>";
	if(nowrite){
		return flash;
	}else{
		document.write(flash);
	}
}

function affichFlashFS(swf,width,height,noflash,params,nowrite,id){
	if(!params) params = '';
	if(!id) id = '';
	if(id) id = " id='"+id+"' ";
	
	noflash=(noflash)?"<div class='flashplayer' style='width:"+width+"px;height:"+height+"px;'>La dernière version du plugin <b>Macromedia&reg; Flash<\/b> n'est pas installée.<br><br>Merci de télécharger et d'installer la dernière version disponible <a href='http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&amp;Lang=French&amp;P5_Language=French' target='_blank'><b>ici<\/b><\/a><\/div>":"&nbsp;";
	var flash = "<object "+id+flNav+" width='"+width+"' height='"+height+"' data='"+swf+"' flashvars='"+params+"' allowfullscreen='true' allowscriptaccess='always'>"+
	"<param name='quality' value='high'>"+
	"<param name='movie' value='"+swf+"'>"+
	"<param name='flashvars' value='"+params+"'>"+
	"<param name='allowfullscreen' value='true'>"+
	"<param name='allowscriptaccess' value='always'>"+ 
	noflash+"</object>";
	if(nowrite){
		return flash;
	}else{
		document.write(flash);
	}
}

function OpenPopUp(nomPage,largeur,hauteur,opt){
	var top=(screen.height-hauteur)/2;
	var left=(screen.width-largeur)/2;
	window.open(nomPage,"","status=1,top="+top+",left="+left+",width="+largeur+",resize=no,height="+hauteur+","+opt);
}

function setCookie(nom, valeur){
	var argv=setCookie.arguments;
	var argc=setCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=nom+"="+escape(valeur)+
	((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
	((path==null) ? "" : ("; path="+path))+
	((domain==null) ? "" : ("; domain="+domain))+
	((secure==true) ? "; secure" : "");
}
function getCookieVal(offset){
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
function getCookie(nom){
	var arg=nom+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen){
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
		i=document.cookie.indexOf(" ",i)+1;
		if (i==0) break;
	}
	return null;
}


var FontSize = Class.create();
FontSize.prototype = {
	font_size : 2,

	initialize : function(){
		this.font_size = parseInt((getCookie('size'))) || 2;
		this.update(this.font_size);
	},
	plus : function(){this.update(this.font_size + 1);},
	minus : function(){	this.update(this.font_size - 1);},
	update : function(size) {
		if(size > 5) {size = 5}
		if(size < 0) {size = 0}
		
		var body = $$('body')[0];	 
		$R(0,5).each(function(x_size){
			body.removeClassName('s'+x_size); 
		})
		body.addClassName('s'+size);
		this.font_size = size;
		setCookie('size', size, null, '/');
	}
}
Event.observe(window, 'load', new Function('gFontSize = new FontSize();'));

/**
 * Place un bloc au centre de l'ecran
 * @param id id du bloc à centrer
 */
function center_bloc(id)
{
	var bloc_width		= jQuery('#'+id).width();
	var bloc_height		= jQuery('#'+id).height();
	var window_width	= jQuery(window).width();
	var window_height	= jQuery(window).height();
	var scroll_x		= jQuery(document.viewport).scrollLeft();
	var scroll_y		= jQuery(document.viewport).scrollTop();
	
	var pos_x = (window_width / 2) - (bloc_width / 2) + scroll_x;
	var pos_y = (window_height / 2) - (bloc_height / 2) + scroll_y;
	jQuery('#'+id).css('position', 'absolute');
	jQuery('#'+id).css('left', pos_x);
	jQuery('#'+id).css('top', pos_y);
}


/**
 * Affiche le bloc "envoyer a un ami"
 */
function showSendToFriend()
{
	var e = jQuery('#form_sendtofriend');
	e.show();
	center_bloc( e.attr('id') );
}

/**
 * Masque le bloc "envoyer a un ami"
 */
function hideSendToFriend()
{
	var e = jQuery('#form_sendtofriend');
	e.hide();
}

/**
 * Masque le bloc "envoyer a un ami"
 */
function hideSendToFriendResult()
{
	var e = jQuery('#form_sendtofriend_result');
	e.hide();
}

/**
 * Soumet le formulaire "envoyer a un ami"
 */
function submitSendToFriend()
{
	// on affiche le bloc de resultat
	jQuery('#form_sendtofriend_result').show();
	jQuery('#form_sendtofriend_result p').html('veuillez patienter...');
	center_bloc( 'form_sendtofriend_result' );

	// on recupere les donnees du formulaire
	var data = jQuery('#form_sendtofriend form').serializeArray();

	// verif des emails
	var regex_mail = new RegExp("^[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,6}$");
	tt = data[3].value.split(',');
	var valid = true;
	jQuery.each(tt, function(){
		if(!regex_mail.test(this))
		{
			jQuery('#form_sendtofriend_result p').html("L'adresse e-mail <b>"+this+"</b> est invalide<br/><a href='javascript:;' onclick='hideSendToFriendResult();'>Fermer</a>");
			center_bloc( 'form_sendtofriend_result' );
			valid = false;
		}
	});

	monemail = data[2].value;
	if(!regex_mail.test(monemail))
	{
		jQuery('#form_sendtofriend_result p').html("Votre adresse e-mail <b>"+monemail+"</b> est invalide<br/><a href='javascript:;' onclick='hideSendToFriendResult();'>Fermer</a>");
		center_bloc( 'form_sendtofriend_result' );
		valid = false;
	}

	if(!valid) return;

	// requete ajax
	jQuery.ajax({
		async: false,
		type: 'POST',
		data: data,
		dataType: 'json',
		url: '/envoyer-ami/envoyer',
		success: function(response, status){
			jQuery('#form_sendtofriend_result p').html(response);
			center_bloc( 'form_sendtofriend_result' );
		},
		error: function(){
			alert('Une erreur est survenue');
	 	}
	 });
}

/**
 * Changement le signet et affiche le teaser dans le carousel
 * @param numPage numéro de la page sélectionée
 * @param nbSignet nombre de signet dans le carousel
 */
function chgTeaserCarousel(numPage, nbSignet) {
	for (var i=1; i<=nbSignet; i++) {
		if (i == numPage) {
			jQuery("#page_"+i).css('display','block');
			jQuery("#numPage_"+i).removeClass("numPage");
			jQuery("#numPage_"+i).addClass("numPageActif");
		} else {
			jQuery("#page_"+i).css('display','none');
			jQuery("#numPage_"+i).removeClass("numPageActif");
			jQuery("#numPage_"+i).addClass("numPage");
		}
	}
}

/**
 * Jquery pour afficher le layer des popups
 * @param id bloc de la home
 * @param idLayer layer de la popup
 */

function layerHome(id, idLayer) {
	jQuery("#"+id).colorbox({inline:true, href:"#"+idLayer, opacity:0.7, close:""});
}

function verifRep(rep, brep){
	var repstr;
	if(brep == 1) 
		repstr = 'vrai';
	else
		repstr = 'faux';
	
	var annoncerep = "Dommage, la bonne réponse est "+repstr+'!';
	if(rep == brep)
		annoncerep = "Bravo, la bonne réponse est "+repstr+'!';
	jQuery("#rep").html(annoncerep);
}

/**
 * Lien sur des blocs avec une partie parametrable dans EDWAN
 * @param debutLien début du lien fixe
 * @param lien lien fin du lien parametré dans EDWAN
 */
function lienBloc(debutLien, lien){
	window.location.href= debutLien + lien;
}

/**
 * Change d'onglet su rle split screen de la home
 * @param index index de l'onglet (0,1,2,)
 * @param bg lien vers l'image de fond
 */
var indexCourant = 0;
function splitChange(index, bg)
{
	
	jQuery('.split_screen').css('background-image', 'url('+bg+')');

	jQuery('.split_screen .bottom div:eq('+indexCourant+')').hide();
	jQuery('.split_screen .bottom div:eq('+index+')').show();
	indexCourant = index;
	
	jQuery('.table .col1 .split_screen div.menu_droite div.blue_button').removeClass('blue_button');
	jQuery('.table .col1 .split_screen div.menu_droite div:eq('+index+')').addClass('blue_button');
}

function sommaireToggle(){
	//change l'icone
	jQuery('.sommaire h2 span.icon img').toggle();
	//affiche ou cache le contenu
	jQuery('#sommaire_ctn').toggle('fast');
}

/**
 * Change le fond de la  vignette 
 * @param id id de la vignette
 * @param action mouseover ou mouseout
 */
function vignetteAction(id, action){
	if(action == "on")
		jQuery('#'+id).css('background', "url('/img/mediatheque/legende_vignette_fond.gif') no-repeat 0px -88px");
	else
		jQuery('#'+id).css('background', "url('/img/mediatheque/legende_vignette_fond.gif') no-repeat 0px 0px");

}

/**
 * Affiche/Cache le sous menu des themes
 */
function btSelectTheme() {
	jQuery('.theme').toggle();
}