/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1b (2007-01-05) Customized by Tony Casparro
* 
* 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();

var language_id = 1;
if(typeof(js_language_id) == 'number')
	language_id = js_language_id;
	
	
currency_symbol = '$';	
if(language_id == 5)	currency_symbol = '&euro;';
if(language_id == 6)	currency_symbol = '&euro;';
	
var validate_lang_pack = Array()
validate_lang_pack[1] = Array();
validate_lang_pack[1]['required'] = 'This is a required field.';
validate_lang_pack[1]['validate-number'] = 'Please enter a valid number in this field.';
validate_lang_pack[1]['validate-digits'] = 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.';
validate_lang_pack[1]['validate-alpha'] = 'Please use letters only (a-z) in this field.';
validate_lang_pack[1]['validate-alphanum']  = 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.';
validate_lang_pack[1]['validate-date']  = 'Please enter a valid date.';
validate_lang_pack[1]['validate-email']  = 'Please enter a valid email address. For example fred@domain.com .';
validate_lang_pack[1]['validate-url']  = 'Please enter a valid URL.';
validate_lang_pack[1]['validate-date-au']  = 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.';
validate_lang_pack[1]['validate-currency-dollar']  = 'Please enter a valid '+currency_symbol+' amount. For example '+currency_symbol+'100.00 .';
validate_lang_pack[1]['validate-selection']  = 'Please make a selection';
validate_lang_pack[1]['validate-password']  = 'Please make sure both fields match.';
validate_lang_pack[1]['validate-phone']  = 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.';	
validate_lang_pack[1]['validate-one-required']  = 'Please select one of the above options.';

validate_lang_pack[5] = Array();
validate_lang_pack[5]['required'] = 'Dieses Feld ist ein Pflichtfeld.';
validate_lang_pack[5]['validate-number'] = 'Bitte geben Sie eine g&#00252;ltige Zahl in dieses Feld ein.';
validate_lang_pack[5]['validate-digits'] = 'Bitte geben Sie nur Zahlen in dieses Feld ein. Vermeiden Sie andere Zeichen, wie Leerzeichen, Punkte und Kommas.';
validate_lang_pack[5]['validate-alpha'] = 'Bitte geben Sie nur Buchstaben (a-z) in dieses Feld ein.';
validate_lang_pack[5]['validate-alphanum']  = 'Bitte geben Sie nur Buchstaben (a-z), oder Zahlen (0-9) in dieses Feld ein. Leerzeichen und andere Zeichen sind nicht erlaubt.';
validate_lang_pack[5]['validate-date']  = 'Bitte geben Sie ein g&#00252;ltiges Datum ein.';
validate_lang_pack[5]['validate-email']  = 'Bitte geben Sie eine g&#00252;ltige E-mail Adresse ein. Z.B. fred@domain.com .';
validate_lang_pack[5]['validate-url']  = 'Bitte geben Sie eine g&#00252;ltige URL ein.';
validate_lang_pack[5]['validate-date-au']  = 'Bitte verwenden Sie das folgende Datumsformat: dd/mm/yyyy. Z.B. 17/03/2006 f&#00252;r den 17. M&#00228;rz 2006.';
validate_lang_pack[5]['validate-currency-dollar']  = 'Bitte geben Sie einen g&#00252;ltigen '+currency_symbol+' Betrag ein. Z.B. '+currency_symbol+'100,00 .';
validate_lang_pack[5]['validate-selection']  = 'Bitte w&#00228;hlen Sie aus.';
validate_lang_pack[5]['validate-password']  = 'Stellen Sie bitte sicher, dass beide Felder &#00252;bereinstimmen.';
validate_lang_pack[5]['validate-phone']  = 'Bitte verwenden Sie nur Zahlen in diesem Feld. Vermeiden Sie andere Zeichen, wie Leerzeichen, Punkte und Kommas.';	
validate_lang_pack[5]['validate-one-required']  = 'Bitte w&#00228;hlen Sie eine der obenstehenden Optionen aus.';

