// Fonctions utilisées sur l'ensemble du site

// Fonctions "standard" macromedia dreamweaver
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_validateForm() { //v3.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) {
  	test=args[i+2];
  	val=MM_findObj(args[i]);
    	if (val) {
    		nm=val.name;
		//alert(nm);
    		if (val.options){
    			if (val.options[val.selectedIndex].value=="")
    				errors+='- Vous devez choisir une valeur dans la boite de sélection '+nm+'.\n';
    		}else{
			if ((val=val.value)!="") {
				if (test.indexOf('isEmail')!=-1) {
					p=val.indexOf('@');
					if (p<1 || p==(val.length-1))
						errors+='- Le champ '+nm+' doit contenir une adresse mail valide.\n';
				} else if (test!='R') {
					num = parseFloat(val);
					if (val!=''+num)
						errors+='- Le champ '+nm+' doit contenir une valeur numérique.\n';
					if (test.indexOf('inRange') != -1) {
						p=test.indexOf(':');
						min=test.substring(8,p); max=test.substring(p+1);
						if (num<min || max<num)
						errors+='- Le champ '+nm+' doit contenir une valeur numérique comprise entre '+min+' et '+max+'.\n';
					}
				}
			} else if (test.charAt(0) == 'R')
				errors += '- Le champ '+nm+' est obligatoire.\n';
		}
    	}
  }
  if (errors)
  	alert('Le formulaire n\' a pas pu être validé pour les raisons suivantes :\n'+errors);
  document.MM_returnValue = (errors == '');
}

// Fonction permettant d'ouvrir une popup à l'adresse url de taille largeur par hauteur
function popup(url,largeur,hauteur){
	var f=window.open(url,"fenetre","height="+hauteur+",width="+largeur+",scrollbars=no");
	f.focus();
	return f;
}

/* Gallery photo V1*/
var Gallery = new Class({
	initialize : function (element){
		this.element = $(element);
		var photos = this.element.getElements("ul li");
		var nav = this.element.getElements(".nav");
		if (photos && photos.length>1){
			var effets = new Array();
			photos.i = 0;
			photos.each(function(photo,i){
				photo.set('tween',{"duration":1000, "wait":true});
				photo.setStyle('opacity',i>0?0:1);
			});
			if (nav.length>1){
				nav[0].addEvent('click',function(){
					$clear(timer);
					defiler(-1);
					timer = defiler.periodical(5000);
				});
				nav[1].addEvent('click',function(){
					$clear(timer);
					defiler();
					timer = defiler.periodical(5000);
				});
			}
			var afficher = function(i){
				photos[i].tween('opacity',1);
			};
			var cacher = function(i){
				photos[i].tween('opacity',0);
			};
			var defiler = function (){
				sens = (arguments.length>0)?arguments[0]:1;
				cacher(photos.i);
				photos.i = (photos.i+sens+photos.length)%photos.length;
				afficher(photos.i);
			}
			var timer = defiler.periodical(5000);
		}
	}
});

/* Lecteur audio V1 (nécessite audio_player.swf)
<a href="song.mp3" rel="audio">Song name</a>
*/
var Audio = new Class({
	Implement: Options,
	options:{
		id : "flash_audio_player",
		player : "/js/audio_player.swf"
	},
	initialize : function(element,options){
		this.element = $(element);
		this.player = new Swiff(this.options.player, {
			//id : this.options.id,
			container : new Element('div').inject(this.element),
			width: 0,
			height: 0,
			params: {wmode: 'transparent',menu: 'false'},
			vars : {
				url : this.element.getProperty('href')
			},
			callBacks : {
				onLoad : function(){
					this.loaded = false;
					this.play = false;
					this.player = $(this.player);
					this.element.addEvent('click',function(event){
						event.stop();
						if (this.play){
							this.player.stopAudio();//$(this.player.id).stopAudio();
							this.element.removeClass('play');
						}else{
							if (!this.loaded) this.player.loadAudio();//$(this.player.id).loadAudio();
							this.loaded = true;
							this.player.playAudio();//$(this.player.id).playAudio();
							this.element.addClass('play');
						}
						this.play = !this.play;
					}.bind(this));
				}.bind(this),
				onError : function(text){
					this.element.getNext('span').setProperty('html','Désolé, ce fichier audio n\'est pas disponible actuellement');
				}.bind(this)
			}
		});
		if (Browser.Plugins.Flash.version < 9){
			this.element.setStyle('display','none');
		}
	}
});

