//var scroller = new Fx.Scroll(window);

var Site = {
	
	start: function(){
		/*
		Site.setUpScrollAnchors();
		Site.liftmeup();
		
		*/
		//new SmoothScroll();
		new SmoothScroll({links: '.scroollers'});

		MooTools.lang.setLanguage('fr-FR');
		Locale.define("fr-FR","FormValidator",{
			required:"ce champs est requis.",
			email:'Veuillez saisir une adresse email valide.',
			url:"Veuillez saisir une URL, comme http://www.google.com.",
			errorPrefix:" ",
			warningPrefix:"Attention: ",
		});
		MooTools.lang.set("fr-FR","Date",{
			months:["janvier","f&eacute;vrier","mars","avril","mai","juin","juillet","ao&ucirc;t","septembre","octobre","novembre","d&eacute;cembre"],
			days:["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],
		});


		ReMooz.assign();
		// common
		/*
		$$('a.boxed img').each(function(element) {
			new ReMooz(element, {
				origin: element.getElement('img'),
				resizeOptions: {
					transition: Fx.Transitions.Back.easeOut,
					resizeLimit: {x: 600, y: 520},
					resizeOpacity: 0.4,
					hideSource: true
				}
			});
		});
		*/

		$$('a.boxed').each(function(element) {
			new ReMooz(element, {
				origin: element.getElement('img'),
				resizeOptions: {
					transition: Fx.Transitions.Back.easeOut,
					resizeLimit: {x: 600, y: 520},
					resizeOpacity: 0.4,
					hideSource: true
				}
			});
		});
		/* let's customize Remooz titles and alt display */
		/*
		ReMooz.prototype.options.generateTitle= function() {
			var title = this.options.title || this.element.getProperty('title');
			var text = this.options.alt || this.element.getProperty('alt');
			if (!title && !text) return false;
			//title = title.split(' :: ');
			if (title) 
				var ret = [new Element('h4').setHTML(title)];
			if(ret)
				 ret.push(new Element('p').setHTML(text));
			else 
				var ret = [new Element('p').setHTML(title)];
			return ret;
		}
		*/
		//Site.initMenu(); 
		if(document.id('commentor')) {
			var recapkey=document.id('recaptchor').getProperty('class');
			var captchascript = new Asset.javascript('http://api.recaptcha.net/js/recaptcha_ajax.js', {
				id: 'recaptcha-js', 
				onload: function(){
					Recaptcha.create(recapkey, "recaptchor", {
						theme : 'black',
						callback: Recaptcha.focus_response_field
					})
				}
			});
		}
		if(document.id('shop')) {
			var shopscript = new Asset.javascript('/tpl/darksea/js/shop.js', {id: 'shopjs'});
		}

		if($('massmail')) {
			var masscript = new Asset.javascript('/tpl/darksea/js/massmail.js', {id: 'massmail-js'});
		}

	},
	

	initMenu : function() {
		var menuitems = $$("#nav li");
		var slidefxs = [];
		//var colorfxs = [];
		
		menuitems.each(function(el, i){
			el.setStyle('opacity', '0');
			timer += 250;
			slidefxs[i] = new Fx.Style(el, 'opacity', {
				duration: 500,
				transition: Fx.Transitions.backOut,
				wait: false,
				onComplete: Site.createOver.pass([el, i])
			});
			slidefxs[i].start.delay(timer, slidefxs[i], 1);

		}, this);
	},
	createOver: function(el, i){
		var first = el.getFirst();
		var overfxs = new Fx.Styles(first, {'duration': 200, 'wait': false});
		var tocolor = 'ffffff';
		var fromcolor = '334664';
		el.addEvent('mouseover', function(){
			overfxs.start({
				'color': tocolor,
				'padding-right': 15
			});
		});
		el.addEvent('mouseout', function(){
			overfxs.start({
				'color': fromcolor,
				'padding-right': 5
			});
		});
	},

	/*
	setUpScrollAnchors: function(){
		$$('a.scroollers').each(function(lnk) {
			if(lnk.href.test("#")) {
				lnk.addEvent('click', function(){
					this.scrollTo(lnk.href.split('#')[1]);
				}.bind(this));
			}
		}, this);
	},
	
	scrollTo: function(element){
		if(this.scrollingTo != element) {
			this.scrollTries = 0;
			this.scrollingTo = element;
		} else this.scrollTries++;
		$clear(this.scrollTimer);
		if($(element)) scroller.toElement($(element));
		else
			if(this.scrollTries < 15) this.scrollTimer = this.scrollTo.pass(element, this).delay(100);
	},
	
	liftmeup : function() {

		var ScrollToTop = new Fx.Scroll(window);
		$$('a.totop').addEvent('click', function() { 
				ScrollToTop.toTop();
			});
		$$('a.skipcontent').addEvent('click', function() { 
				ScrollToTop.toElement('content');
			});
	
	}
	*/	
}

//window.addEvent('load', Site.start);
window.addEvent('domready', function() {
	Site.start();
	CheckForm.start();
	CheckComment.start();

});

sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

var CheckForm = {

	start : function(){
		if(document.id('messenger')) {
			document.id('submitter').addEvent('click', function(e){
				e.stop();
				CheckForm.CheckValue();
			});
		}

	},

	CheckValue : function() {

		var messenger = document.id('messenger').action;
		var contact = document.id('contact').value;
		var email = document.id('email').value;
		var emailmatch = document.id('emailmatch').value;
		var message = document.id('message').value;
		var lblcontact = document.id('lblcontact');
		var lblemail = document.id('lblemail');
		var lblemailmatch = document.id('lblemailmatch');
		var lblmessage = document.id('lblmessage');
		var contacte=true;
		var emaile=true;
		var emailmatche=true;
		var messagee=true;
		
		if(!contact) {
			contacte=false;
			lblcontact.addClass('warn');
			lblcontact.innerHTML = 'Veuillez indiquer votre nom';
		}
		else {
			contacte=true;
			lblcontact.removeClass('warn');
			lblcontact.innerHTML = 'Votre Nom';
		}
		if(!email) {
			emaile=false;
			lblemail.addClass('warn');
			lblemail.innerHTML = 'Veuillez indiquer votre Email';
		}
		else {
			if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))) {
				emaile=false;
				lblemail.addClass('warn');
				lblemail.innerHTML = 'Votre Email n\'est pas valide';
			}
			else {
				emaile=true;
				lblemail.removeClass('warn');
				lblemail.innerHTML = 'Votre Email';
			}
		}
		if(!emailmatch) {
			emaile=false;
			lblemailmatch.addClass('warn');
			lblemailmatch.innerHTML = 'Veuillez confirmer votre Email';
		}
		else {
			if (emailmatch!=email) {
				emailmatche=false;
				lblemailmatch.addClass('warn');
				lblemailmatch.innerHTML = 'Vos Emails ne correspondent pas ';
			}
			else {
				emailmatche=true;
				lblemailmatch.removeClass('warn');
				lblemailmatch.innerHTML = 'Veuillez inidquer une nouvelle fois votre adresse Email';
			}
		}
		if(!message) {
			messagee=false;
			lblmessage.addClass('warn');
			lblmessage.innerHTML = 'Veuillez indiquer un message.';
		}
		else {
			messagee=true;
			lblmessage.removeClass('warn');
			lblmessage.innerHTML = 'Votre Message';
		}
		if(messagee==false || !emaile || !emailmatche || !contacte) {
			return false;
		}
		else {
			if (messenger.search('='))
				var messengeruri=messenger+'&ajax=true';
			else 
				var messengeruri=messenger+'?ajax=true';
			
			CheckForm.FrmSubmit(document.id('messenger'));
		}
	
	},

	/*
	loadUrl : function(theUri) {
		var Uri=theUri;
		// let's first fade content //
		var myPost=$('messenger').toQueryString();
		var FadeContentfx = new Fx.Style($('loader'), 'opacity', {
			wait: true,
			duration: 1000,
			onComplete: function() {
				new Ajax(Uri, {
					method: 'post',
					data: myPost,
					update: 'loader',
					evalScripts: true,
					onComplete: function() {
						var LiveContentFx = new Fx.Style($('loader'), 'opacity', {
									wait: true,
									duration: 1000
								}).start(0,1);
						}
				}).request();
			}
		}).start(1,0);
	}
	*/
	
	FrmSubmit : function(form) {
		var myPost=form.toQueryString();
		var formuri=form.get('action');
		if(formuri.contains('='))
			formuri+='&json=true';
		else 
			formuri+='?json=true';

		var responder=form.getFirst('div.responder');
		var blurry=form.getFirst('div.blurry');
		var fields=form.getChildren('input');
		var fsr = new Element('fieldset', {'class':'loading'});
		var fsrlegend = new Element('legend').set('text', 'Formulaire en cours de traitement...').inject(fsr);

		blurry.set('tween');

		var Postman=new Request.JSON({
			method: 'post', 
			url: formuri,
			data: myPost,
			//headers:{'Content-Type':'application/json charset=UTF-8'},
			evalScripts : true,
			evalResponse : true,
			onRequest:function() {
				responder.adopt(fsr);
				fields.setStyle('disable','true');
				blurry.tween('opacity',5); 
			},
			onSuccess:function(jsonObj) {
				blurry.tween('opacity',0); 
				fsr.removeClass('loading');
				blurry.empty();
				var message=new Element('h3').set('text', jsonObj.message).inject(fsr);
				fsrlegend.set('text', jsonObj.legend);
			}.bindWithEvent(this),
			onFailure:function() {
				fsr.removeClass('loading');
				fields.setStyle('disable','false');
				fsrlegend.set('text', 'Une erreur est survenue!');
				var message=new Element('h3').set('text', ' Veuillez cliquer une fois encore sur le bouton envoyer').inject(fsr);
				blurry.tween('opacity',1); 
			}
		}).send();
	}
	
	
};

