﻿var RootUrlOn = '';
var RootUrlOff = '';
var Validator = Class.create();

function SetFormElmError(elmId, errorMsg)
{
    setErrorElm(elmId);
    setErrorImgElm($('imgFormCheck_'+elmId), errorMsg);
}
function SetFormElmPass(elmId)
{
    setPassElm(elmId);
    setPassImgElm($('imgFormCheck_'+elmId));
}

function resetPassElm(elmId)
{
    try 
	{
		$('label_'+elmId).removeClassName('error');
	}
	catch(ex)
		{ alert('label_'+elmId + ' undefined resetPassElm !');}

}

function setPassElm(elmId)
{
    try 
	{
		$('label_'+elmId).removeClassName('error');
	}
	catch(ex)
		{ alert('label_'+elmId + ' undefined setPassElm !');}
}

function setErrorElm(elmId)
{
   try 
	{
		$('label_'+elmId).addClassName('error');
	}
	catch(ex)
		{ alert('label_'+elmId + ' undefined setErrorElm !');}
	
}

var myFormError = new FormError();
function setErrorImgElm(imgFormCheck, errorMsg)
{
    imgFormCheck.src = RootUrlOn;
    imgFormCheck.alt = errorMsg;
    myFormError.set(imgFormCheck.id, errorMsg, true);
}
function setPassImgElm(imgFormCheck)
{
    imgFormCheck.src = RootUrlOff;
    imgFormCheck.alt = '';
    myFormError.set(imgFormCheck.id, '', false);
}

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.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, button, panelElmId, rootUrlOn, rootUrlOff , options){
		this.options = Object.extend({
		
		    onButtonClick : true,
			onSubmit : false,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			showErrorPanel : true,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		this.button = $(button);
		this.panelElm = $(panelElmId);  
		
		RootUrlOn = rootUrlOn;
		RootUrlOff =rootUrlOff;
		
		if(this.options.onButtonClick) 
		{ 
		        Event.observe(this.button,'click',this.onClick.bind(this),false); 
		}
			
		if(this.options.onSubmit) 
		{ 
		    Event.observe(this.form,'submit',this.onSubmit.bind(this),false); 
		}

		if(this.options.immediate) 
		        {
			        var useTitles = this.options.useTitles;
			        var callback = this.options.onElementValidate;
			        var panelElmId = this.panelElm.id;
			        var showErrorPanel = this.options.showErrorPanel;
			        var immediate = this.options.immediate;
			
			        Form.getElements(this.form).each(function(input) { // Thanks Mike!
				    Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback, showErrorPanel : showErrorPanel, immediate : immediate}, panelElmId); });
			        });
		        }
	},

	onClick :  function(ev){    //alert('click on ' + this.panelElm.id );
		if(!this.validate()) Event.stop(ev);
	},
	
	onSubmit :  function(ev){ 
		if(!this.validate()) Event.stop(ev);
	},

	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		var showErrorPanel = this.options.showErrorPanel;
		var immediate = this.options.immediate;
		
		// Show error Panel on submit same if Imediate = true;
		immediate = "onsubmit";
		var panelElmId = this.panelElm.id;
		
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback, showErrorPanel : showErrorPanel, immediate : immediate },panelElmId); });
		} else {
		    
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback, showErrorPanel : showErrorPanel, immediate : immediate   },panelElmId); }).all();
		}
		if(!result && this.options.focusOnError) 
		{
		    try 
		    {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
			}
			catch(ex)
			{}
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options, panelElmId){
	
		options = Object.extend({
			useTitle : false,
			showErrorPanel : false,
			immediate : false,
			onElementValidate : function(result, elm) {}
		}, options || {});


		elm = $(elm);
		panelElm = $(panelElmId);
		
	       //alert('Validation.validate(isChildOf:' + elm.childOf(panelElm) + ' --> ' + panelElm.id + ',' + elm.id + ':' + elm.name);
		if (elm.childOf(panelElm))   // Si l'?ment appartient au panel ?urveiller
		{
		    var cn = elm.classNames();
		    return result = cn.all(function(value) {
			    var test = Validation.test(value,elm,options.useTitle,options.showErrorPanel, options.immediate);
			    options.onElementValidate(test, elm);
			    return test;
		    });
		}
		else
		{
		    return true;
		}
		
	},
	test : function(name, elm, useTitle, showErrorPanel, immediate) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
	  try 
	  {

		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) 
		{
		    var errorMsg;
		    if (immediate=='onsubmit') elm[prop]='';
		    
			if(!elm[prop])              
			{
			     if ((immediate) || (immediate=='onsubmit'))
			     {
			        var imgFormCheck;
					
			         switch (elm.type.toLowerCase()) 
				            {
				                case 'select-one' : 
					            case 'checkbox':
					            case 'radio':
						            var p = elm.parentNode;
						            if(p) { imgFormCheck = $('imgFormCheck_' + p.id)
							              }
						            break;
					            default:
						            imgFormCheck = $('imgFormCheck_' + elm.id);
			                }
			             //finNew   
			        if (imgFormCheck!=null)
			        {
			            errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
              	        setErrorImgElm(imgFormCheck, errorMsg);
            	    }
            	    else
		            {  alert('<img id="imgFormCheck_' + elm.id + '" /> not found in the source page *1* !');
		            }
			     }
			}
			
			if (showErrorPanel) elm[prop] = true;
				switch (elm.type.toLowerCase()) 
					{
    					case 'select-one' : 
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) setErrorElm($(p).id);
							break;
						default:
                            setErrorElm(elm.id);
				    }
			return false;
		} 
		else 
		{
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
	        var imgFormCheck;

            switch (elm.type.toLowerCase()) 
	            {
	                case 'select-one' : 
		            case 'checkbox':
		            case 'radio':
			            var p = elm.parentNode;
			            if(p) { imgFormCheck = $('imgFormCheck_' + p.id)
				              }
			            break;
		            default:
			            imgFormCheck = $('imgFormCheck_' + elm.id);
                }
                
             //finNew   
             
			
		    if (imgFormCheck!=null)
		    {
		            setPassImgElm(imgFormCheck);
			}
			else
			{  
			    // alert('<img id="imgFormCheck_' + elm.id + '" /> not found in the source page *2*!'); 
			}
				// New
				switch (elm.type.toLowerCase()) 
					{
					    case 'select-one' : 
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) setPassElm($(p).id);
							break;
						default:
			                      setPassElm(elm.id);
				    }
				  //FinNEw  
			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] = '';
			}
			var imgFormCheck;
				switch (elm.type.toLowerCase()) 
					{
					    case 'select-one' : 
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {   imgFormCheck = $('imgFormCheck_' + p.id); }
							break;
						default: imgFormCheck = $('imgFormCheck_' + elm.id);
				    }

		    if (imgFormCheck!=null)
		    {   setPassImgElm(imgFormCheck);
			}
			else
			{  alert('<img id="imgFormCheck_' + elm.id + '" /> not found in the source page (or imgFormCheck_' + elm.parentNode.id + ' for radio and checkbox options) !'); 
			}
				switch (elm.type.toLowerCase()) 
					{
					    case 'select-one' : 
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) resetPassElm($(p).id);
							break;
						default:
						        resetPassElm(elm.id);
				    }
		});
	},
	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));
			});