/* Initialisation de la page */
window.addEvent('domready', function() {
	var sousMenu = $('gauche');
	if (sousMenu){
		/* Sous Menu en Accordéon */
		var items = sousMenu.getChildren('li');
		var thread = null;
		sousMenu.toggle = function(item,_options){
			var options = {wait: false, duration: 500,transition:Fx.Transitions.Cubic.easeOut};
			if (_options) options = $extend(options,_options);
			items.each(function(other,j) {
				if(other!=item) {
					if (options.duration>0){
						other.set('tween',options);
						other.tween('height',other.minHeight);
					}else{
						other.setStyle('height',other.minHeight);
					}
				}
			});
			if (item){
				if (options.duration>0){
					item.set('tween',options);
					item.tween('height',item.maxHeight);
				}else{
					item.setStyle('height',item.maxHeight);
				}
				if (sousMenu.slide) sousMenu.slide.delay(options.duration);
			}
		}
		items.each(function(item,i) {
			var link = item.getElement("a");
			var menu = item.getElement("ul");
			item.maxHeight = item.getSize().y;
			item.minHeight = item.maxHeight-(menu?menu.getStyle("height").toInt():0);
			item.oldColor = item.getStyle('background-color');
			item.addEvents({
				"mouseenter" : function(){
					//item.get('tween').chain(function(){
					//	item.setStyle('background-color',item.oldColor);
					//});
					//item.tween('background-color','#ccc');
					$clear(thread);
					thread = (function(){
						//item.setStyle('background-color','#444');
						sousMenu.toggle(item,{duration:500});
					}).delay(500);
				},
				"mouseleave" : function(){
					$clear(thread);
					//item.setStyle('background-color',item.oldColor);
				}
			});
		});
		sousMenu.toggle(sousMenu.getElement('li.selected'),{duration:0});
		/* Faire suivre les sous menus avec le défilement vertical de la fenêtre */
		var marginOffset = sousMenu.getStyle('margin-top').toInt();
		var topOffset = sousMenu.getPosition().y;
		var bottomOffset = $('contenu').getStyle('height').toInt()-100;
		var screenHeight = window.getSize().y;
		var debug = new Element('div',{styles:{position:'fixed',background:'white',top:0,left:0}});
		debug.inject(document.body);
		sousMenu.slide = function(toTop){
			// TODO Simplifier...
			var menuHeight = sousMenu.getStyle('height').toInt();
			var screenTop = window.getScrollTop()-topOffset;
			var screenBottom = screenTop+screenHeight;
			var menuTop = sousMenu.getStyle('margin-top').toInt()+sousMenu.getStyle('border-top-width').toInt();
			//debug.innerHTML = 'marginOffset='+marginOffset+', topOffset='+topOffset+', bottomOffset='+bottomOffset+', screenHeight='+screenHeight+', menuTop='+menuTop+', menuHeight='+menuHeight+',screenTop='+screenTop+',screenBottom='+screenBottom;
			if (toTop || menuHeight<screenHeight || menuTop>screenTop){
				sousMenu.tween('margin-top',Math.max(Math.min(screenTop,bottomOffset-menuHeight),0)+marginOffset);
			}else if (menuTop<screenBottom-menuHeight && menuTop<bottomOffset-menuHeight){
				sousMenu.tween('margin-top',Math.max(Math.min(screenBottom-menuHeight,bottomOffset-menuHeight),0)+marginOffset);
			}
		}
		window.addEvent('scroll',sousMenu.slide);
	}

	/* Déplier/replier les articles */
	var articles = $$('ul.articles')[0];
	var toggle = $('toggle');
	if (toggle && articles){
		var folded = articles.className.indexOf('folded') != -1;
		toggle.set('text',folded?'Tout déplier':'Tout replier');
		toggle.addEvent('click',function(e){
			e.stop();
			articles.set('class','articles '+(folded?'unfolded':'folded'));
			folded = !folded;
			toggle.set('text',folded?'Tout déplier':'Tout replier');
		});
	}

	/* Caddie en Ajax (utilise la librairie catalogue.mootools.js de pro.ircf.fr) */
	new Catalogue.Caddie('caddie',{
		codeCatalogue: Catalogue.CODE_CATALOGUE,
		onAdd: function(button){
			button.getNext('span').setProperty('html','<small>Ajout en cours...</small><br/>');
		},
		onAddComplete: function(button){
			button.getNext('span').setProperty('html','<small><a href=\"#\">Article ajouté</a></small><br/>');
			(function(){button.getNext('span').setProperty('html','');}).delay(5000);
		}
	});

	/* Images des articles */
	$$('ul.images li a[rel="lightbox[image]"]').each(function(a){
		a.addEvent('mouseover',function(){
			var imageDetail = $('imageDetail');
			if (imageDetail.rel){
				imageDetail.href = this.href;
				imageDetail.getElement('img').src = this.href;
			}
		});
	});

	/* Interdire les clics droits sur les images */
	$$('img').addEvents({
		'contextmenu' : function(event){event.stop();return false;},
		'mousedown' : function(event){event.stop();return false;}
	});

	/* Gallery */
	$$('.gallery').each(function(e){		
		new Gallery(e);
	});

	/* Lecteur Audio */
	$$('a[rel=audio]').each(function(e){		
		new Audio(e);
	});
});
