/* Fonctions utilsées sur font-vendome.fr */

/* 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;
    		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 == '');
}

/* Menu V8 */
var Menu = new Class({
	Implements : Options,
	options : {
		showMinLevel : 0,
		hideDelay : 300,
		morph : {
			showStyles : {opacity:1},
			hideStyles : {opacity:0},
			options : {link:'cancel',duration:200}
		},
		toggleOnClick : false
	},
	initialize: function(menu,options){
		this.setOptions(options);
		this.menu = document.id(menu);
		if (this.menu){
			this.items = document.id(menu).getChildren('li');
			this.items.each(function(item,i){
				item.i = i;
				item.link = item.getElement('a');
				item.link.addEvent('focus',this.showItem.bind(this,item));
				item.submenu = item.getElement('ul');
				if (this.options.showMinLevel>0){
					if (item.submenu) item.submenu.setStyle('display','block');
				}else if (this.options.toggleOnClick){
					item.addEvent('click',this.toggleItem.bind(this,item));
				}else{
					item.addEvents({mouseenter:this.showItem.bind(this,item),mouseleave:this.hideItem.bind(this,item)});
				}
				if (item.submenu){
					item.submenu.morph = new Fx.Morph(item.submenu,this.options.morph.options);
					var options = $merge(this.options);
					options.showMinLevel = options.showMinLevel-1;
					new Menu(item.submenu,options);
				}
			}.bind(this));
		}
	},
	showItem : function(item){
		this.timer = $clear(this.timer);
		item.link.addClass('hover');
		if (item.submenu){
			item.submenu.morph.start(this.options.morph.showStyles).chain(function(){item.submenu.setStyle('display','block');}.bind(this));
		}
		this.items.each(function(otherItem,j){
			if (item.i!=j) this.hideItemNow(otherItem);
		}.bind(this));
	},
	hideItem : function(item){
		this.timer = $clear(this.timer);
		this.timer = this.hideItemNow.bind(this,item).delay(this.options.hideDelay);
	},
	hideItemNow : function(item){
		if (item.link){
			item.link.removeClass('hover');
			if (item.submenu){
				item.submenu.morph.start(this.options.morph.hideStyles).chain(function(){item.submenu.setStyle('display','none');}.bind(this));
			}
		}
	},
	toggleItem : function(item){
		// TODO Fix
		//if (item.hasClass('hover')){
		//	this.hideItemNow(item);
		//}else{
			this.showItem(item);
		//}
	}
});