var CheckComment = {

	start : function() {
		if(document.id('commentor')) {
			document.id('submitter').addEvent('click', function(e){
				e.stop();
				CheckComment.CheckValue();
			});
		}
	},

	CheckValue : function() {
		
		var commentor = document.id('commentor').action;
		var uri = document.id('uri').value;
		var comment = document.id('comment').value;
		var lblcomment = document.id('lblcomment');

		// two cases logged_in or not ?
		var userid = document.id('userid');
		if(userid) {
			if(!comment) {
				commente=false;
				lblcomment.addClass('warn');
				lblcomment.innerHTML = 'Veuillez remplir le champ commentaire.';
			}
			else {
				commente=true;
				lblcomment.removeClass('warn');
				lblcomment.innerHTML = 'Commentaire';
			}
			if(commente==false) {
				return false;
			}
			else {
				/*
				var commenturi=uri+'?ajax=true&topic=comment#commentor';
				CheckComment.loadUrl(commenturi);
				*/
				CheckComment.FrmSubmit(document.id('commentor'));
			}
		
		}
		else {
			var username = document.id('username').value;
			var email = document.id('email').value;
			var lblusername = document.id('lblusername');
			var lblemail = document.id('lblemail');
			var usernamee=true;
			var emaile=true;
			var commente=true;
			
			if(!username) {
				usernamee=false;
				lblusername.addClass('warn');
				lblusername.innerHTML = 'Veuillez choisir un nom';
			}
			else {
				usernamee=true;
				lblusername.removeClass('warn');
				lblusername.innerHTML = 'Nom';
			}
			if(!email) {
				emaile=false;
				lblemail.addClass('warn');
				lblemail.innerHTML = 'Veuillez indiquer votre Email';
			}
			else {
				if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))) {
					emaile=false;
					lblemail.addClass('warn');
					lblemail.innerHTML = 'Votre Email n\'est pas valide';
				}
				else {
					emaile=true;
					lblemail.removeClass('warn');
					lblemail.innerHTML = 'Votre Email';
				}
			}
			if(!comment) {
				commente=false;
				lblcomment.addClass('warn');
				lblcomment.innerHTML = 'Veuillez remplir le champ commentaire.';
			}
			else {
				commente=true;
				lblcomment.removeClass('warn');
				lblcomment.innerHTML = 'Commentaire';
			}
			if(commente==false || emaile==false  || usernamee==false) {
				return false;
			}
			else {
				CheckComment.FrmSubmit(document.id('commentor'));
			}
		}
	
	},

	FrmSubmit : function(form) {
		var myPost=form.toQueryString();
		var formuri=form.get('action');
		if(formuri.contains('='))
			formuri+='&json=true#commentor';
		else 
			formuri+='?json=true#commentor';


		var responder=form.getFirst('div.responder');
		var blurry=form.getFirst('div.blurry');
		var fields=form.getChildren('input');
		var fsr = new Element('fieldset', {'class':'loading'});
		var fsrlegend = new Element('legend').set('text', 'Commentaire en cours de traitement...').inject(fsr);
		var newcomment=document.id('commentx');
		newcomment.setStyle('opacity',0); 
		newcomment.addClass('comments'); 

		blurry.set('tween');

		var Postman=new Request.JSON({
			method: 'post', 
			url: formuri,
			data: myPost,
			//headers:{'Content-Type':'application/json charset=UTF-8'},
			evalScripts : true,
			evalResponse : true,
			onRequest:function() {
				responder.adopt(fsr);
				fields.setStyle('disable','true');
				blurry.tween('opacity',5); 
			},
			onSuccess:function(jsonObj) {
				// two cases according to captcha response //
				if(jsonObj.status == false) {
					Recaptcha.reload();
					fsr.removeClass('loading');
					fields.setStyle('disable','false');
					fsrlegend.set('text', 'Une erreur est survenue!');
					blurry.tween('opacity',1);
				}
				else {
					blurry.tween('opacity',0); 
					fsr.removeClass('loading');
					blurry.empty();
					var comcontent= new Element('div', { 'class':'comments-content', 'text':jsonObj.content});
					var cominfo= new Element('div', { 'class':'comments-info', 'text': jsonObj.info });
					newcomment.adopt(comcontent, cominfo).tween('opacity',1);
					var message=new Element('h3').set('text', jsonObj.message).inject(fsr);
					fsrlegend.set('text', jsonObj.legend);
				}
			}.bindWithEvent(this),
			onFailure:function() {
				fsr.removeClass('loading');
				fields.setStyle('disable','false');
				fsrlegend.set('text', 'Une erreur est survenue!');
				var message=new Element('h3').set('text', ' Veuillez cliquer une fois encore sur le bouton envoyer').inject(fsr);
				blurry.tween('opacity',1); 
			}
		}).send();
	}
};
/**
 * ReMooz - Zoomer
 *
 * Inspired by so many boxes and zooms
 *
 * @version		1.0
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

var ReMooz = new Class({

	Implements: [Events, Options, Chain],

	options: {
		link: null,
		type: 'image',
		container: null,
		className: null,
		centered: false,
		dragging: true,
		closeOnClick: true,
		shadow: (Browser.Engine.trident) ? 'onOpenEnd' : 'onOpen', // performance
		resize: true,
		margin: 20,
		resizeFactor: 0.95,
		resizeLimit: false, // {x: 640, y: 640}
		fixedSize: false,
		cutOut: true,
		addClick: true,
		opacityLoad: 0.6,
		opacityResize: 1,
		opacityTitle: 0.9,
		resizeOptions: {},
		fxOptions: {},
		closer: true,
		parse: false, // 'rel'
		parseSecure: false,
		temporary: false,
		onBuild: $empty,
		onLoad: $empty,
		onOpen: $empty,
		onOpenEnd: $empty,
		onClose: $empty,
		onCloseEnd: $empty,
		generateTitle: function(el) {
			var text = el.get('title');
			if (!text) return false;
			var title = text.split(' :: ');
			var head = new Element('h6', {'html': title[0]});
			return (title[1]) ? [head, new Element('p', {'html': title[1]})] : head;
		}
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.setOptions(options);
		if (this.options.parse) {
			var obj = this.element.getProperty(this.options.parse);
			if (obj && (obj = JSON.decode(obj, this.options.parseSecure))) this.setOptions(obj);
		}
		var origin = this.options.origin;
		this.origin = ((origin) ? $(origin) || this.element.getElement(origin) : null) || this.element;
		this.link = this.options.link || this.element.get('href') || this.element.get('src');
		this.container = $(this.options.container) || this.element.getDocument();
		this.bound = {
			'click': function(e) {
				this.open.delay(1, this);
				return false;
			}.bind(this),
			'close': this.close.bind(this),
			'dragClose': function(e) {
				if (e.rightClick) return;
				this.close();
			}.bind(this)
		};
		if (this.options.addClick) this.bindToElement();
	},

	destroy: function() {
		if (this.box) this.box.destroy();
		this.box = this.tweens = this.body = this.content = null;
	},

	bindToElement: function(element) {
		($(element) || this.element).addClass('remooz-element').addEvent('click', this.bound.click);
		return this;
	},

	getOriginCoordinates: function() {
		var coords = this.origin.getCoordinates();
		delete coords.right;
		delete coords.bottom;
		return coords;
	},

	open: function(e) {
		if (this.opened) return (e) ? this.close() : this;
		this.opened = this.loading = true;
		if (!this.box) this.build();
		this.coords = this.getOriginCoordinates();
		this.coords.opacity = this.options.opacityLoad;
		this.coords.display = '';
		this.tweens.box.set(this.coords);
		this.box.addClass('remooz-loading');
		ReMooz.open(this.fireEvent('onLoad'));
		this['open' + this.options.type.capitalize()]();
		return this;
	},

	finishOpen: function() {
		this.tweens.fade.start(0, 1);
		this.drag.attach();
		this.fireEvent('onOpenEnd').callChain();
	},

	close: function() {
		if (!this.opened) return this;
		this.opened = false;
		ReMooz.close(this.fireEvent('onClose'));
		if (this.loading) {
			this.box.setStyle('display', 'none');
			return this;
		}
		this.drag.detach();
		this.tweens.fade.cancel().set(0).fireEvent('onComplete');
		if (this.tweens.box.timer) this.tweens.box.clearChain();
		var vars = this.getOriginCoordinates();
		if (this.options.opacityResize != 1) vars.opacity = this.options.opacityResize;
		this.tweens.box.start(vars).chain(this.closeEnd.bind(this));
		return this;
	},

	closeEnd: function() {
		if (this.options.cutOut) this.element.setStyle('visibility', 'visible');
		this.box.setStyle('display', 'none');
		this.fireEvent('onCloseEnd').callChain();
		if (this.options.temporary) this.destroy();
	},

	openImage: function() {
		var tmp = new Image();
		tmp.onload = tmp.onabort = tmp.onerror = function(fast) {
			this.loading = tmp.onload = tmp.onabort = tmp.onerror = null;
			if (!tmp.width || !this.opened) {
				this.fireEvent('onError').close();
				return;
			}
			var to = {x: tmp.width, y: tmp.height};
			if (!this.content) this.content = $(tmp).inject(this.body);
			else tmp = null;
			this[(this.options.resize) ? 'zoomRelativeTo' : 'zoomTo'].create({
				'delay': (tmp && fast !== true) ? 1 : null,
				'arguments': [to],
				'bind': this
			})();
		}.bind(this);
		tmp.src = this.link;
		if (tmp && tmp.complete && tmp.onload) tmp.onload(true);
	},

	/**
	 * @todo Test implementation
	 */
	openElement: function() {
		this.content = this.content || $(this.link) || $E(this.link);
		if (!this.content) {
			this.fireEvent('onError').close();
			return;
		}
		this.content.inject(this.body);
		this.zoomTo({x: this.content.scrollWidth, y: this.content.scrollHeight});
	},

	zoomRelativeTo: function(to) {
		var scale = this.options.resizeLimit;
		if (!scale) {
			scale = this.container.getSize();
			scale.x *= this.options.resizeFactor;
			scale.y *= this.options.resizeFactor;
		}
		for (var i = 2; i--;) {
			if (to.x > scale.x) {
				to.y *= scale.x / to.x;
				to.x = scale.x;
			} else if (to.y > scale.y) {
				to.x *= scale.y / to.y;
				to.y = scale.y;
			}
		}
		return this.zoomTo({x: to.x.toInt(), y: to.y.toInt()});
	},

	zoomTo: function(to) {
		to = this.options.fixedSize || to;
		var box = this.container.getSize(), scroll = this.container.getScroll();
		var pos = (!this.options.centered) ? {
			x: (this.coords.left + (this.coords.width / 2) - to.x / 2).toInt()
				.limit(scroll.x + this.options.margin, scroll.x + box.x - this.options.margin - to.x),
			y: (this.coords.top + (this.coords.height / 2) - to.y / 2).toInt()
				.limit(scroll.y + this.options.margin, scroll.y + box.y - this.options.margin - to.y)
		} :  {
			x: scroll.x + ((box.x - to.x) / 2).toInt(),
			y: scroll.y + ((box.y - to.y) / 2).toInt()
		};
		if (this.options.cutOut) this.element.setStyle('visibility', 'hidden');
		this.box.removeClass('remooz-loading');
		var vars = {left: pos.x, top: pos.y, width: to.x, height: to.y};
		if (this.options.opacityResize != 1) vars.opacity = [this.options.opacityResize, 1];
		else this.box.set('opacity', 1);
		this.tweens.box.start(vars).chain(this.finishOpen.bind(this));
		this.fireEvent('onOpen');
	},

	build: function() {
		this.addEvent('onBlur', function() {
			this.focused = false;
			this.box.removeClass('remooz-box-focus').setStyle('z-index', ReMooz.options.zIndex);
		}, true);
		this.addEvent('onFocus', function() {
			this.focused = true;
			this.box.addClass('remooz-box-focus').setStyle('z-index', ReMooz.options.zIndexFocus);
		}, true);

		var classes = ['remooz-box', 'remooz-type-' + this.options.type, 'remooz-engine-' + Browser.Engine.name + Browser.Engine.version];
		if (this.options.className) classes.push(this.options.className);
		this.box = new Element('div', {
			'class': classes.join(' '),
			'styles': {
				'display': 'none',
				'top': 0,
				'left': 0,
				'zIndex': ReMooz.options.zIndex
			}
		});

		this.tweens = {
			'box': new Fx.Morph(this.box, $merge({
					'duration': 400,
					'unit': 'px',
					'transition': Fx.Transitions.Quart.easeOut,
					'chain': 'cancel'
				}, this.options.resizeOptions)
			),
			'fade': new Fx.Tween(null, $merge({
					'property': 'opacity',
					'duration': (Browser.Engine.trident) ? 0 : 300,
					'chain': 'cancel'
				}, this.options.fxOptions)).addEvents({
					'onComplete': function() {
						if (!this.element.get('opacity')) this.element.setStyle('display', 'none');
					},
					'onStart': function() {
						if (!this.element.get('opacity')) this.element.setStyle('display', '');
					}
				}
			)
		};
		this.tweens.fade.element = $$();

		if (this.options.shadow) {
			if (Browser.Engine.webkit420) {
				this.box.setStyle('-webkit-box-shadow', '0 0 10px rgba(0, 0, 0, 0.7)');
			} else if (!Browser.Engine.trident4) {
				var shadow = new Element('div', {'class': 'remooz-bg-wrap'}).inject(this.box);
				['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'].each(function(dir) {
					new Element('div', {'class': 'remooz-bg remooz-bg-' + dir}).inject(shadow);
				});
				this.tweens.bg = new Fx.Tween(shadow, {
					'property': 'opacity',
					'chain': 'cancel'
				}).set(0);
				this.addEvent(this.options.shadow, this.tweens.bg.set.bind(this.tweens.bg, 1), true);
				this.addEvent('onClose', this.tweens.bg.set.bind(this.tweens.bg, 0), true);
			}
		}

		if (this.options.closer) {
			var closer = new Element('a', {
				'class': 'remooz-btn-close',
				'events': {'click': this.bound.close}
			}).inject(this.box);
			this.tweens.fade.element.push(closer);
		}
		this.body = new Element('div', {'class': 'remooz-body'}).inject(this.box);

		var title = this.options.title || this.options.generateTitle.call(this, this.element);
		if (title) { // thx ie6
			var title = new Element('div', {'class': 'remooz-title'}).adopt(
				new Element('div', {'class': 'remooz-title-bg', 'opacity': this.options.opacityTitle}),
				new Element('div', {'class': 'remooz-title-content'}).adopt(title)
			).inject(this.box);
			this.tweens.fade.element.push(title);
		}
		this.tweens.fade.set(0).fireEvent('onComplete');

		this.drag = new Drag.Move(this.box, {
			'snap': 15,
			'preventDefault': true,
			'onBeforeStart': function() {
				if (!this.focused && !this.loading) ReMooz.focus(this);
				else if (this.loading || this.options.closeOnClick) this.box.addEvent('mouseup', this.bound.dragClose);
			}.bind(this),
			'onSnap': function() {
				this.box.removeEvent('mouseup', this.bound.dragClose);
				if (!this.options.dragging) this.drag.stop();
				else this.box.addClass('remooz-box-dragging');
			}.bind(this),
			'onComplete': function() {
				this.box.removeClass('remooz-box-dragging');
			}.bind(this)
		});
		this.drag.detach();

		this.fireEvent('onBuild', this.box, this.element);
		this.box.inject(this.element.getDocument().body);
	}

});

