// Main javascript document
// JEG.ch
// © Cyril Picard informatique

// Main js

// Main javascript document
// JEG.ch
// © Cyril Picard informatique

// Form js

var Form = new Class({
	Implements: Options,
	
	options: {
		validate: false,
		successid: false,
		errorid: false,
		fields: new Array(),
		path: '/',
		reset: true,
		onSubmit: $empty,
		onReceived: $empty
	},
	
	initialize: function(form, options) {
		this.setOptions(options);
		this.form = $(form);
		this.scroll = new Fx.Scroll(window);
		this.act = this.form.get('action');
		this.process = false;
		this.processC = false;
		this.validation=new Array();
		// IMG and Events
		this.loaderimg = new Element('div',{'class':'buttonset ajax-loader','html':'<img src="'+this.options.path+'images/ajax-loader.gif" align="top" /> Patientez...'});
		this.submitB = this.form.getElement('div.buttonset');
		this.form.getElement('a.submit').addEvent('click',(function(e) { new Event(e).stop(); this.submit(); }).bind(this));
		this.form.getElement('a.reset').addEvent('click',(function(e) { new Event(e).stop(); this.clearError(); this.clearSuccess(); this.form.reset();}).bind(this));
		// add enter key gestion
		this.form.addEvent('submit',(function(e){ new Event(e).stop(); this.submit(); }).bind(this))
		if (this.options.validate) {
			this.ok = false;
			if (this.options.errorid) this.options.errorid.slide('hide');
			if (this.options.successid) this.options.successid.slide('hide');
			this.notokpng = new Asset.image(this.options.path+'images/NotOK.png',{'class':'OK','align':'top'});
			this.okpng = new Asset.image(this.options.path+'images/OK.png',{'class':'OK','align':'top'});
			this.options.fields.each(function(field,i) {
				var imglink = this.notokpng.clone().inject($(field.element).getParent());
				this.validation[i] = new Array($(field.element),field.type,field.message,imglink);
				$(field.element).addEvent('blur',(function() {
					this.validate(i);
				}).pass(i,this));
			},this);
		} else {
			this.ok = true;
		}
		if (this.form.get('enctype') == "multipart/form-data") {
			this.iframe = new IFrame({'name':'iframe_post','id':'iframe_post','width':'0','height':'0'}).addEvent('load',this.iframe.bind(this)).inject($$('body')[0]);
			this.form.set('target','iframe_post');
		}
	},
	submit: function() {
		if (this.ok) {
			this.send();
		} else {
			this.clearError();
			this.clearSuccess();
			if (this.validate()) {
				this.send();
			} else {
				this.displayError();
			}
		}
	},
	send: function() {
		if (!this.process) {
			this.loaderimg.replaces(this.submitB);
			this.process = true;
			this.processC = this.checkprocess.delay(45000);
			this.options.onSubmit.run(this);
			if (this.form.get('enctype') == "multipart/form-data") {
				this.form.submit();
			} else {
				this.ajax = new Request.JSON({url:this.act, method:'post',onSuccess:this.completed.bind(this),onFailure:this.clearProccess.bind(this)}).send(this.form.toQueryString());
			}
		}
	},
	iframe: function() {
		if (this.process) {
			var json = JSON.decode(this.iframe.contentDocument.body.get('text'),true);
			this.completed(json);
		}
	},
	checkprocess: function() {
		if (this.processC) {
			if (this.ajax) {
				$clear(this.processC);
				this.processC = false;
				this.process=false;
				this.ajax.cancel();
				this.submitB.replaces(this.loaderimg);
				alert("Une erreur est survenue lors de la connection avec le serveur. Veuillez réessayer, s'il vous plaît.");
			}
		}
	},
	clearProccess: function() {
		$clear(this.processC);
		this.processC = false;
		this.process=false;
		this.ajax.cancel();
		this.submitB.replaces(this.loaderimg);
		alert("Une erreur est survenue lors de la connection avec le serveur. Veuillez réessayer, s'il vous plaît.");

	},
	completed: function(json) {
		$clear(this.processC);
		this.processC = false;
		this.options.onReceived.run([this,json]);
		if (json.type=='error') {
			this.error = json.error;
			this.displayError();
		} else if (json.type=='redirect') {
			window.location = json.url;
		} else if (json.type=='msg') {
			if (this.options.reset) this.form.reset();
			this.displaySuccess(json.msg);
		}
		this.process=false;
		this.submitB.replaces(this.loaderimg);
	},
	validate: function(i) {
		if ($defined(i)) {
			// One field check
			var id = this.validation[i][0];
			var check = this.validation[i][1];
			var val = false;
			if (check=='empty') {
				val = !id.get('value').isEmpty();
			} else if (check=='email') {
				val = id.get('value').isEmail();
			} else if (check=='alphanum') {
				val = !id.get('value').isntAlphaNummeric();
			} else if (check=='url') {
				val = !id.get('value').isntURL();
			}
			if (val) {
				this.validation[i][3] = this.okpng.clone().replaces(this.validation[i][3]);
			} else {
				this.validation[i][3] = this.notokpng.clone().replaces(this.validation[i][3]);
			}
		} else {
			// Global check
			this.error = new Array();
			this.validation.each(function(obj){
				var val = false;
				var msg;
				var id = obj[0];
				var check = obj[1];
				if (check=='empty') {
					val = !id.get('value').isEmpty();
					msg = 'Le champ '+obj[2]+' doit être renseigné.';
				} else if (check=='email') {
					val = id.get('value').isEmail();
					msg = 'L\'adresse email n\'est pas valide.';
				} else if (check=='alphanum') {
					val = !id.get('value').isntAlphaNummeric();
					msg = 'Le champ '+obj[2]+' ne peut contenir que des caractères alphanumériques.';
				} else if (check=='url') {
					val = !id.get('value').isntURL();
					msg = 'Le champ '+obj[2]+' doit être une adresse URL correcte.';
				}
				if (!val) {
					this.error.extend([msg]);
				}
			},this);
			if (this.error.length == 0) {
				return true;
			} else {
				return false;
			}
		}
	},
	displayError: function() {
		if (this.options.errorid) {
			if (this.error.length==1) {
				var html = '<p>'+this.error[0]+'</p>';
			} else {
				var html = '<p>Les erreurs suivantes ont été trouvées :</p><ul class="liste">';
				this.error.each(function(e) {
					html += '<li>'+e+'</li>';
				});
				html += '</ul>';
			}
			this.options.errorid.getElement('div').set('html',html);
			if (this.options.errorid.getElement('div').getStyle('height').toInt()<35) this.options.errorid.setStyle('height','35px');
			this.options.errorid.slide('show');
			this.scroll.toElement(this.options.errorid);
			this.options.errorid.highlight.delay(500,this.options.errorid,"#fc3");
		} else {
			var text='';
			this.error.each(function(e) {
				text += e+"\n";
			});
			alert(text);
		}
	},
	clearError: function() {
		if (this.options.errorid) {
			this.options.errorid.slide('hide').getElement('div').set('html',$empty());
			this.options.errorid.setStyle('height','auto');
		}
	},
	displaySuccess: function(msg) {
		if (this.options.successid) {
			this.options.successid.set('html','<p>'+msg+'</p>').slide('show');
			this.scroll.toElement(this.options.successid);
			this.options.successid.highlight.delay(500,this.options.successid,"#C6D880");
		} else {
			alert(msg);
		}
	},
	clearSuccess: function() {
		if (this.options.successid) {
			this.options.successid.slide('hide').set('html',$empty());
		}
	}
});