/* Gallery V15 */
/* TODO Recode to handle variable image width with SLIDE effect */
var SLIDE = 0, FADE = 1;
var Gallery = new Class({
	Implements : Options,
	options : {
		container : 'div',
		list : 'ul',
		items : 'li',
		prev : '.prev',
		next : '.next',
		auto : true,
		step : 1,
		delay : 3000,
		loop : true,
		links : 'ul.nav li a',
		linksEvent : 'click',
		linksRel : false,
		play : '.play',
		autoHide : true,
		tween : {'link':'cancel'},
		effect : SLIDE, // SLIDE | FADE
		pause : true
	},
	initialize : function(element,options){
		this.element = document.id(element);
		this.setOptions(options);
		this.prev = this.element.getElement(this.options.prev);
		this.next = this.element.getElement(this.options.next);
		this.play = this.element.getElement(this.options.play);
		this.links = this.element.getElements(this.options.links);
		this.container = this.element.getElement(this.options.container);
		this.list = this.container.getElement(this.options.list);
		this.items = this.list.getElements(this.options.items);
		this.itemWidth = this.items[0].getStyle('width').toInt()+this.items[0].getStyle('padding-right').toInt()+this.items[0].getStyle('padding-left').toInt();
		this.i = 0;
		this.maxStep = Math.ceil(this.items.length/this.options.step);
		if (this.maxStep>0){
			if (this.options.auto){
				this.start();
				if (this.options.pause) this.element.addEvents({'mouseenter':this.stop.bind(this),'mouseleave':this.start.bind(this)});
			}
			if (this.prev) this.prev.addEvent('click',this.scrollBy.bind(this,0));
			if (this.next) this.next.addEvent('click',this.scrollBy.bind(this,1));
			if (this.play) this.play.addEvent('click',function(){if (this.timer) this.stop(); else	this.start();}.bind(this));
			if (this.options.autoHide){
				this.element.getElements('.button').setStyle('opacity',0);
				this.element.addEvents({
					'mouseenter' : function(){
						$$(this.prev,this.next,this.play).fade('in');
					}.bind(this),
					'mouseleave' : function(){
						$$(this.prev,this.next,this.play).fade('out');
					}.bind(this)
				});
			}
		};
		if (this.options.effect==SLIDE){
			if (this.options.loop){
				this.items.clone().inject(this.list);
				this.items.clone().inject(this.list);
				this.list.setStyle('margin-left',-this.items.length * this.itemWidth * this.options.step);
			}
			this.list.tween = new Fx.Tween(this.list, this.options.tween);
			this.list.setStyle('width',this.itemWidth*3*this.items.length);
		}else{
			this.zIndex = this.items.length+1;
			for(var i=0;i<this.items.length;i++){
				this.items[i].set('tween',this.options.tween);
				this.items[i].setStyles({'position':'absolute','z-index':this.items.length-i});
			}
		}
		if (typeof(Slimbox)!='undefined') Slimbox.scanPage();
		if (this.links.length>0){
			this.links.each(function(link,j){
				link.addEvent(this.options.linksEvent,function(event){
					event.stop();
					this.stop();
					if (this.options.linksRel) j = this.getIndexByLink(link);
					this.scrollTo(j);
				}.bind(this));
			}.bind(this));
			this.link = this.links[0];
			this.link.addClass('selected');
		}
	},
	getIndexByLink : function(link){
		for(var i=0;i<this.items.length;i++){
			if (this.items[i].id==link.rel) return i;
		}
		return 0;
	},
	getLinkByIndex : function(j){
		if (this.options.linksRel){
			for (var i=0;i<this.links.length;i++){
				if (this.links[i].rel==this.items[j].id) return this.links[i];
			}
		}else{
			this.link = this.links[j];
		}
		return this.link;
	},
	scrollBy : function (direction){
		this.scrollTo(this.i+direction*2-1);
		return false;
	},
	scrollTo : function (index,callback){
		if (this.link) this.link.removeClass('selected');
		this.i = index;
		if (this.options.effect==SLIDE){
			this.list.tween.start('margin-left',-this.itemWidth * (this.i+this.items.length) * this.options.step).chain(function(){
				if (this.options.loop && Math.abs(this.i)>=this.maxStep){
					this.list.setStyle('margin-left',-this.items.length * this.itemWidth * this.options.step);
					this.i = (this.i+this.maxStep) % this.maxStep;
					if (callback) callback();
				}
			}.bind(this));
		}else if (this.options.effect==FADE){
			this.i = (this.i+this.maxStep) % this.maxStep;
			this.items[this.i].setStyles({'z-index':this.zIndex,'opacity':0});
			this.items[this.i].tween('opacity',1);
			this.zIndex++;
		}
		this.link = this.getLinkByIndex((this.i+this.maxStep) % this.maxStep);
		if (this.link) this.link.addClass('selected');
	},
	start : function(){
		if (this.play) this.play.addClass('stop');
		if (this.next) this.next.fireEvent('mouseenter');
		this.timer = this.scrollBy.bind(this,1).periodical(this.options.delay);
	},
	stop : function(){
		if (this.play) this.play.removeClass('stop');
		if (this.next) this.next.fireEvent('mouseleave');
		this.timer = $clear(this.timer);
	}
});

/* Marquee V5 */
var Marquee = new Class({
	Implements : Options,
	options : {
		isVertical : false,
		speed : 1,
		pause : {mouse:false,interval:false,duration:0},
		delay : 30
	},
	initialize : function(element,options){
		this.element = document.id(element);
		this.setOptions(options);
		this.content = this.element.getFirst();
		this.element.size = this.element.getSize();
		this.content.size = this.content.getSize();
		this.size = {x: this.element.size.x+this.content.size.x, y: this.element.size.y+this.content.size.y};
		this.position = {x: this.element.size.x, y: this.element.size.y};
		Number.prototype.mod = function(n) {return ((this%n)+n)%n;}
		if (this.options.pause && this.options.pause.mouse){
			this.element.addEvents({
				mouseenter : this.stop.bind(this),
				mouseleave : this.start.bind(this)
			});
		}
		this.start();
	},
	start : function (){
		this.thread = this.scroll.periodical(this.options.delay,this);
	},
	stop : function (){
		$clear(this.thread);
	},
	scroll : function (){
		if (this.options.isVertical){
			this.position.y = (this.position.y-this.options.speed+this.content.size.y).mod(this.size.y)-this.content.size.y;
			this.content.setStyle('top',this.position.y);
			if (this.options.pause && this.options.pause.interval && this.position.y%this.options.pause.interval==0) this.pause();
		}else{
			this.position.x = (this.position.x-this.options.speed+this.content.size.x).mod(this.size.x)-this.content.size.x;
			this.content.setStyle('left',this.position.x);
			if (this.options.pause && this.options.pause.interval && this.position.x%this.options.pause.interval==0) this.pause();
		}
	},
	pause : function(){
		this.stop();
		this.start.delay(this.options.pause.duration,this);
	}
});

