var scroller = new Fx.Scroll(window);

var Site = {
	
	start: function(){

		Site.setUpScrollAnchors();
		Site.liftmeup();
		new SmoothScroll(null, window);
		//ReMooz.initialize();
		$$('a.remooz').each(function(link, i) {
			new ReMooz(link, {
				origin:'img',
				//url: img.getParent().href,
				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;
		};
		var accordion = new Accordion('h3.atStart', 'div.atStart', {
			opacity: false,
			onActive: function(toggler, element){
				$$('h3.atStart').addEvent('click', function() { 
					Site.scrollTo('contentinner');
				});
				toggler.setStyle('color', '#E16E21');
				toggler.setStyle('cursor', 'default');
				toggler.setStyle('background-position', '0 0');
			},
			onBackground: function(toggler, element){
				toggler.setStyle('background-position', '0 -30px');
				toggler.setStyle('color', '#939393');
				toggler.setStyle('cursor', 's-resize');
			}
		}, $('accordion'));
		var accordiontwo = new Accordion('h3.atStarttwo', 'div.atStarttwo', {
			opacity: false,
			onActive: function(toggler, element){
				$$('h3.atStarttwo').addEvent('click', function() { 
					Site.scrollTo('contentinner');
				});
				toggler.setStyle('color', '#E16E21');
				toggler.setStyle('cursor', 'default');
				toggler.setStyle('background-position', '0 0');
			},
			onBackground: function(toggler, element){
				toggler.setStyle('background-position', '0 -30px');
				toggler.setStyle('color', '#939393');
				toggler.setStyle('cursor', 's-resize');
			}
		}, $('accordiontwo'));

		//let's do fancy stuff for the demo download
		if($('system')) {
			var sys=$('system');
			// let's init 
			sys.selectedIndex=0;
			sys.addEvent('change', function() { 
				toppos=(sys.selectedIndex>0) ? sys.selectedIndex.toInt()*40 +'px' : 0+ 'px';
				$('arti-sys').setStyle('background-position', 'center -'+toppos+ '');
				
			});
		}
		if($('version')) {
			var ver=$('version');
			// let's init 
			ver.selectedIndex=0;
			ver.addEvent('change', function() { 
				toppos=(ver.selectedIndex>0) ? ver.selectedIndex.toInt()*50 +'px' : 0+ 'px';
				$('arti-mod').setStyle('background-position', 'center -'+toppos+ '');
				
			});
		}


	},
	
	
	
	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();
	if($('submenu')) slidingtabs = new SlidingTabs('submenu', 'innerwrapper');
	if($('submitter')) {
		$('submitter').addEvent('click',function(evt) {
			new Event(evt).stop();
			CheckFeedback.CheckValue();
		});
	}
});

var CheckFeedback = {

	CheckValue : function() {

		var messenger = $('messenger').action;
		var contact = $('contact').value;
		var email = $('email').value;
		var emailmatch = $('emailmatch').value;
		var phone = $('phone').value;
		var lblcontact = $('lblcontact');
		var lblemail = $('lblemail');
		var lblemailmatch = $('lblemailmatch');
		var lblphone = $('lblphone');
		if($('message')) {
			var message = $('message').value;
			var lblmessage = $('lblmessage');
			var messagee=true;
		}
		else {
			var messagee=true;
		}
		var contacte=true;
		var emaile=true;
		var emailmatche=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 e-mail';
		}
		else {
			if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))) {
				emaile=false;
				lblemail.addClass('warn');
				lblemail.innerHTML = 'Votre e-mail n\'est pas valide';
			}
			else {
				emaile=true;
				lblemail.removeClass('warn');
				lblemail.innerHTML = 'Votre e-mail';
			}
		}
		if(!emailmatch) {
			emaile=false;
			lblemailmatch.addClass('warn');
			lblemailmatch.innerHTML = 'Veuillez confirmer votre e-mail';
		}
		else {
			if (emailmatch!=email) {
				emailmatche=false;
				lblemailmatch.addClass('warn');
				lblemailmatch.innerHTML = 'Vos e-mails ne correspondent pas';
			}
			else {
				emailmatche=true;
				lblemailmatch.removeClass('warn');
				lblemailmatch.innerHTML = 'Veuillez confirmer votre e-mail';
			}
		}
		if($('title') && $('message')) {
			messagee=true;
		}
		/*
		else if($('message')) {
			if(!message) {
				messagee=false;
				lblmessage.addClass('warn');
				lblmessage.innerHTML = 'Veuillez indiquer un message';
			}
			else {
				messagee=true;
				lblmessage.removeClass('warn');
				lblmessage.innerHTML = 'Votre Message';
			}
		}
		*/
		if(!phone) {
			phonee=false;
			lblphone.addClass('warn');
			lblphone.innerHTML = 'Veuillez indiquer votre numero de telephone';
		}
		else {
			phonee=true;
			lblphone.removeClass('warn');
			lblphone.innerHTML = 'votre numero de telephone';
		}



		if(messagee==false || !emaile || !emailmatche || !contacte || !phonee) {
			return false;
		}
		else {
			if (messenger.search('='))
				var messengeruri=messenger+'&ajax=true';
			else 
				var messengeruri=messenger+'?ajax=true';

			//CheckFeedback.loadUrl(messengeruri);
			$('messenger').submit();
		}
	
	},

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


