/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
*
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

var Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		//this.error = error || 'Validation failed.';
		this.error = error;
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
}
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)},
	max : function(v,elm,opt) {return v <= parseFloat(opt)},
	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			displayMsgs : true,
			hideObject : false,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var displayMsgs = this.options.displayMsgs;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, displayMsg: displayMsgs, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev) {
		if (!this.validate()) Event.stop(ev);
		else if (this.options.hideObject != false) $(this.options.hideObject).hide();
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var displayMsgs = this.options.displayMsgs;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, displayMsg: displayMsgs, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, displayMsg: displayMsgs, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			displayMsg : true,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		if (elm.hasClassName('blocked') || elm.hasClassName('disabled') || elm.hasClassName('nocheck')) {
			return true;
			// return null;     A voir si ça pose problème...
		} else {
			var cn = elm.classNames();
			return result = cn.all(function(value) {
				var test = Validation.test(value,elm,options.useTitle,options.displayMsg);
				options.onElementValidate(test, elm);
				return test;
			});
		}
	},
	test : function(name, elm, useTitle, displayMsg) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = displayMsg ? (useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error) : '';
					
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							
							advice = '<span class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(node_after(first_child(elm.parentNode.parentNode))) +'" style="display:none">' + errorMsg + '</span>';
							if (!$('advice-' + name + '-' + Validation.getElmID(node_after(first_child(elm.parentNode.parentNode))))) {
								new Insertion.After(node_after(first_child(elm.parentNode.parentNode)), advice);
							}
							advice = Validation.getAdvice(name, node_after(first_child(elm.parentNode.parentNode)));
							
							break;
						default:
							advice = '<span class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</span>';
							new Insertion.After($('img-'+elm.id), advice);
							advice = Validation.getAdvice(name, elm);
				    }
				}
				if (typeof Effect == 'undefined') {
					advice.show();
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			if (!elm.hasClassName('radio')) {
				$('img-'+elm.id).removeClassName('validation-passed-img');
				$('img-'+elm.id).removeClassName('validation-img');
				$('img-'+elm.id).addClassName('validation-failed-img');
			} else {
				node_after(first_child(elm.parentNode.parentNode)).removeClassName('validation-passed-img');
				node_after(first_child(elm.parentNode.parentNode)).removeClassName('validation-img');
				node_after(first_child(elm.parentNode.parentNode)).addClassName('validation-failed-img');
			}
			return false;
		} else {
			switch (elm.type.toLowerCase()) {
				case 'checkbox':
				case 'radio':
					var advice = Validation.getAdvice(name, node_after(first_child(elm.parentNode.parentNode)));
					break;
				default:
					var advice = Validation.getAdvice(name, elm);
			}
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			if (!elm.hasClassName('radio')) {
				$('img-'+elm.id).removeClassName('validation-failed-img');
				$('img-'+elm.id).removeClassName('validation-img');
				$('img-'+elm.id).addClassName('validation-passed-img');
			} else {
				node_after(first_child(elm.parentNode.parentNode)).removeClassName('validation-failed-img');
				node_after(first_child(elm.parentNode.parentNode)).removeClassName('validation-img');
				node_after(first_child(elm.parentNode.parentNode)).addClassName('validation-passed-img');
			}
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.add('IsAVS13', '', function(v) {
				
				var check = 0;
				digits = v.replace(/\./g,'').split('');
				
				for (var i = 0; i <= 11; i++) {
					if (i % 2 == 0) {
						check = check + digits[i] * 1;
					} else {
						check += 3 * digits[i];
					}
				}

				check = check % 10;
				check = (10 - check) % 10;

				return (check == digits[12]);
			});

Validation.add('IsAVS11', '', function(v) {
				
				var check = 0;
				digits = v.replace(/\./g,'').split('');

				check = check + (digits[0] * 5);
				check = check + (digits[1] * 4);
				check = check + (digits[2] * 3);
				check = check + (digits[3] * 2);
				check = check + (digits[4] * 7);
				check = check + (digits[5] * 6);
				check = check + (digits[6] * 5);
				check = check + (digits[7] * 4);
				check = check + (digits[8] * 3);
				check = check + (digits[9] * 2);
				
				check = check % 11;
				check = 11 - check;

				return (check == digits[10]);
			});

Validation.add('IsIBAN', '', function(v) {

				var lettres = new Array();
				lettres['0'] = 0;
				lettres['1'] = 1;
				lettres['2'] = 2;
				lettres['3'] = 3;
				lettres['4'] = 4;
				lettres['5'] = 5;
				lettres['6'] = 6;
				lettres['7'] = 7;
				lettres['8'] = 8;
				lettres['9'] = 9;
				lettres['A'] = 10;
				lettres['B'] = 11;
				lettres['C'] = 12;
				lettres['D'] = 13;
				lettres['E'] = 14;
				lettres['F'] = 15;
				lettres['G'] = 16;
				lettres['H'] = 17;
				lettres['I'] = 18;
				lettres['J'] = 19;
				lettres['K'] = 20;
				lettres['L'] = 21;
				lettres['M'] = 22;
				lettres['N'] = 23;
				lettres['O'] = 24;
				lettres['P'] = 25;
				lettres['Q'] = 26;
				lettres['R'] = 27;
				lettres['S'] = 28;
				lettres['T'] = 29;
				lettres['U'] = 30;
				lettres['V'] = 31;
				lettres['W'] = 32;
				lettres['X'] = 33;
				lettres['Y'] = 34;
				lettres['Z'] = 35;
				lettres['a'] = 10;
				lettres['b'] = 11;
				lettres['c'] = 12;
				lettres['d'] = 13;
				lettres['e'] = 14;
				lettres['f'] = 15;
				lettres['g'] = 16;
				lettres['h'] = 17;
				lettres['i'] = 18;
				lettres['j'] = 19;
				lettres['k'] = 20;
				lettres['l'] = 21;
				lettres['m'] = 22;
				lettres['n'] = 23;
				lettres['o'] = 24;
				lettres['p'] = 25;
				lettres['q'] = 26;
				lettres['r'] = 27;
				lettres['s'] = 28;
				lettres['t'] = 29;
				lettres['u'] = 30;
				lettres['v'] = 31;
				lettres['w'] = 32;
				lettres['x'] = 33;
				lettres['y'] = 34;
				lettres['z'] = 35;

		
				var check = '';
				digits = v.split('');

				for (var i = 4; i < digits.length; i++) {
					check = check + '' + lettres[digits[i]];
				}
					
				check = check + '' + lettres[digits[0]];
				check = check + '' + lettres[digits[1]];
				check = check + '' + lettres[digits[2]];
				check = check + '' + lettres[digits[3]];
				
				digits = check.split('');

				var check = digits[0];

				for (var j = 1; j < digits.length; j++) {
					
					check = check * 10;
					check = parseInt(check) + parseInt(digits[j]);
					check = check % 97;
				}

				return (check == 1);
			});

Validation.addAllThese([
	['required', 'Ce champ est obligatoire.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['requirednt', '', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-true', '', function(v) {
				return true;
			}],
	['validate-number', 'Veuillez entrer un nombre valide.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && /^[0-9]+$/.test(v));
			}],
	['validate-selection', '', function(v,elm){
				return elm.options ? elm.value != 0 : !Validation.get('IsEmpty').test(v);
			}],


	['validate-excel', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^.+\.(csv|CSV|xls|XLS|xlsx|XLSX)$/.test(v);
			}],
	['validate-nomprofession', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[A-Za-zàâäéèêëîïôöùûüÿçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ0-9\')( -]+$/.test(v);
			}],
	['validate-nomentreprise', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[A-Za-zàâäéèêëîïôöùûüÿçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ0-9\+\'\.,)( -]+$/.test(v);
			}],
	['validate-nomprenom', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[A-Za-zàâäéèêëîïôöùûüÿçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ -]+$/.test(v);
			}],
	['validate-adresse', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[A-Za-zàâäéèêëîïôöùûüÿçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ0-9\'\. -]+$/.test(v);
			}],
	['validate-npa', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[1-9][0-9]{3}$/.test(v);
			}],
	['validate-localite', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[A-Za-zàâäéèêëîïôöùûüÿçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ0-9\'\. -]+$/.test(v);
			}],
	['validate-lieux', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[0-9A-Za-zàâäéèêëîïôöùûüÿçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ\'\., -]+$/.test(v);
			}],
	['validate-telephone', '', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v.substring(1)) && /^\+[0-9]{11}$/.test(v));
			}],
	['validate-telephonech', '', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v.substring(1)) && /^0[1-9][0-9]{8}$/.test(v));
			}],
	['validate-remarques', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[A-Za-zàâäéèêëîïôöùûüÿçÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ0-9\.\'%:!@ \s-]+$/.test(v);
			}],
	['validate-reference', '', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[A-Za-z0-9/ -]+$/.test(v);
			}],
	['validate-montant', '', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && /^[0-9]+(.[0-9][0-9])?$/.test(v));
			}],
	['validate-annee', '', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && /^[1-9][0-9][0-9][0-9]$/.test(v));
			}],
	['validate-avs', '', function(v) {
				return Validation.get('IsEmpty').test(v) || Validation.get('IsAVS13').test(v);
			}],
	['validate-iban', '', function(v) {
				return Validation.get('IsEmpty').test(v) || ((/^(CH|ch)[0-9]{2}[A-Za-z0-9]{17}$/.test(v) || /^(FR|fr)[0-9]{2}[A-Za-z0-9]{23}$/.test(v)) && Validation.get('IsIBAN').test(v));
			}],
	['validate-contrat', '', function (v) {
				return Validation.get('IsEmpty').test(v) || /^CH(AG|AI|AR|BE|BL|BS|FR|GE|GL|GR|JU|LU|NE|NW|OW|SG|SH|SO|SZ|TG|TI|UR|VD|VS|ZG|ZH)\.[0-9]{2}\.[0-9]{5}$/.test(v)
			}],
	['validate-matricule', '', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && /^[0-9]+$/.test(v));
			}],
	['validate-email', '', function (v) {
				return Validation.get('IsEmpty').test(v) || /^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/.test(v)
			}],
	['validate-notiers', '', function (v) {
				return Validation.get('IsEmpty').test(v) || /^CIE[0-9]{5}$/.test(v)
			}],
	['validate-login', '', function (v) {
				return Validation.get('IsEmpty').test(v) || Validation.get('validate-notiers').test(v) || in_array(v, ['admin', 'superadmin'])
			}],
	['validate-password', 'Au moins 8 caractères, dont un chiffre, une majuscule, une minuscule et un caractère spécial', function (v) {
				//return Validation.get('IsEmpty').test(v) ||  /^[-A-Za-z0-9\(\)§°\+@%=\?!\$£#*éàèùâêîôûäëïöüç:_/]{6,}$/.test(v)
				var repass = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");

				return Validation.get('IsEmpty').test(v) || repass.test(v)
			}],
	['validate-passwordlogin', '', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^.{8,}$/.test(v)
			}],
	['validate-idem', 'Les valeurs doivent être identiques.', function (v,elm) {
				var p = elm.parentNode.parentNode;
				var options = p.getElementsByTagName('INPUT');
				var a = $A(options);
				var t = a[0].value;
				for (var i=1; i < a.length; i++) {
					if (a[i].value != t) return false;
				}
				return true;
			}],
	['validate-one-required', '', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				var a = $A(options);
				for (var i=0; i < a.length; i++) {
					if (a[i].hasClassName('radio') && a[i].checked) return true;
				}
				return false;
			}],





	['validate-percent', 'Veuillez entrer un pourcentage valide.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && /^[0-9]+$/.test(v) && v <= 100);
			}],
	
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', 'Veuillez n\'entrer que des lettres.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Zàâäçéèêëïîôöûü ,'\.-]+$/.test(v)
			}],
	['validate-alphanum', 'Veuillez n\'entrer que des chiffres et des lettres.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z0-9àâäçéèêëïîôöûü ,'\.-]+$/.test(v)
			}],
	['validate-textarea', 'Veuillez n\'entrer que des chiffres et des lettres.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z0-9àâäçéèêëïîôöûü ,'\.%-]+$/.test(v)
			}],
	
	['validate-date', 'Veuillez entrer une date valide.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\.(\d{2})\.(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) &&
							(parseInt(RegExp.$1, 10) == d.getDate()) &&
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) &&
							(parseInt(RegExp.$1, 10) == d.getDate()) &&
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
			}]
	
]);







// VALIDATION

function loadForm() {
	if($('vform') != undefined)				new Validation('vform',			{immediate: true});
	if($('vformsubmit') != undefined)		new Validation('vformsubmit',	{immediate: true, onFormValidate : submitForm});
	if($('vformnt') != undefined)			new Validation('vformnt',		{immediate: true, displayMsgs: false});

}

window.onload = function() {
	loadForm();
}
