/* Script client commun à toutes les pages du site */

/* Déclaration */

/* Gallery V13 */
/* 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 : '.button.prev',
		next : '.button.next',
		auto : true,
		step : 1,
		delay : 3000,
		loop : true,
		links : 'ul.nav li a',
		linksEvent : 'click',
		linksRel : false,
		play : '.button.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){
		for (var i=0;i<this.links.length;i++){
			if (this.links[i].rel==this.items[j].id) return this.links[i];
		}
		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);
	}
});

/* 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);
		//}
	}
});

/* PngFix V3 */
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);
			}
		});
	}
});

/* Hover */
var Hover = new Class({
	Implements : Options,
	options : {
		hoverClass : 'hover',
		houtClass : 'hout',
		emulateLink : true,
		morph : {link: 'cancel',duration:300}
	},
	initialize: function(elements,options){
		this.setOptions(options);
		this.elements = $$(elements);
		this.elements.each(function(e){
			if (this.options.emulateLink){
				var a = e.getElement('a');
				if (a){
					e.setStyle('cursor','pointer');
					e.addEvent('click', function(){
						location.href = a.href;
					});
				}
			}
			e.morph = new Fx.Morph(e,this.options.morph);
			e.houtSelector = elements + '.' + this.options.houtClass;
			e.hoverSelector = elements + '.' + this.options.hoverClass;
			e.addEvents({
				'mouseenter' : function(){
					e.morph.start(e.hoverSelector).chain(function(){e.addClass(this.options.hoverClass);e.removeClass(this.options.houtClass);}.bind(this));
				}.bind(this),
				'mouseleave' : function(){
					e.morph.start(e.houtSelector).chain(function(){e.removeClass(this.options.hoverClass);e.addClass(this.options.houtClass);}.bind(this));
				}.bind(this)
			});
		}.bind(this));
	}
});

/* Typewriter http://davidwalsh.name/mootools-typewriter */
var Typewriter = new Class({
  Implements: [Options],
  options: {
    container: document.id(document.body),
    message: '',
    delay: 30,
    cursor: 0,
		onComplete: null,
		word: false
  },
  initialize: function(options) {
    this.setOptions(options);
		this.parent = this.options.container.getParent();
  },
  start: function() {
		if (this.options.word){
    	this.timer = this.setWord.periodical(this.options.delay,this);
		}else{
    	this.timer = this.setLetter.periodical(this.options.delay,this);
		}
  },
	stop: function(){
		if (this.timer) clearTimeout(this.timer);
	},
  setLetter: function() {
    this.options.container.set('html',this.options.container.get('html') + this.options.message.charAt(this.options.cursor));
		this.options.container.position({x:0,y:Math.min(0,this.parent.getSize().y-this.options.container.getSize().y)});
    this.options.cursor++;
		if (this.options.cursor>=this.options.message.length){
			this.stop();
			if (this.options.onComplete) this.options.onComplete();
		}
  },
	setWord: function(){
		var space = this.options.message.indexOf(' ',this.options.cursor);
		var word = this.options.message.substring(this.options.cursor,space>0?space:this.options.message.length);
    this.options.container.set('html',this.options.container.get('html') + word + ' ');
		this.options.container.position({x:0,y:Math.min(0,this.parent.getSize().y-this.options.container.getSize().y)});
		this.options.cursor+= word.length+1;
		console.info('word = "'+word+'", word length = '+word.length+', cursor = '+this.options.cursor+', message length = '+this.options.message.length);
		if (this.options.cursor>=this.options.message.length){
			this.stop();
			if (this.options.onComplete) this.options.onComplete();
		}
	},
	write: function(msg){
		this.stop();
		this.options.message = msg;
    this.options.cursor = 0;
		this.options.container.set('html','');
		this.start();
	}
});

