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

/* Déclaration */

/* Menu V6 */
var Menu = new Class({
	Implements : Options,
	options : {
		showMinLevel : 0,
		hideDelay : 300,
		morph : {
			showStyles : {opacity:1},
			hideStyles : {opacity:0},
			options : {link:'cancel',duration:200}
		}
	},
	initialize: function(menu,options){
		this.setOptions(options);
		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{
				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));
			}
		}
	}
});

/* Gallery photo V3 */
var Gallery = new Class({
	Implements : Options,
	options : {
		container : 'div',
		list : 'ul',
		items : 'li',
		buttons : '.button',
		auto : true,
		step : 1,
		delay : 6000,
		containerEvents : null,
		itemEvents : null,
		loop : true
	},
	initialize : function(element,options){
		this.element = $(element);
		this.setOptions(options);
		this.buttons = this.element.getElements(this.options.buttons);
		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();
				this.element.addEvents({'mouseenter':this.stop.bind(this),'mouseleave':this.start.bind(this)});
			}
			this.buttons[0].addEvent('click',this.scroll.bind(this,[0]));
			this.buttons[1].addEvent('click',this.scroll.bind(this,[1]));
		};
		// Loop V2 : Copy items twice and move to 2nd instance at startup
		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.list.setStyle('width',this.itemWidth*3*this.items.length);
	},
	scroll : function (direction){
		// Loop V2 : setStyle AFTER tween when loop	
		this.i+=direction*2-1;
		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;
			}
		}.bind(this));
		return direction;
	},
	start : function(){
		this.buttons[1].fireEvent('mouseenter');
		this.timer = this.scroll.bind(this,[1]).periodical(this.options.delay);
	},
	stop : function(){
		this.buttons[1].fireEvent('mouseleave');
		this.timer = $clear(this.timer);
	}
});

/* Pulse V1 */
var Pulse = new Class({
	Implements : Options,
	options : {
		from : 0.6,
		to : 1,
		duration : 500
	},
	initialize : function (element,options){
		this.element = $(element);
		this.setOptions(options);
		this.element.fade(this.options.to);
		setTimeout(function(){
			var tmp = this.options.from;
			this.options.from = this.options.to;
			this.options.to = tmp;
			this.initialize(this.element, this.options);
		}.bind(this),this.options.duration);
	}
});

/* Googlemaps V2 */
var GoogleMaps = new Class({
	Implements : [Options],
	element : null,
	options : {
		markers : null,
		url : null,
		controls :{
			smallMap : true,
			type : true
		},
		icon : {
			image : "/wp-content/themes/echappee-belle/images/markerA.png",
			shadow : "/wp-content/themes/echappee-belle/images/shadow50.png",
			iconSize : new GSize(20, 34),
			shadowSize : new GSize(37, 34),
			iconAnchor : new GPoint(9, 34),
			infoWindowAnchor : new GPoint(9, 2),
			infoShadowAnchor : new GPoint(18, 25)
		},
		center : null,
		zoom : 9,
		markerDefaultEvents : {
			click : function(){
				this.openInfoWindowHtml(this.marker.text);
			}
		}
	},
	map : null,
	geocoder : null,
	icon : null,
	markers : [],
	initialize : function(element,options){
		this.element = $(element);
		this.setOptions(options);
		// Initialisation de l'API Google Maps
		this.geocoder = new GClientGeocoder();
		this.map = new GMap2(this.element);
		if (this.options.controls.smallMap) this.map.addControl(new GSmallMapControl());
		if (this.options.controls.type)  this.map.addControl(new GMapTypeControl());
		if (this.options.icon){
			this.icon = new GIcon();
			$extend(this.icon,this.options.icon);
		}
		if (this.options.markers) this.addMarkers(this.options.markers);
		if (this.options.url) this.loadMarkers(this.options.url);
		if (this.options.center) this.setCenter(this.options.center);
		document.onunload = GUnload;
	},
	addMarkers : function(markers){
		markers.each(function (marker){
			//alert('addMarkers : address='+marker.address+' lat='+marker.lat+' lng='+marker.lng);
			if (!marker.lat || !marker.lng){
				this.geoencode(marker);
			}else{
				this.addMarker(marker);
			}
		}.bind(this));
	},
	addMarker : function(marker){
		//alert('addMarker : address='+marker.address+' lat='+marker.lat+' lng='+marker.lng+', text='+marker.text);
		var gPoint = new GLatLng(marker.lat,marker.lng);
		var gMarker = new GMarker(gPoint, new GIcon(this.icon));
		gMarker.marker = marker;
		if (!marker.events) marker.events = this.options.markerDefaultEvents;
		if (marker.events){
			var eventsHash = new Hash(marker.events);
			eventsHash.each(function(eventFunction,eventName){
				GEvent.addListener(gMarker,eventName,eventFunction);
			});
		}
		this.markers.push(gMarker);
		this.map.addOverlay(gMarker);
		if (!this.options.center) this.setCenter(gPoint);
	},
	geoencode : function(marker){
		this.geocoder.getLatLng(
			marker.address,
			function(point) {
				if (!point) {
					//GLog.write("Adresse \"" + marker.address + "\" non trouvée");
				} else {
					marker.lat=point.y;
					marker.lng=point.x;
				}
				this.addMarker(marker);
			}.bind(this)
		);
	},
	loadMarkers : function(url){
		//alert(url);
		var result = [];
		GDownloadUrl(url, function(data) {
	        var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			//alert (markers.length);
			for (var i = 0; i < markers.length; i++) {
				result.push({
					lat : markers[i].getAttribute("latitude"),
					lng : markers[i].getAttribute("longitude"),
					address : markers[i].getAttribute("address"),
					text : this.innerXML(markers[i]),
					events: markers[i].getAttribute("events")
				});
			}
			this.addMarkers(result);
		}.bind(this));
	},
	setCenter : function(center){
		this.options.center = center;
		this.map.setCenter(center, this.options.zoom);
	},
	innerXML : function(node){
		return (node.xml || (new XMLSerializer()).serializeToString(node) || "").replace(
		new RegExp("(^<\\w*" + node.tagName + "[^>]*>)|(<\\w*\\/\\w*" + node.tagName + "[^>]*>$)", "gi"), "");
	}
});

