/* ---------------------------------------------
-
-  JavaScript Form Validation Assistant
-  Version 0.79, Build 20080910
-  Thomas A. Corey, Talsoft Enterprises Inc.
-  http://www.talsoftent.com
-
-----------------------------------------------*/

if (!Array.prototype.for_each) {
	Array.prototype.for_each = function(callback) {
		var len = this.length;
		if (typeof(callback) != "function") throw new TypeError();

		for (var a = 0; a < len; a++) {
			callback.call(this[a]);
		}
	}
}

BaseValidator = function() { };

RequiredField = function(form_name, field_name, message) {
	if (typeof(form_name) !== "string") throw new TypeError();
	if (typeof(field_name) !== "string") throw new TypeError();

	this.page_form = document.forms[form_name];
	this.page_field = this.page_form.elements[field_name];
	this.error_message = message;
};

RequiredField.prototype = new BaseValidator();

RequiredField.prototype.validate = function() {
	return (this.page_field.value.length != 0);
};

FieldMethod = function(form_name, field_name, register_method, message) {
	this.page_form = document.forms[form_name];
	this.page_field = this.page_form.elements[field_name];
	this.error_message = message;
	this.validate = register_method;
};

FieldMethod.prototype = new BaseValidator();

FormValidator = function(form_name) {
	if (typeof(form_name) !== "string") throw new TypeError();
	this.page_form = document.forms[form_name];
	this.page_form.validator = this;
	this.validators = [];
	this.disabled = false;
};

FormValidator.prototype.addValidator = function(validator) {
	try {
		if (!(validator instanceof BaseValidator)) throw new TypeError("FormValidator: Failed attempt to add an invalid object type to the validators collection of this instance.");
		this.validators.push(validator);
	} catch (e) {
		alert(e.message);
	}
};

FormValidator.prototype.addValidators = function(validator) {
	this._addValidators(arguments);
};

FormValidator.prototype._addValidators = function(validators) {
	for (var a = 0; a < validators.length; a++) {
		this.addValidator(validators[a]);
	}
};

FormValidator.prototype.validate = function() {
	var router = this.validator;
	var passed = true;

	if (router.disabled) return (true);

	var messages = [];
	router.validators.for_each(function() {
		if (!this.validate()) {
			passed = false;
			messages.push(" - " + this.error_message);
		}
	});

	if (!passed) {
		var msg = "Cannot proceed due to the following error(s):\n";
		msg += messages.join("\n");
		alert(msg);
	}

	return (passed);
};

FormValidator.prototype.bind = function() {
	this.page_form.onsubmit = this.validate;
	this.page_form.onreset = function() { location.href = '/cart.aspx'; };
};