ReMooz.factory = function(extended) {
	return $extend(this, extended);
};

ReMooz.factory(new Options).factory({

	options: {
		zIndex: 41,
		zIndexFocus: 42,
		query: 'a.remooz',
		modal: false
	},

	assign: function(elements, options) {
		return $$(elements).map(function(element) {
			return new ReMooz(element, options);
		}, this);
	},

	stack: [],

	open: function(obj) {
		var last = this.stack.getLast();
		this.focus(obj);
		if (last && this.options.modal) last.close();
	},

	close: function(obj) {
		var length = this.stack.length - 1;
		if (length > 1 && this.stack[length] == obj) this.focus(this.stack[length - 1]);
		this.stack.erase(obj);
	},

	focus: function(obj) {
		var last = this.stack.getLast();
		obj.fireEvent('onFocus', [obj]);
		if (last == obj) return;
		if (last) last.fireEvent('onBlur', [last]);
		this.stack.erase(obj).push(obj);
	}

});

var viewer=new Class({mode:'rand',modes:['top','right','bottom','left','alpha'],sizes:{w:480,h:240},fxOptions:{duration:500},interval:5000,initialize:function(a,b){if(b)for(var o in b)this[o]=b[o];if(this.buttons){this.buttons.previous.addEvent('click',this.previous.bind(this,[true]));this.buttons.next.addEvent('click',this.next.bind(this,[true]))}this.__current=0;this.__previous=null;this.items=a.setStyle('display','none');this.items[this.__current].setStyle('display','block');this.disabled=false;this.attrs={left:['left',-this.sizes.w,0,'px'],top:['top',-this.sizes.h,0,'px'],right:['left',this.sizes.w,0,'px'],bottom:['top',this.sizes.h,0,'px'],alpha:['opacity',0,1,'']};this.rand=this.mode=='rand';this.sequence=typeof(this.mode)=='object'?this.mode:false;this.curseq=0;this.timer=null},walk:function(n,b){if(this.__current!==n&&!this.disabled){this.disabled=true;if(b){this.stop()}if(this.rand){this.mode=this.modes.getRandom()}else if(this.sequence){this.mode=this.sequence[this.curseq];this.curseq+=this.curseq+1<this.sequence.length?1:-this.curseq}this.__previous=this.__current;this.__current=n;var a=this.attrs[this.mode].associate(['p','f','t','u']);for(var i=0;i<this.items.length;i++){if(this.__current===i){this.items[i].setStyles($extend({'display':'block','z-index':'2'},JSON.decode('{"'+a.p+'":"'+a.f+a.u+'"}')))}else if(this.__previous===i){this.items[i].setStyles({'z-index':'1'})}else{this.items[i].setStyles({'display':'none','z-index':'0'})}}this.items[n].set('tween',$merge(this.fxOptions,{onComplete:this.onComplete.bind(this)})).tween(a.p,a.f,a.t)}},play:function(a){this.stop();if(!a){this.next()}this.timer=this.next.periodical(this.interval,this,[false])},stop:function(){$clear(this.timer)},next:function(a){this.walk(this.__current+1<this.items.length?this.__current+1:0,a)},previous:function(a){this.walk(this.__current>0?this.__current-1:this.items.length-1,a)},onComplete:function(){this.disabled=false;this.items[this.__previous].setStyle('display','none');if(this.onWalk)this.onWalk(this.__current)}});