/* Calendar V2 */
Date.prototype.getWeek = function() {
	var onejan = new Date(this.getFullYear(),0,1);
	return Math.ceil((((this - onejan) / 86400000) + onejan.getDay())/7);
}
Date.prototype.toString = function() {
	var day = this.getDate();
	if (day<10) day = "0" + day;
	var month = this.getMonth() + 1;
	if (month<10) month = "0" + month;
	return day + "-" + month + "-" + this.getFullYear();
}
Array.prototype.inArray = function(value) {
	for (var i = 0, l = this.length; i < l; i++){
		if (this[i] == value) return true;
	}
	return false;
}
var Calendar = function(_options){
	// Define the default options
	this.options = {
		id : "calendar",
		currentDate : new Date(),
		startDate : new Date(new Date().getFullYear()-1,0,1),
		endDate : new Date(new Date().getFullYear()+1,0,1),
		month : ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"],
		day : ["lundi","mardi","mercredi","jeudi","vendredi","samedi","dimanche"],
		week : "Sem",
		onpick : null,
		highlight : null
	}
	//Get the input options
	if (_options){
		if (_options.id) this.options.id =  _options.id;
		if (_options.currentDate) this.options.currentDate = _options.currentDate;
		if (_options.startDate) this.options.startDate = _options.startDate;
		if (_options.endDate) this.options.endDate = _options.endDate;
		if (_options.month) this.options.month = _options.month;
		if (_options.day) this.options.day = _options.day;
		if (_options.week) this.options.week = _options.week;
		if (_options.onpick) this.options.onpick = _options.onpick;
		if (_options.highlight) this.options.highlight = _options.highlight;
	}
	// Gets or create the container
	this.container = document.getElementById(this.options.id);
	if (!this.container){
		this.container = document.createElement("DIV");
		this.container.id = this.options.id;
		document.body.appendChild(this.container);
	}
	// Generate the calendar in the container
	this.generate = function(){
		// Create input buttons and select boxes
		var inputPrevious = document.createElement("INPUT");
		inputPrevious.type = "button";
		inputPrevious.value = "<";
		inputPrevious.calendar = this;
		inputPrevious.onclick = function(){this.calendar.previousMonth()};
		var selectMonth = document.createElement("SELECT");
		selectMonth.name = "month";
		selectMonth.calendar = this;
		selectMonth.onchange = function(){
			this.calendar.setMonth(this.options[this.selectedIndex].value);
		}
		for (var m=0;m<12;m++){
			var option = document.createElement("OPTION");
			option.value = m;
			option.selected = (m==this.options.currentDate.getMonth());
			option.appendChild(document.createTextNode(this.options.month[m]));
			selectMonth.appendChild(option);
		}
		var selectYear = document.createElement("SELECT");
		selectYear.name = "year";
		selectYear.calendar = this;
		selectYear.onchange = function(){
			this.calendar.setYear(this.options[this.selectedIndex].value);
		}
		for (var y=this.options.startDate.getFullYear();y<this.options.endDate.getFullYear();y++){
			var option = document.createElement("OPTION");
			option.value = y;
			option.selected = (y==this.options.currentDate.getFullYear());
			option.appendChild(document.createTextNode(y));
			selectYear.appendChild(option);
		}
		var inputNext = document.createElement("INPUT");
		inputNext.type = "button";
		inputNext.value = ">";
		inputNext.calendar = this;
		inputNext.onclick = function(){this.calendar.nextMonth()};
		// Add them into a paragraph
		var p = document.createElement("P");
		p.appendChild(inputPrevious);
		p.appendChild(selectMonth);
		p.appendChild(selectYear);
		p.appendChild(inputNext);
		// Create the calendar view
		var view = document.createElement("DIV");
		// Create the main form
		var form = document.createElement("FORM");
		form.appendChild(p);
		form.appendChild(view);
		this.container.appendChild(form);
		this.update();
	}

	// Update the calendar
	this.update = function (){
		// Create the caption
		var caption = document.createElement("CAPTION");
		caption.appendChild(document.createTextNode(this.options.month[this.options.currentDate.getMonth()]+" "+this.options.currentDate.getFullYear()));
		// Create the head
		var thead = document.createElement("THEAD");
		var tr = document.createElement("TR");
		var th = document.createElement("TH");
		th.appendChild(document.createTextNode(this.options.week));
		tr.appendChild(th);
		for (var d=0;d<7;d++){
			var th = document.createElement("TH");
			th.appendChild(document.createTextNode(this.options.day[d].substring(0,1).toUpperCase()));
			tr.appendChild(th);
		}
		thead.appendChild(tr);
		// Create the body
		var tbody = document.createElement("TBODY");
		var date = new Date(this.options.currentDate.getFullYear(),this.options.currentDate.getMonth(),1);
		for (var w=0;w<6;w++){
			var tr = document.createElement("TR");
			var th = document.createElement("TH");
			th.appendChild(document.createTextNode(date.getWeek()));
			tr.appendChild(th);
			for (var d=0;d<7;d++){
				var td = document.createElement("TD");
				if ((date.getDay()+6)%7==d && date.getMonth()==this.options.currentDate.getMonth()){
					// Day is highlighted if no highlight is defined or if current date matches a highlight date
					if (!this.options.highlight || this.options.highlight.inArray(date.toString())){
						td.className = "highlight";
						td.calendar = this;
						td.date = date.toString();
						td.onclick = function (){
							if (this.calendar.options.onpick){
								this.calendar.options.onpick(this.calendar,this.date);
							}
						};
					}
					td.appendChild(document.createTextNode(date.getDate()));
					date.setDate(date.getDate()+1);
				}
				tr.appendChild(td);
			}
			tbody.appendChild(tr);
		}
		// Create the table
		var table = document.createElement("TABLE");
		table.appendChild(caption);
		table.appendChild(thead);
		table.appendChild(tbody);
		// Replace the content of the view with the table
		var view = this.container.getElementsByTagName("DIV")[0];
		while (view.firstChild) view.removeChild(view.firstChild);  
		view.appendChild(table);
		// Update month and year pickers
		var pickers = this.container.getElementsByTagName("SELECT");
		pickers[0].selectedIndex = this.options.currentDate.getMonth();
		pickers[1].selectedIndex = this.options.currentDate.getFullYear()-this.options.startDate.getFullYear();
		
	}

	// Change current month or year
	this.setMonth = function (month){
		this.options.currentDate.setMonth(month);
		this.update();
	}
	this.setYear = function (year){
		this.options.currentDate.setYear(year);
		this.update();
	}
	this.previousMonth = function (){
		this.options.currentDate.setMonth(this.options.currentDate.getMonth()-1);
		if (this.options.currentDate.getTime()<this.options.startDate.getTime()){
			this.nextMonth();
		}
		this.update();
	}
	this.nextMonth = function(){
		this.options.currentDate.setMonth(this.options.currentDate.getMonth()+1);
		if (this.options.currentDate.getTime()>this.options.endDate.getTime()){
			this.previousMonth();
		}
		this.update();
	}
	
	// Generate and update the calendar
	this.generate();
}

