/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Copyright (c) 2007 Andrew Tetlaw
*/
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.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,
			//Google changes Dan Hertz 20080222
			onFormValidate : function(result,form)
			{ return result; }, 
			onElementValidate : function(result,elm)
			{ return result; } 
		}, 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();
		}
		// Changed by Daniel Hertz 20070627 from Google Group suggestion for hidden value validation
		if(!result && this.options.focusOnError) { var first = Form.getElements(this.form).findAll(function(elm) { return $(elm).hasClassName('validation-failed')}).first();
		if ( first.type != "hidden" ) {
			first.focus();
			}
	}
	//Google Changes Dan Hertz 20080222
		var onFormValidateResults =
		this.options.onFormValidate(result, this.form);
		if (onFormValidateResults != undefined){
		results = onFormValidateResults;
		}
        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;
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" 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:
							new Insertion.After(elm, advice);
				    }
					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');
			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) {
		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.addAllThese([
	['required', 'This is a required field.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Please enter a valid number in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', 'Please use whole numbers only (no dots or commas).', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', 'Please use letters only (a-z)', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9). No spaces or other characters are allowed.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
			/* Deleted this to use altered date checker below Daniel Hertz 20070727
	['validate-date', 'Please enter a valid date.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
			*/
	['validate-date', 'Please use this date format: m/dd/yyyy. For example 3/17/2007 for the 17th of March, 2007.', function(v) {
                if(Validation.get('IsEmpty').test(v)) return true;
                var regex = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
                if(!regex.test(v)) return false;
                var d = new Date(v.replace(regex, '$1/$2/$3'));
                return ( parseInt(RegExp.$1, 10) == (1+d.getMonth()) ) &&
                       (parseInt(RegExp.$2, 10) == d.getDate()) &&
                       (parseInt(RegExp.$3, 10) == d.getFullYear() );
            }], 
	['validate-email', 'Please enter a valid email address. For example, joe@domain.com', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', 'Please enter a valid URL. For example, http://mydomain.com', 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{1,2})\/(\d{1,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)//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', 'Please select an item from the dropdown list.', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', 'Please select one of the options from the list.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}],
//  Custom classes by Daniel Hertz 20070627 and Google group
// You can call a backend program to check if username is taken, and show response.
	['validate-unique-user-name', 'This user name is already taken', function(v) {
				var theRequest = new Ajax.Request('/check/', { method: 'post', asynchronous: false, parameters: 'user_name='+v });
				return theRequest.transport.responseText;
	}],
	['validate-screen-name', 'This screen name is already taken', function(v) {
				var theRequest = new Ajax.Request('/check/', { method: 'post', asynchronous: false, parameters: 'screen_name='+v });
				return theRequest.transport.responseText;
	}],
//A minimum of 15 digits for credit cards
	['validate-credit-card', 'Please enter a valid Credit Card number.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  /^[\d]{15,19}$|^([\d]{4})( |-)?([\d]{6})( |-)?([\d]{5})$|^([\d]{4})( |-)?([\d]{4})( |-)?([\d]{4})( |-)?([\d]{4})$/.test(v);
	}], 
	['validate-zip-us', 'Please enter a valid American zip code. Ex:"12345" or "12345-6789"', function(v) {
				var varZip = /^\d{5}([\-]\d{4})?$/;
				return Validation.get('IsEmpty').test(v) || varZip.test(v);
    }],
	['validate-zip-us-ca', 'Please enter a valid US Zip or Canadian Postal Code.', function(v) {
            v = v.toUpperCase();
            return Validation.get('IsEmpty').test(v) ||  /^(\d{5}(( |-)\d{4})?)|([A-Za-z]\d[A-Za-z]( |-|)\d[A-Za-z]\d)$/.test(v);
            }], 
	['validate-postal-code', 'Please enter a valid postal code. Allowed chars: a-z,A-Z,0-9,-,space', function(v) {
				var varPostalCode = /^[-\w\d\s]+$/;
				return Validation.get('IsEmpty').test(v) || varPostalCode.test(v);
    }],
	['validate-areacode', 'Please enter a three (3) digit number. Ex:"202"', function(v) {
				var varTel = /^\b\d{3}$/;
				return Validation.get('IsEmpty').test(v) || varTel.test(v);
    }],
	['validate-tel', 'Please enter a seven (7) digit phone number with dash. Ex:"212-2121"', function(v) {
				var varTel = /^\b\d{3}-\d{4}$/;
				return Validation.get('IsEmpty').test(v) || varTel.test(v);
    }],
	['validate-select', 'Please select an item from the drop-down menu.', function(v,elm){
				var varDropdown = /^(SELECT)|(-1)|(- -)|(0)$/;
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
    }],
	['validate-pass', 'min 6 chars, max 20 chars, Allowed chars: a-z,A-Z,0-9, - @ & #"', function(v) {
				var varPass = /^[@\#\&\-\w\d\s]+$/;
				return Validation.get('IsEmpty').test(v) || varPass.test(v);
    }],
	['validate-title', 'Only the following characters are allowed: a-z A-Z 0-9 . , ! \' -', function(v) {
				var varTitle = /^[\'\-\.\,\!\;\:\w\d\s\(\)]+$/;
				return Validation.get('IsEmpty').test(v) || varTitle.test(v);
    }],
	['validate-alphanum-extended', 'Only the following characters are allowed: a-z A-Z 0-9 . , -', function(v) {
				var varAlphaNumX = /^[-\.\,\w\d\s]+$/;
				return Validation.get('IsEmpty').test(v) || varAlphaNumX.test(v);
    }],
	['validate-words', 'Only the following characters are allowed: a-z A-Z 0-9 . ,? ! \' -', function(v) {
				var varWords = /^[@\#\&\'\-\?\.\,\!\;\:\w\d\s\(\)]+$/;
				return Validation.get('IsEmpty').test(v) || varWords.test(v);
    }],
	['validate-text', 'Only the following characters are allowed: a-z A-Z 0-9 . , ! \' -', function(v) {
				var varTheText = /^[-\.\w\d\s\(\)]+$/;
				return Validation.get('IsEmpty').test(v) || varTheText.test(v);
    }],
	['validate-www', 'Please enter a valid URL. For example: "mywebsite.com"', function(v) {
				var varWWW = /^[-\_\.\w\d]+$/;
				return Validation.get('IsEmpty').test(v) || varWWW.test(v);
    }],
	['validate-email-multiple', 'Please enter one or more email addresses separated by a comma. For example fred@domain.com,jane@sample.com', function (v) {
				var varEmailMultiple = /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+(([,;.]([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/;
				return Validation.get('IsEmpty').test(v) || varEmailMultiple.test(v);
			}],
	['validate-tags', 'Tags can only have letters, numbers, hyphen, bracket, comma or period."', function(v) {
				var varTags = /^[\-\.\,\(\)\w\d\s]+$/;
				return Validation.get('IsEmpty').test(v) || varTags.test(v);
    }],
	['validate-phone', 'Tags can only have letters, numbers, hyphen, bracket, comma or period."', function(v) {
				var varTags = /^[\-\.\,\(\)\w\d\s]+$/;
				return Validation.get('IsEmpty').test(v) || varTags.test(v);
    }],
	['validate-checkbox', 'Please select one or more items from the list.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}],
	['validate-radio-group', 'Please select an item from the list.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}],
	['validate-one-required-table', 'Please select one of the above options.', function (v,elm) {
				var table = elm.up('table');
				var options = table.getElementsByTagName('INPUT'); 
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}],
	['validate-upc', 'Please enter a 12 digit UPC number. For example, "123456789012"', function(v) {
				var varUpc = /^\d{12}?$/;
				return Validation.get('IsEmpty').test(v) || varUpc.test(v);
    }],

	['validate-ean', 'Please enter a 13 digit EAN-13 number. For example, "1234567890123"', function(v) {
				var varEan = /^\d{13}?$/;
				return Validation.get('IsEmpty').test(v) || varEan.test(v);
    }],
	['validate-gtin', 'Please enter a 14 digit UPC number. For example, "00123456789012"', function(v) {
				var varGtin = /^\d{14}?$/;
				return Validation.get('IsEmpty').test(v) || varGtin.test(v);
    }],
	['validate-cspc', 'Please enter a 5-8 digit CSPC number. For example, "00123456"', function(v) {
				var varCspc = /^(\d{5})|(\d{6})|(\d{7})|(\d{8})?$/;
				return Validation.get('IsEmpty').test(v) || varCspc.test(v);
    }],
	//Is fire hot or cold?
	['validate-antispam-fire', 'Incorrect answer. Please try again.', function(v) {
				var varFire = /^[hH]ot$/;
				return Validation.get('IsEmpty').test(v) || varFire.test(v);
    }],
	//What is (5 times 2) minus 3?
	['validate-antispam-math', 'Incorrect number. Please try again.', function(v) {
				var varMath = /^6|[sS]ix$/;
				return Validation.get('IsEmpty').test(v) || varMath.test(v);
    }]
]);