/*!
	Slimbox v1.69 - The ultimate lightweight Lightbox clone
	(c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
var Slimbox = (function() {

	// Global variables, accessible to Slimbox only
	var win = window, ie6 = Browser.Engine.trident4, options, images, activeImage = -1, activeURL, prevImage, nextImage, compatibleOverlay, middle, centerWidth, centerHeight,

	// Preload images
	preload = {}, preloadPrev = new Image(), preloadNext = new Image(),

	// DOM elements
	overlay, center, image, sizer, prevLink, nextLink, bottomContainer, bottom, caption, number,

	// Effects
	fxOverlay, fxResize, fxImage, fxBottom;

	/*
		Initialization
	*/

	win.addEvent("domready", function() {
		// Append the Slimbox HTML code at the bottom of the document
		$(document.body).adopt(
			$$(
				overlay = new Element("div", {id: "lbOverlay", events: {click: close}}),
				center = new Element("div", {id: "lbCenter"}),
				bottomContainer = new Element("div", {id: "lbBottomContainer"})
			).setStyle("display", "none")
		);

		image = new Element("div", {id: "lbImage"}).injectInside(center).adopt(
			sizer = new Element("div", {styles: {position: "relative"}}).adopt(
				prevLink = new Element("a", {id: "lbPrevLink", href: "#", events: {click: previous}}),
				nextLink = new Element("a", {id: "lbNextLink", href: "#", events: {click: next}})
			)
		);

		bottom = new Element("div", {id: "lbBottom"}).injectInside(bottomContainer).adopt(
			new Element("a", {id: "lbCloseLink", href: "#", events: {click: close}}),
			caption = new Element("div", {id: "lbCaption"}),
			number = new Element("div", {id: "lbNumber"}),
			new Element("div", {styles: {clear: "both"}})
		);
	});


	/*
		Internal functions
	*/

	function position() {
		var scroll = win.getScroll(), size = win.getSize();
		$$(center, bottomContainer).setStyle("left", scroll.x + (size.x / 2));
		if (compatibleOverlay) overlay.setStyles({left: scroll.x, top: scroll.y, width: size.x, height: size.y});
	}

	function setup(open) {
		["object", ie6 ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				if (open) el._slimbox = el.style.visibility;
				el.style.visibility = open ? "hidden" : el._slimbox;
			});
		});

		overlay.style.display = open ? "" : "none";

		var fn = open ? "addEvent" : "removeEvent";
		win[fn]("scroll", position)[fn]("resize", position);
		document[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		var code = event.code;
		// Prevent default keyboard action (like navigating inside the page)
		return options.closeKeys.contains(code) ? close()
			: options.nextKeys.contains(code) ? next()
			: options.previousKeys.contains(code) ? previous()
			: false;
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex) {
		if (imageIndex >= 0) {
			activeImage = imageIndex;
			activeURL = images[imageIndex][0];
			prevImage = (activeImage || (options.loop ? images.length : 0)) - 1;
			nextImage = ((activeImage + 1) % images.length) || (options.loop ? 0 : -1);

			stop();
			center.className = "lbLoading";

			preload = new Image();
			preload.onload = animateBox;
			preload.onload = animateBox;
			preload.src = activeURL;
		}

		return false;
	}

	function animateBox() {
		center.className = "";
		fxImage.set(0);
		image.setStyles({backgroundImage: "url(" + activeURL + ")", display: ""});
		sizer.setStyle("width", preload.width);
		$$(sizer, prevLink, nextLink).setStyle("height", preload.height);

		caption.set("html", images[activeImage][1] || "");
		number.set("html", (((images.length > 1) && options.counterText) || "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length));

		if (prevImage >= 0) preloadPrev.src = images[prevImage][0];
		if (nextImage >= 0) preloadNext.src = images[nextImage][0];

		centerWidth = image.offsetWidth;
		centerHeight = image.offsetHeight+10;
		var top = Math.max(0, middle - (centerHeight / 2)), fn;
		if (center.offsetHeight != centerHeight) {
			fxResize.start({height: centerHeight, top: top});
		}
		if (center.offsetWidth != centerWidth) {
			fxResize.start({width: centerWidth, marginLeft: -centerWidth/2});
		}
		fn = function() {
			if(activeImage==0 || bottomContainer.getStyle("display")=="none") {
				bottomContainer.setStyles({width: centerWidth, top: top + centerHeight, marginLeft: -centerWidth/2, visibility: "hidden", display: ""});
			}
			fxImage.start(1);
		};
		//if (fxResize.check(fn)) 
		fn();
	}

	function animateCaption() {
		if (prevImage >= 0) prevLink.style.display = "";
		if (nextImage >= 0) nextLink.style.display = "";
		if(activeImage==0 || bottomContainer.getStyle("visibility")=="hidden") {
			fxBottom.set(-bottom.offsetHeight).start(0);
			bottomContainer.style.visibility = "";
		}
	}

	function stop() {
		preload.onload = $empty;
		preload.src = preloadPrev.src = preloadNext.src = activeURL;
		fxResize.cancel();
		fxImage.cancel();
		fxBottom.cancel();
		if(activeImage==0) {
			$$(prevLink, nextLink, image, bottomContainer).setStyle("display", "none");
		}
		else {
			$$(prevLink, nextLink, image).setStyle("display", "none");
		}
	}

	function close() {
		if (activeImage >= 0) {
			stop();
			$(bottomContainer).setStyle("display", "none");
			activeImage = prevImage = nextImage = -1;
			center.style.display = "none";
			fxOverlay.cancel().chain(setup).start(0);
		}

		return false;
	}


	/*
		API
	*/

	Element.implement({
		slimbox: function(_options, linkMapper) {
			// The processing of a single element is similar to the processing of a collection with a single element
			$$(this).slimbox(_options, linkMapper);

			return this;
		}
	});

	Elements.implement({
		/*
			options:	Optional options object, see Slimbox.open()
			linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 2 elements:
					the image URL and the image caption (may contain HTML)
			linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
					the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
					This function must always return true when the DOM element argument is "this".
		*/
		slimbox: function(_options, linkMapper, linksFilter) {
			linkMapper = linkMapper || function(el) {
				return [el.href, el.title];
			};

			linksFilter = linksFilter || function() {
				return true;
			};

			var links = this;

			links.removeEvents("click").addEvent("click", function() {
				// Build the list of images that will be displayed
				var filteredLinks = links.filter(linksFilter, this);
				return Slimbox.open(filteredLinks.map(linkMapper), filteredLinks.indexOf(this), _options);
			});

			return links;
		}
	});

	return {
		open: function(_images, startImage, _options) {
			options = $extend({
				loop: true,				// Allows to navigate between first and last images
				overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				overlayFadeDuration: 400,		// Duration of the overlay fade-in and fade-out animations (in milliseconds)
				resizeDuration: 400,			// Duration of each of the box resize animations (in milliseconds)
				resizeTransition: false,		// false uses the mootools default transition
				initialWidth: 250,			// Initial width of the box (in pixels)
				initialHeight: 250,			// Initial height of the box (in pixels)
				imageFadeDuration: 400,			// Duration of the image fade-in animation (in milliseconds)
				captionAnimationDuration: 400,		// Duration of the caption animation (in milliseconds)
				counterText: "Image {x} sur {y}",	// Translate or change as you wish, or set it to false to disable counter text for image groups
				closeKeys: [27, 88, 67],		// Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
				previousKeys: [37, 80],			// Array of keycodes to navigate to the previous image, default: Left arrow (37), 'p' (80)
				nextKeys: [39, 78]			// Array of keycodes to navigate to the next image, default: Right arrow (39), 'n' (78)
			}, _options || {});

			// Setup effects
			fxOverlay = new Fx.Tween(overlay, {property: "opacity", duration: options.overlayFadeDuration});
			fxResize = new Fx.Morph(center, $extend({duration: options.resizeDuration, link: "chain"}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
			fxImage = new Fx.Tween(image, {property: "opacity", duration: options.imageFadeDuration, onComplete: animateCaption});
			fxSwitch = new Fx.Tween(image, {property: "opacity", duration: options.imageFadeDuration});
			fxBottom = new Fx.Tween(bottom, {property: "margin-top", duration: options.captionAnimationDuration});

			// The function is called for a single image, with URL and Title as first two arguments
			if (typeof _images == "string") {
				_images = [[_images, startImage]];
				startImage = 0;
			}

			middle = win.getScrollTop() + (win.getHeight() / 2);
			centerWidth = options.initialWidth;
			centerHeight = options.initialHeight;
			center.setStyles({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2, display: ""});
			compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
			if (compatibleOverlay) overlay.style.position = "absolute";
			fxOverlay.set(0).start(options.overlayOpacity);
			position();
			setup(1);

			images = _images;
			options.loop = options.loop && (images.length > 1);
			return changeImage(startImage);
		}
	};

})();

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function() {
	$$(document.links).filter(function(el) {
		return el.rel && el.rel.test(/^lightbox/i);
	}).slimbox({/* Put custom options here */}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
};


Form.Validator.addAllThese([

	['validate-matchemail', {
		errorMsg: function(element, props){
			return FormValidator.getMsg('matchemail');
		},
		test: function(element, props){
			var eleVal = element.get('value');
			var matchVal = document.id(props.matchInput) && document.id(props.matchInput).get('value');
			return eleVal && matchVal ? eleVal == matchVal : true;
		}
	}]

]);

Form.Validator.Label = new Class({

	//small hacks from the original Inline
	Extends: Form.Validator,

	options: {
		displayError:true,
		scrollToErrorsOnSubmit: false,
		scrollFxOptions: {
			transition: 'quad:out',
			offset: {
				y: -20
			}
		}
	},

	initialize: function(form, options){
		this.parent(form, options);
		this.labels=$$('label');
		this.addEvent('onElementValidate', function(isValid, field, className, warn){
			var validator = this.getValidator(className);
			this.labels.each(function(label) {
				if(label.get('for') == field.get('id')) {
					field.label=label;
				}

			});
			if (!isValid && validator.getError(field)){
				if (warn) field.addClass('warning');
				var advice = this.makeAdvice(className, field, validator.getError(field), warn);
				this.insertAdvice(advice, field);
				this.showAdvice(className, field);
			} else {
				this.hideAdvice(className, field);
			}
		});
	},

	makeAdvice: function(className, field, error, warn){
		if(this.options.displayError) {
			var errorMsg = ' ( ';
				errorMsg += (warn)?this.warningPrefix:this.errorPrefix;
				errorMsg += (this.options.useTitles) ? field.title || error:error;
				errorMsg += ' ) ';
		}
		else {
			var errorMsg = '';
		}
		var cssClass = (warn) ? 'warning-advice' : 'validation-advice';
		var advice = this.getAdvice(className, field);
		if(advice) {
			advice = advice.clone(true, true).set('html', errorMsg ).replaces(advice);
		} else {
			advice = new Element('span', {
				html: errorMsg ,
				styles: { display: 'none' },
				id: 'advice-' + className + '-' + this.getFieldId(field)
			}).addClass(cssClass);
		}
		field.store('advice-' + className, advice);
		return advice;
	},

	getFieldId : function(field){
		return field.id ? field.id : field.id = 'input_' + field.name;
	},

	showAdvice: function(className, field){
		var advice = this.getAdvice(className, field);
		if (advice && !field.retrieve(this.getPropName(className))
				&& (advice.getStyle('display') == 'none'
				|| advice.getStyle('visiblity') == 'hidden'
				|| advice.getStyle('opacity') == 0)){
			field.store(this.getPropName(className), true);
			if (advice.reveal) {
				advice.setStyles({'opacity': 1, 'visibility': 'visible', 'display' : 'inline'});
			}
			else {
				advice.setStyle('display', 'inline');
			}
			field.label.addClass('lblwarning');
			field.highlight('#fff', '#831026');
		}
	},

	hideAdvice: function(className, field){
		var advice = this.getAdvice(className, field);
		if (advice && field.retrieve(this.getPropName(className))) {
			field.store(this.getPropName(className), false);
			//if Fx.Reveal.js is present, transition the advice out
			if (advice.dissolve) advice.setStyles({'opacity': 0, 'visibility': 'hidden', 'display' : 'none'});
			else advice.setStyle('display', 'none');

			field.label.removeClass('lblwarning');

		}
	},

	getPropName: function(className){
		return 'advice' + className;
	},

	resetField: function(field){
		field = document.id(field);
		if (!field) return this;
		this.parent(field);
		field.className.split(' ').each(function(className){
			this.hideAdvice(className, field);
		}, this);
		return this;
	},

	getAllAdviceMessages: function(field, force){
		var advice = [];
		if (field.hasClass('ignoreValidation') && !force) return advice;
		var validators = field.className.split(' ').some(function(cn){
			var warner = cn.test('^warn-') || field.hasClass('warnOnly');
			if (warner) cn = cn.replace(/^warn-/, '');
			var validator = this.getValidator(cn);
			if (!validator) return;
			advice.push({
				message: validator.getError(field),
				warnOnly: warner,
				passed: validator.test(),
				validator: validator
			});
		}, this);
		return advice;
	},

	getAdvice: function(className, field){
		return field.retrieve('advice-' + className);
	},

	insertAdvice: function(advice, field){
		//Check for error position prop
		var props = field.get('validatorProps');
		//Build advice
		if (!props.msgPos || !document.id(props.msgPos)){
			if(field.type.toLowerCase() == 'radio') field.getParent().adopt(advice);
			else advice.inject(document.id(field), 'after');
		} else {
			document.id(props.msgPos).grab(advice);
		}
	},

	validateField: function(field, force){
		var result = this.parent(field, force);
		if (this.options.scrollToErrorsOnSubmit && !result){
			var failed = document.id(this).getElement('.validation-failed');
			var par = document.id(this).getParent();
			while (par != document.body && par.getScrollSize().y == par.getSize().y){
				par = par.getParent();
			}
			var fx = par.retrieve('fvScroller');
			if (!fx && window.Fx && Fx.Scroll){
				fx = new Fx.Scroll(par, this.options.scrollFxOptions);
				par.store('fvScroller', fx);
			}
			if (failed){
				if (fx) fx.toElement(failed);
				else par.scrollTo(par.getScroll().x, failed.getPosition(par).y - 20);
			}
		}
		return result;
	}

});