// Open a calendar to pick a date and close it
var DatePicker = function (field,event){
	DatePicker.field = field;
	if (!this.calendar){
		this.calendar = new Calendar({
			onpick : function (_calendar,_date){
				if (DatePicker.field){
					DatePicker.field.value = _date;
					_calendar.container.style.display = "none";
				}
			}
		});
	}else{
		this.calendar.container.style.display = (this.calendar.container.style.display=="block")?"none":"block";
	}
	if (event){
		x = (navigator.appName.substring(0,3) == "Net") ? event.pageX : event.clientX + document.documentElement.scrollLeft;
		y = (navigator.appName.substring(0,3) == "Net") ? event.pageY+8 : event.clientY + document.documentElement.scrollTop;
		this.calendar.container.style.position = "absolute";
		this.calendar.container.style.left = x + "px";
		this.calendar.container.style.top = y + "px";
	}
}

/* Fonctions de vérification des formulaires */
// 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 == '');
}
// Fonctions de vérification pour des formulaires spécifiques
function verifierFormulaireNewsletter(){
	f=document.formulaire;
	if (document.formulaire.groupe[0].checked){
		// Vérifie le formulaire pour les particuliers
		MM_validateForm(
			'CodePostal','','R',
			'Ville','','R',
			'Mail_Internaute','','RisEmail'
		);
		return (document.MM_returnValue);
	}else{
		// Vérifie le formulaire pour les professionnels
		activiteValide=(f.Autre_Activite.value!="" || f.Activite.selectedIndex!=0);
		if (!activiteValide){
			alert("Choisissez ou saisissez une activité");
		}
		MM_validateForm(
			'Nom','','R',
			'Code_Postal','','R',
			'Ville','','R',
			'Mail_Internaute','','RisEmail'
		);
		return (activiteValide && document.MM_returnValue);
	}	
}
function verifierFormulaireBrochure(){
	f=document.formulaire;
	// Vérifie le formulaire pour les professionnels
	activiteValide=(f.Autre_Activite.value!="" || f.Activite.selectedIndex!=0);
	if (!activiteValide){
		alert("Choisissez ou saisissez une activité");
	}
	MM_validateForm(
		'Nom','','R',
		'Code_Postal','','R',
		'Ville','','R',
		'Mail_Internaute','','RisEmail',
		'Telephone','','R'
	);
	return (activiteValide && document.MM_returnValue);	
}
// Fonction permettant d'ouvrir une popup à l'adresse url de taille largeur, hauteur
var fenetre = null;
function popup(nom,url,largeur,hauteur){
    fenetre = window.open(url,nom,"resizable=no,height="+hauteur+",width="+largeur+",scrollbars=yes,status=no");
	fenetre.focus();
}
// Fonction pour modifier le pointage d'un formulaire vers une popup
function submitPopup(nom,form,largeur,hauteur){
	popup(nom,"about:blank",largeur,hauteur);
	form.target = nom;
}