/* UTF-8 saved file */ 

Validation.addAllThese([
	['required', 'Ce champ est obligatoire.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Veuillez saisir un nombre valide dans ce champ.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],											
	['validate-number-special-Bonus', 'Veuillez saisir un nombre valide compris entre 0.5 et 2 dans ce champ.', function(v) {
				if((parseFloat(v)>=0.5)&&(parseFloat(v)<=2)){return true;}else{return false;}
			}],										
	['validate-digits', 'Veuillez à n\'utiliser que des chiffres dans ce champ. Veuillez ne pas utiliser d\'espaces ou d\'autres caractères comme le point ou la virgule.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', 'Veuillez à n\'utiliser que des lettres (a-z) dans ce champ.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Veuillez à n\'utiliser que des lettres (a-z) ou des chiffres  (0-9) dans ce champ. Aucun espace ou autre caractère n\'est autorisé.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-names', 'Veuillez à n\'utiliser que des lettres (a-z), accentuée ou pas, ou bien l\'espace, le tiret et l\'apostrophe. Aucun autre caractère n\'est autorisé.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-ZàäâéèêëîïôöùüûçÀÄÂÉÈÊËÎÏÔÖÙÜÛÇ' \-]+$/.test(v)
			}],			
	['validate-date', 'Veuillez saisir une date valide.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', 'Veuillez saisir une adresse email valide, par exemple : nom@domaine.fr', function (v) {
					// Séquence obligatoire pour accepter xxxx@xxx...  yyyy¤*#xxx@xxx so will be accepted 
				//t = '¤*#' + v; 
				return Validation.get('IsEmpty').test(v) || /^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+((\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)?)+@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?$/.test(v)
				// oldTest : return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)

				
				// Séquence obligatoire pour accepter xxxx@xxx...  yyyy¤*#xxx@xxx so will be accepted 
				//t = '¤*#' + v; 
				//return Validation.get('IsEmpty').test(v) || /[¤][*][#]\w{1,}([.1]([\w\-]{1,})){0,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(t)
				// oldTest : return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', 'Veuillez saisir une URL valide.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp|news):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', 'Veuillez utiliser ce format de date: jj/mm/aaaa. Par exemple 24/03/2006 pour le 24 mars 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', 'Veuillez saisir une somme valide en $ dollars. Par exemple $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)
			}],
			
	['validate-currency-euro', 'Veuillez saisir une somme valide en € euro. Par exemple €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)
			}],
			
	['validate-selection', 'Veuillez à faire une sélection.', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
			
	['validate-radio-one-required', 'Veuillez s&eacute;lectionner l\'une des options pr&eacute;c&eacute;dentes !', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) { return ($F(elm)!=null); });
			}],
			
	['validate-select-all-required', 'Veuillez renseigner les listes précédentes !', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('select');
			    return !($A(options).any(function(elm) { return ($F(elm)==''); }));
			}]			
			
			
]);