/* PngFix V3 */
// TODO copy standard border style (border-radius style raise an error on IE)
var PngFix = new Class({
	initialize : function (element){
		var images = document.id(element||document.body).getElements('img');
		images.each(function(img){
			if (img.src.toUpperCase().contains('.PNG')){
				var span = new Element('span', {
					'class': img.className+' img',
					'styles': {
						'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+img.src+'\', sizingMethod=\'scale\')',
						'display': 'block',
						'width': img.width,
						'height': img.height
					}
				});
				span.setStyles(img.getStyles('position','top','left','z-index','width','height','padding','margin','text-align','vertical-align'));
				span.replaces(img);
			}
		});
	}
});

/* Article du catalogue (après chargement sur la page ou en ajax) */
var Article = new Class({
	initialize : function(element){
		element.getElements('#outils ul.images li a').each(function(lien){
			lien.addEvent('click',function(event){
				event.stop();
				document.id('loader').setStyle('display','block');
				var image = new Element('img');
				image.addEvent('load', function(){
					image.inject($('image').empty());
					document.id('loader').setStyle('display','none');
				});
				image.src = lien.href;
			});
		});
		var panorama = element.getElement('#outils #panorama a');
		if (panorama){
			panorama.addEvent('click',function(event){
				event.stop();
				/* Version 1 : Fichiers MOV, ne fonctionne pas sur IE ?! */
				/*var embed = new Element('embed',{
					'src':panorama.href,
					'wmode':'transparent',
					'pluginspage':'http://apple.com/quicktime/download/',
					'showlogo' : false
				});
				embed.inject($('image').empty());*/
				/* Version 2 : Animation Flash (swiff) */
				new Swiff(panorama.href, {
					container : 'image',
					width: document.id('image').getStyle('width'),
					height: document.id('image').getStyle('height'),
					params: {wmode: 'transparent',menu: 'false'}
				});
			});
		}
		/* TODO Ne fonctionne pas sur IE 7 ?! */
		var en_savoir_plus = element.getElement('#outils #en_savoir_plus a').addEvent('click',function(event){
			event.stop();
			var description = document.id('description');
			description.setStyle('visibility',description.getStyle('visibility')=='hidden'?'visible':'hidden');
		});
	}
});

/* Initialisation de la page */
window.addEvent('domready', function() {
	/* Menu*/
	new Menu('menu');
	/* Liens vers les articles en Ajax */
	var article = document.id('article');
	if (article){
		new Article(article);
		$$('ul.articles li a').each(function(a){
			a.addEvent('click',function(event){
				event.stop();
				document.id('loader').setStyle('display','block');
				new Request.HTML({
					method: 'get',
					url: a.href,
					onComplete: function (responseTree,responseElements,responseHTML,responseJavaScript) {
						responseElements.each(function(element){
							if(element.get('id') == 'article'){
								element.replaces(article);
								article = element;
								new Article(article);
								document.id('loader').setStyle('display','none');
							}
						});
					}
				}).send();
			});
		});
	}
	/* Carte des concessionnaires */
	var points = $$('#carte li');
	var distributeurs = $$('#distributeurs li');
	if (points && distributeurs){
		points.each(function(point,i){
			point.addEvent('mouseover',function(){
				distributeurs.each(function(distributeur,j){
					distributeur.removeClass('selected');
					points[j].removeClass('selected');
				});
				point.addClass('selected');
				distributeurs[i].addClass('selected');
			});
		});
	}
	/* Gallery */
	$$('.gallery').each(function(g){
		new Gallery(g,{autoHide:false,auto:false});
	});
	/* Animations Flash */
	$$('.flash').each(function(flash){
		new Swiff('/flash/'+flash.id+'.swf', {
		    container : flash.id,
			width: flash.getStyle('width'),
		    height: flash.getStyle('height'),
		    params: {
		        wmode: 'transparent',
		        menu: 'false'
		    }
		});
	});
	/* Marquees */
	$$('.marquee').each(function(m){
		new Marquee(m,{isVertical:true,pause:{interval:30,duration:3000}});
	});
	/* PngFix */
	if (Browser.Engine.trident4) new PngFix();
});