var ReMooz = new Class({

	Implements: [Events, Options],

	options: {
		id: null,
		url: null,
		positionToCenter: false,
		marginBox: 10,
		resize: true,
		resizeFactor: 0.8,
		resizeLimit: false, // {x: 640, y: 640}
		hideSource: true,
		zIndex: 41,
		zIndexFocus: 42,
		addClick: true,
		resizeOptions: {},
		resizeOpacity: 1,
		fxsOptions: {},
		generateTitle: null,
		showTitle: null,
		onLoad: $empty,
		onOpen: $empty,
		onBeforeClose: $empty,
		onClose: $empty
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.setOptions(options);
		this.url = this.options.url || this.element.href || this.element.src;

		this.addEvent('onBlur', function() {
			this.focussed = false;
			this.box.removeClass('remo-box-focus').setStyle('z-index', this.options.zIndex);
		}.bind(this));
		this.addEvent('onFocus', function() {
			this.focussed = true;
			this.box.addClass('remo-box-focus').setStyle('z-index', this.options.zIndexFocus);
		}.bind(this));

		this.element.addClass('remo-zoom-in').addEvent('trash', this.destroy.bind(this));

		this.clickEvent = function(e) {
			this.open.delay(1, this);
			return false;
		}.bind(this);
		if (this.options.addClick) this.bindToElement();
	},

	destroy: function(unload) {
		if (this.box && !unload) this.box.destroy();
		this.box = this.boxFx = this.image = null;
		return null;
	},

	bindToElement: function(el) {
		($(el) || this.element).addEvent('click', this.clickEvent);
		return this;
	},

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

	open: function(e) {
		if (this.opened) return (e) ? this.close() : this;
		this.opened = true;
		if (!this.box) this.build();
		this.coords = this.getSourceCoordinates();
		this.boxFx.set(this.coords).start({'opacity': 0.7});
		this.box.setStyle('display', '').addClass('remo-loading');
		this.boxDrag = this.boxDrag || new Drag.Move(this.box, { // inits here because of safari
			'snap': 15,
			'onStart': function() {
				if (!this.focussed && !this.loading) {
					ReMooz.focus(this);
					this.focusEvent = true;
				}
			}.bind(this),
			'onSnap': function() {
				this.dragging = true;
				this.box.addClass('remo-box-dragging');
			}.bind(this),
			'onComplete': function() {
				if (!this.dragging && !this.focusEvent) this.close();
				this.dragging = this.focusEvent = false;
				this.box.removeClass('remo-box-dragging');
			}.bind(this)
		}).detach();
		this.fireEvent('onLoad');
		this.loadImage();
		return this;
	},

	close: function() {
		if (!this.opened) return this;
		this.fireEvent('onBeforeClose');
		this.opened = this.zoomed = false;
		ReMooz.close(this);
		if (this.loading) {
			this.box.setStyle('display', 'none');
			return this;
		}
		this.boxDrag.detach();
		this.fxs.set(this.fxs.hide);
		if (this.boxFx.timer) this.boxFx.clearChain();
		var vars = this.getSourceCoordinates();
		if (this.options.resizeOpacity != 1) vars.opacity = this.options.resizeOpacity;
		this.boxFx.start(vars).chain(function() {
			this.element.setStyle('visibility', 'visible');
			this.box.setStyle('display', 'none');
			this.fireEvent('onClose');
		}.bind(this));
		return this;
	},

	loadImage: function() {
		this.loading = true;
		var loader = new Image();
		loader.onload = loader.onabort = loader.onerror = function(fast) {
			this.loading = loader.onload = loader.onabort = loader.onerror = null;
			if (!loader.width || !this.opened) {
				this.close();
				return;
			}
			var to = {x: loader.width, y: loader.height};
			if (!this.image)
			{
				 this.image = (Client.Engine.webkit419) ? new Element('img', {'src': loader.src}) : $(loader);
				 this.image.addClass('remo-img').injectTop(this.box);
			} else loader = null;
			this.openImage.create({
				'delay': (loader && fast !== true) ? 1 : null,
				'arguments': [to],
				'bind': this
			})();
		}.bind(this);
		loader.src = this.url;
		if (loader && loader.complete && loader.onload) loader.onload(true);
	},

	openImage: function(size) {
		if (this.options.hideSource) this.element.setStyle('visibility', 'hidden');
		this[(this.options.resize) ? 'zoomRelativeTo' : 'zoomTo'](size);
	},

	zoomRelativeTo: function(to) {
		var max = this.options.resizeLimit || {
			'x': Client.getWidth() * this.options.resizeFactor,
			'y': Client.getHeight() * this.options.resizeFactor
		};
		for (var i = 2; i--;) {
			if (to.x > max.x) {
				to.y *= max.x / to.x;
				to.x = max.x;
			} else if (to.y > max.y) {
				to.x *= max.y / to.y;
				to.y = max.y;
			}
		}
		return this.zoomTo({'x': to.x.toInt(), 'y': to.y.toInt()});
	},

	zoomTo: function(to) {
		var box = window.getSize();
		var pos = (!this.options.positionToCenter) ? {
			'x': (this.coords.left + (this.coords.width / 2) - to.x / 2).toInt()
				.limit(box.scroll.x + this.options.marginBox, box.scroll.x + box.size.x - this.options.marginBox - to.x),
			'y': (this.coords.top + (this.coords.height / 2) - to.y / 2).toInt()
				.limit(box.scroll.y + this.options.marginBox, box.scroll.y + box.size.y - this.options.marginBox - to.y)
		} :  {
			'x': box.scroll.x + ((box.size.x - to.x) / 2).toInt(),
			'y': box.scroll.y + ((box.size.y - to.y) / 2).toInt()
		};
		this.box.removeClass('remo-loading');
		this.fireEvent('onOpen');
		var vars = {'left': pos.x, 'top': pos.y, 'width': to.x, 'height': to.y};
		if (this.options.resizeOpacity != 1) vars.opacity = [this.options.resizeOpacity, 1];
		else this.box.setStyle('opacity', 1);
		this.boxFx.start(vars).chain(this.openComplete.bind(this));
	},

	openComplete: function() {
		ReMooz.open(this);
		this.zoomed = true;
		this.boxDrag.attach();
		this.fxs.start($merge(this.fxs.show, (this.title) ? (this.options.showTitle || this.showTitle).call(this) : {}));
	},

	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(' :: ');
		var ret = [new Element('h4').setHTML(title)];
		if (text) ret.push(new Element('p').setHTML(text));
		return ret;
	},

	showTitle: function() {
		return {1: {marginLeft: [-this.titleBox.scrollWidth, 0]}};
	},

	build: function() {
		this.box = new Element('div', {
			'class': 'remo-box',
			styles: {
				display: 'none',
				zIndex: this.options.zIndex
			},
			events: {
				click: function() {
					if (this.zoomed) return true;
					this.close();
					return false;
				}.bind(this)
			}
		});
		this.boxFx = new Fx.Styles(this.box, $merge({
			duration: 500,
			unit: 'px',
			transition: Fx.Transitions.Quart.easeOut,
			wait: false
		}, this.options.resizeOptions));

		this.btnClose = new Element('a', {
			'class': 'remo-btn-close',
			events: {'click': this.close.bind(this)}
		}).inject(this.box);
		this.fxs = new Fx.Elements(this.btnClose, $merge({
			duration: 500,
			unit: 'px',
			transition: Fx.Transitions.Quart.easeOut,
			wait: false
		}, this.options.fxsOptions));
		this.fxs.hide = {0: {opacity: 0}};
		this.fxs.show = {0: {opacity: 1}};


		this.title = (this.options.generateTitle || this.generateTitle).call(this);
		if (this.title) {
			this.titleBox = new Element('div', {
				'class': 'remo-title'
			}).inject(new Element('div', {
				'class': 'remo-title-wrap'
			}).inject(this.box));
			new Element('div', {'class': 'remo-title-bg'}).setOpacity(0.8).inject(this.titleBox);
			this.titleTxt = new Element('div', {'class': 'remo-title-txt'})
				[$type(this.title) == 'string' ? 'setHTML' : 'adopt'](this.title).inject(this.titleBox);
			this.fxs.elements.push(this.titleBox);
			this.fxs.hide[1] = {opacity: 0};
			this.fxs.show[1] = {opacity: 1};
		}
		this.fxs.set(this.fxs.hide);
		this.box.inject(document.body);
	}

});

ReMooz.factory = $extend;

ReMooz.factory({

	options: {
		zIndex: 41,
		zIndexFocus: 42,
		scanQuery: 'a.remooz',
		optionsField: 'rel'
	},

	initialize: function(elements, options) {
		options = options || {};
		$$(elements || this.options.scanQuery).each(function(el) {
			var add = el.getProperty(this.options.optionsField);
			if (add) add = Json.decode(add, true);
			el.$attributes.remooz = new ReMooz(el, add ? $merge(add, options) : options);
		}, this);
	},

	opened: [],

	open: function(obj) {
		this.focus(obj);
	},

	close: function(obj) {
		var last = this.opened.length - 1;
		if (this.opened.indexOf(obj) == last) this.focus(this.opened[last - 1]);
		this.opened.remove(obj);
	},

	focus: function(obj) {
		var last = this.opened.getLast();
		if (!obj || last == obj) return;
		if (last) last.fireEvent('onBlur', [last], 10);
		obj.fireEvent('onFocus', [obj], 10);
		this.opened.remove(obj).push(obj);
	}

});