var options = {
	'menutimeout':700,
	'szNormal':170,
	'szSmall':140,
	'szFull':230
};
var fcinit = new Array();

var SlideMenu = new Class({
	Implements: Options,
	
	options: {
		'width': '138px',
		'timeout': 700
	},
	
	initialize: function(menu,options) {
		this.menu = menu;
		this.setOptions(options);
		this.menu.getElements('dl').each(function(list,i) {
			if (Browser.trident4) list.setStyle('width',this.options.width);
			if (list.getElements("dd").length > 0) {
				list.set({
					'id':"dd"+i,
					'events':{
						'mouseenter': this.show.pass(list,this),
						'mouseleave': this.hideevent.pass(this.options.timeout,list),
						'focus': this.show.pass(list,this),
						'blur': this.hideevent.pass(this.options.timeout,list),
						'tohide':this.hide
					}
				}).store('timer',false).getElement('dd').set('slide',{link:'cancel'}).slide('hide');
			}
		},this);
	},
	show: function(el) {
		var t = el.retrieve('timer')
		if (t) $clear(t);
		el.getElement('dd').slide('in');
		this.menu.getElements('dl[id!='+el.get('id')+']').fireEvent('tohide');
	},
	hide: function() {
		var t = this.retrieve('timer')
		if (t) $clear(t);
		this.getElement('dd').slide('out');
	},
	hideevent: function(timeout) {
		var t = this.fireEvent.delay(timeout,this,'tohide');
		this.store('timer',t);
	}
});

var Tabs = new Class({
	initialize: function(element) {
		this.element = element;
		this.tabs = new Element('div',{'class':'border-bot-ccc padding-bot-small'});
		this.element.getChildren('div').each(function(item,index) {
			var title = item.get('title');
			if (item.hasClass('tab-selected')) {
				this.selected = item;
			} else {
				item.slide('hide');
			}
			new Element('span',{
				'class':'tab',
				'html':title,
				'events':{'click':this.toggle.pass(item,this)}
			}).inject(this.tabs);
		},this);
		this.tabs.inject(this.element,'top');
	},
	toggle: function(item) {
		if (item.hasClass('tab-selected')) {
			return;
		}
		this.selected.slide('hide').removeClass('tab-selected');
		this.selected = item.addClass('tab-selected').slide('show');
	}
});