/* Initialisation */
window.addEvent('domready',function(){
	/* Menu */
	new Menu('menu',{hideDelay:150, morph : {options : {duration:100}}});
	/* Gallery */
	$$('#content .gallery.slide').each(function(gallery){
		new Gallery(gallery,{linksEvent:'mouseover',linksRel:true});
	});
	/* PNG fix */
	if (Browser.Engine.trident4) new PngFix();
	/* Hover */
	if (Browser.Engine.trident4) new Hover();
	/* Carte des commerciaux */
	var liens = $$('#content #map area');
	var contacts = $$('.contacts');	
	if (liens && contacts){
		liens.each(function(lien,i){
			lien.addEvent('click',function(){
				contacts.each(function(contacts,j){
					contacts.removeClass('selected');
					liens[j].removeClass('selected');
				});
				lien.addClass('selected');
				contacts[i].addClass('selected');
			});
		});
	}
	/* Accordéon (gamme de produits) */
	/* TODO Ajouter un effet de fondu */
	var selecteurs = $$('ul.menu_produits li');
	var elements = $$('div.famille');
	if (selecteurs && elements) {
		selecteurs.each(function(selecteur,i){			
			selecteur.addEvent('click',function(event){
				event.stop();				
				selecteur.toggleClass('not_selected');
				elements[i].toggleClass('not_selected');
			});
		});
		elements.each(function(element,i){
			element.getElement('h2').addEvent('click',function(){
				element.toggleClass('not_selected');
				selecteurs[i].toggleClass('not_selected');
			});
		});
	}
	/* Initialise le carousel 3D */
	var solutions = $$('#caracteristiques>.solution>ul>li');
	var produits = $$('#caracteristiques>.produit>ul>li');
	var carouselContainer = document.id('carousel-container');
	if (carouselContainer){
		var carouselSelect = function(index){
			//console.info('carouselSelect('+index+')');
			solutions.each(function(solution){
				solution.removeClass('selected');
			});
			produits.each(function(produit){
				produit.removeClass('selected');
			});
			solutions[index].addClass('selected');
			produits[index].addClass('selected');
			document.id('caracteristiques').slide('in'); // S'assurer que l'onglet caractéristiques est bien ouvert
		}
		var carousel = jQuery("#carousel").featureCarousel({
			carouselSpeed: 300,
			autoPlay: '0',
			onSelect: carouselSelect,
			trackerIndividual: false,
			trackerSummation: false
		  // include options like this:
		  // (use quotes only for string values, and no trailing comma after last option)
		  // option: value,
		  // option: value
		});
		jQuery("prev").click(function () {
		  carousel.prev();
		});
		jQuery("next").click(function () {
		  carousel.next();
		});
		carouselSelect(0);
	}
	
	/* Initialise le carousel 3D */
	/*var solutions = $$('#caracteristiques>.solution>ul>li');
	var produits = $$('#caracteristiques>.produit>ul>li');
	var carousel = document.id('carousel');
	if (carousel){
		var carouselSelect = function(index){
			//console.info('carouselSelect('+index+')');
			solutions.each(function(solution){
				solution.removeClass('selected');
			});
			produits.each(function(produit){
				produit.removeClass('selected');
			});
			solutions[index].addClass('selected');
			produits[index].addClass('selected');
			document.id('caracteristiques').slide('in'); // S'assurer que l'onglet caractéristiques est bien ouvert
		}
		jQuery("#carousel").CloudCarousel({			
				xPos: 128,
				yPos: 32,
				buttonLeft: jQuery("#prev"),
				buttonRight: jQuery("#next"),
				altBox: jQuery("#alt-text"),
				titleBox: jQuery("#title-text"),
				bringToFront: true,
				onSelect: carouselSelect
		});
		carouselSelect(0);
	}*/
	
	/* Configurateur : Faire parler la mascotte lorsqu'on survole un "data-enter", coche un "data-checked" ou envoie un "data-submit" */
	var bulle = document.id('bulle');
	var bouche = document.id('bouche');
	if (bulle && bouche){
		bulle.fade('hide');
		bulle.div = bulle.getElement('div');
		bulle.div.div = bulle.div.getElement('div');
		bulle.ouvrir = function(msg){
			bulle.fade('in');
			bulle.typewriter.write(msg);
			bouche.addClass('animee');
		}
		bulle.fermer = function(){
			bulle.fade('out');
			bouche.removeClass('animee');
		}
		bulle.typewriter = new Typewriter({container:bulle.div.div,onComplete:function(){bouche.removeClass('animee');}});
		bulle.fixe = bulle.div.div.get('html');
		bulle.ouvrir(bulle.fixe);
		/*$$('#content .data-enter').each(function(tip){ // $$('#content *[data-enter]') ne fonctionne pas...
			tip.addEvents({
				mouseenter : function(){
					bulle.ouvrir(tip.getProperty('data-enter'));
				},
				mouseleave : function(){
					bulle.fermer();
					if (bulle.fixe) bulle.ouvrir(bulle.fixe);
				}
			});
		});*/
		bulle.checked = false;
		$$('#content .data-checked').each(function(tip){ // $$('#content *[data-checked]') ne fonctionne pas...
			tip.addEvent('click',function(e){
				if (e.target.checked){
					bulle.fixe = tip.getProperty('data-checked');
					bulle.ouvrir(bulle.fixe);
					bulle.checked = true;
				}else{
					bulle.checked = false;
				}
			});
		});
		$$('#content .data-submit').each(function(tip){ // $$('#content *[data-submit]') ne fonctionne pas...
			tip.addEvent('submit',function(e){
				if (!bulle.checked){
					e.stop();
					bulle.ouvrir(tip.getProperty('data-submit'));
				}
			});
		});
	}
	/* Système d'onglets */
	var tabs = $$('ul.onglets li a');
	tabs.each(function(tab,i){
		tab.element = document.id(document.body).getElement(tab.getProperty('href'));
		tab.select = function(e){
			if (e) e.stop();
			tabs.each(function(tab2,j){
				if (i!=j){
					tab2.removeClass('selected');
					if (tab2.element) tab2.element.slide('out');
				}else{
					tab2.addClass('selected');
					if (tab2.element) tab2.element.slide('in');
				}
			});
		}
		tab.addEvent('click',tab.select);
	});
	if (tabs.length>0) tabs[0].select();
	/* Infobulle */
	jQuery('form ol li label[data-description]').each(function(){
		jQuery(this).qtip({
			content: jQuery(this).attr('data-description'), // Use the tooltip attribute of the element for the content
			position: {
				corner: {
					target: 'rightMiddle',
					tooltip: 'topLeft'
				}
			},
			style: { 
				width: 350,
				padding: 10,
				//background: '#A2D959',
				//color: 'black',
				//textAlign: 'center',
				border: {
					width: 2,
					radius: 4,
					color: '#bebebe'
				},
				tip: 'leftTop',
				name: 'light' // Inherit the rest of the attributes from the preset dark style
			}
		});
	});	
});