validate_lang_pack[6] = Array();
validate_lang_pack[6]['required'] = 'Ce champ est onligatoire.'; 
validate_lang_pack[6]['validate-number'] = 'Veuillez entrer un num&#00233;ro valable dans ce champ.'; 
validate_lang_pack[6]['validate-digits'] = 'Veuillez n\'utiliser que des chiffres dans ce champ. Veuillez &#00233;viter les espaces et les autres caract&#00232;res tels que les points et les virgules.'; 
validate_lang_pack[6]['validate-alpha'] = 'Veuillez n\'utiliser que des lettres (a-z) dans ce champ.'; 
validate_lang_pack[6]['validate-alphanum'] = 'Veuillez n\'utiliser que des lettres (a-z) ou que des chiffres (0-9) dans ce champ. Aucun espace ou autre caract&#00232;re n\'est autoris&#00233;.'; 
validate_lang_pack[6]['validate-date'] = 'Veuillez entrer une date valable.'; 
validate_lang_pack[6]['validate-email'] = 'Veuillez entrer une adresse email valable. Par exemple, fred@domain.com.'; 
validate_lang_pack[6]['validate-url'] = 'Veuillez entrer un URL valable.'; 
validate_lang_pack[6]['validate-date-au'] = 'Veuillez utiliser le format suivant pour les dates: jj/mm/aaa. Par exemple, 17/03/2006 signifie le 17 mars 2006.';
validate_lang_pack[6]['validate-currency-dollar'] = 'Veuillez entrer un montant en '+currency_symbol+' valable. Par exemple, '+currency_symbol+' 100.'; 
validate_lang_pack[6]['validate-selection'] = 'Veuillez faire une s&#00233;lection.'; 
validate_lang_pack[6]['validate-password'] = 'Veuillez vous assurer que les deux champs soient les m&#00234;mes.'; 
validate_lang_pack[6]['validate-phone'] = 'Veuillez n\'utiliser que des chiffres dans ce champ. Veuillez &#00233;viter les espaces et les autres caract&#00232;res tels que les points et les virgules.'; 
validate_lang_pack[6]['validate-one-required'] = 'Veuillez choisir l\'une des options ci-dessus.'; 	



	
lang_pack = validate_lang_pack[language_id];

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, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : 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 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, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, 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,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		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 = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					
					var ele_name =Validation.getElmID(elm);
					if(elm.className.indexOf('validate-phone') > -1) ele_name = ele_name.substring(2);
					
					advice = '<div class="validation-advice" id="advice-' + name + '-' + ele_name +'" style="display:none">' + errorMsg + '</div>'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							if(elm.className.indexOf('validate-phone') > -1)
							{
								var p = elm.parentNode;
								if(p) {
									new Insertion.Bottom(p, advice);
								} else {
									new Insertion.After(elm, advice);
								}
							}
							else
							{
								new Insertion.After(elm, advice);
							}
							break;
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.show(); 
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide(); 
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			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) {
		var ele_name =Validation.getElmID(elm);
		if(elm.className.indexOf('validate-phone') > -1) ele_name = ele_name.substring(2);
		return $('advice-' + name + '-' + ele_name) || $('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.addAllThese([
	['required', lang_pack['required'], function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', lang_pack['validate-number'], function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', lang_pack['validate-digits'], function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', lang_pack['validate-alpha'], function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', lang_pack['validate-alphanum'], function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-date', lang_pack['validate-date'], function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', lang_pack['validate-email'], function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', lang_pack['validate-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', lang_pack['validate-date-au'], 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',lang_pack['validate-currency-dollar'], 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', lang_pack['validate-selection'], function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-password', lang_pack['validate-password'], function(v,elm){
				var pass2 = $(elm.id + "2");
				if(v  == pass2.value) return true;
			}],
	['validate-phone', lang_pack['validate-phone'], function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],				
	['validate-one-required', lang_pack['validate-one-required'], function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}]
]);