String.implement({
	isEmpty: function() {
		if (this == null || this.length == 0)
			return true;
		return !/\S/.test(this);
	},
	isEmail: function() {
		if (this.isEmpty()) {
			return false;
		} else {
			return /^[A-Z0-9._%+-]+@([A-Z0-9.-]+\.[A-Z]{2,6})$/i.test(this);
		}
	},
	isntAlphaNummeric: function() {
		if (this == null || this.length == 0) {
			return true;
		} else {
			return !/^[\w.]+$/.test(this);
		}
	},
	isntURL: function() {
		if (this == null || this.length == 0) {
			return true;
		} else {
			return !/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/.test(this);
		}
	}
});
Element.implement({
	maketab : function() {
		new Tabs(this);
	},
	dlToggle : function() {
		this.getElement('dt').addEvent('click',(function() { this.slide('toggle'); }).bind(this.getElement('dd'))).fireEvent('click');
	},
	curvy: function(options) {
		var st_options = { tl: 20, tr: 20, bl: 20, br: 20 };
		st_options = $merge(st_options,options);
		if (Browser.Engine.webkit420) {
        	this.setStyles({'-webkit-border-top-left-radius':st_options.tl+'px', '-webkit-border-top-right-radius':st_options.tr+'px','-webkit-border-bottom-left-radius':st_options.bl+'px','-webkit-border-bottom-right-radius':st_options.br+'px'});
        } else if (Browser.Engine.gecko19) {
        	this.setStyles({'-moz-border-radius-topleft':st_options.tl+'px','-moz-border-radius-topright':st_options.tr+'px','-moz-border-radius-bottomleft':st_options.bl+'px','-moz-border-radius-bottomright':st_options.br+'px'});
        } else {
        	/*if ($type(this.curvyobject)!='object') {
        		new Asset.javascript(html_path+'js/curvycorners.js');
        		this.curvyobject = new CurvyObject(this,options);
				this.curvyobject.applyCorners();
        	}*/
        }
		return this;
	}
});
Elements.implement({
	maketab : function() {
		this.each(function(item) {
			item.maketab();
		});
	},
	dlToggle : function() {
		this.each(function(item) {
			item.dlToggle();
		});
	},
	curvy: function(options) {
		var st_options = { tl: 20, tr: 20, bl: 20, br: 20 };
		st_options = $merge(st_options,options);
		if (Browser.Engine.webkit420) {
        	this.setStyles({'-webkit-border-top-left-radius':st_options.tl+'px', '-webkit-border-top-right-radius':st_options.tr+'px','-webkit-border-bottom-left-radius':st_options.bl+'px','-webkit-border-bottom-right-radius':st_options.br+'px'});
        } else if (Browser.Engine.gecko19) {
        	this.setStyles({'-moz-border-radius-topleft':st_options.tl+'px','-moz-border-radius-topright':st_options.tr+'px','-moz-border-radius-bottomleft':st_options.bl+'px','-moz-border-radius-bottomright':st_options.br+'px'});
        } else {
        	/*if ($type(this.curvyobject)!='object') {
        		new Asset.javascript(html_path+'js/curvycorners.js');
        		this.curvyobject = new CurvyObject(this,options);
				this.curvyobject.applyCorners();
        	}*/
        }
		return this;
	}
});

window.addEvent('domready',function() {
	new SlideMenu($('menu-container'),{'timeout':options.menutimeout});
	if ($$('.ticker').length > 0) $$('.ticker').maketab();
	if ($('cadre')) $('cadre').curvy({tr:5,tl:5,br:5,bl:5});
	if ($$('.membre').length > 0) $$('.membre').curvy({tr:10,tl:10,br:10,bl:10});
	document.getElement('#search .Sinput').addEvents({
		'focus': function() { if (this.value=='Rechercher...') { this.value=''; } },
		'blur':function() { if (this.value=='') { this.value='Rechercher...'; } }
	});
	if ($$('.Dir-contact')) {
		$$('a.Dir-contact').each(function(item,i) {
			item.addEvent('click',(function(e) { new Event(e).stop(); this.getParent().getElement('div.Dir-contact').slide('toggle')}).bind(item));
			item.getParent().getElement('div.Dir-contact').slide('hide');
		});
	}
	if ($$('.h2-sidebar')) $$('.h2-sidebar').curvy({tr:5,tl:5,br:5,bl:5});
	$$('#sidebar .toggle').each(function(item) {
		item.getElement('.h2-sidebar').addEvent('click', (function(e) {
			new Event(e).stop();
			this.getElement('.to-toggle').slide('toggle');
		}).bind(item));
	});
	fcinit.each(function(fct) { fct.attempt() });
});