// Facebook
function fbs_click(link) {
	//var u=location.href;
	//var t=document.title;
	//window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	//return false;
	window.open(link.href,'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

/* Initialisation */
window.addEvents({
	/* Au chargement du document... */
	'domready' : function(){
		/* Menu */
		new Menu("menu-menu-principal");
		/* Gallery */
		$$('.gallery').each(function(gallery){
			new Gallery(gallery);
		});
		/* GMarkers */
		var liens = $$('a.gmarker');
		if (liens.length>0){
			var googlemap = new Element('div',{id:'googlemap','class':'popup'});
			var div = new Element('div',{'class':'map'});
			var voile = new Element('div',{'class':'voile'});
			var fermer = function(){
					googlemap.setStyle('visibility','hidden');
					voile.setStyle('visibility','hidden');
			}
			voile.addEvent('click',fermer);
			googlemap.adopt([
				new Element('a',{
					'class':'close',
					'text':'Fermer',
					'events':{
						'click': fermer
					}
				}),
				div
			]);
			$(document.body).grab(googlemap);
			$(document.body).grab(voile);
			liens.each(function(lien){
				lien.addEvent('click',function(event){
					event.stop();
					new GoogleMaps(div,{markers:[{
						address:lien.rel,
						events:{
							click:function(){
								this.openInfoWindowHtml(lien.title);
							}
						}
					}]});
					googlemap.setStyle('visibility','visible');
					voile.setStyle('visibility','visible');
				});
			});
		}
		/* Calendar */
		$$(".date").each(function(element){
			element.setAttribute('autocomplete','off');
			element.onclick = function (event){DatePicker(this,event?event:window.event)};
		});
	},
	/* Au chargement complet de la page... */
	'load' : function(){
		/* Recalculer la hauteur de l'agenda suivant celle de la sidebar et du contenu */
		var agenda = $$('.agenda')[0], sidebar = $('sidebar'), content = $('content');
		if (agenda && sidebar && content){
			agenda.setStyle('height',Math.max(sidebar.getSize().y-Math.abs(content.getSize().y-agenda.getSize().y),agenda.getSize().y));
		}
	}
});

