﻿// Goodies.importGoodies(Goodies.VISCONF, Goodies.VALIDATION_BASIC);

TriggerMode = {
	FIELD_BLUR  : 0,
	FORM_SUBMIT : 1
};

VisualFormValidator = function(formName) {
	this.formName = formName;
	this.pageForm = document.forms[formName];
	this.disabled = false;
	this.validators = [];
	this.triggerMode = TriggerMode.FORM_SUBMIT;
	
	if (this.pageForm == null) {
		alert("The specified form could not be found, VisualFormValidator is now disabled.");
		this.disabled = true;
	}
};

VisualFormValidator.prototype.addValidator = function(x) {
	if (!(x instanceof BaseValidator)) throw new TypeError("Attempt to add an invalid object type to the current validator.");
	x.router = this;
	this.validators.push(x);
};

VisualFormValidator.prototype.addValidators = function(x) {
	for (var a = 0; a < arguments.length; a++) this.addValidator(arguments[a]);
};

VisualFormValidator.prototype.validate = function() { 
	var passed = true;
	
	var i = 0;
	this.router.validators.forEach(function() {
		if (!this.validate()) {
			
			this.pageField.binder.reject(this.pageField, this.errorMessage);
			passed = false;
			if (i == 0) this.pageField.scrollIntoView();
		} else {
			this.pageField.binder.accept(this.pageField);
		}
		
		i += 1;
	});
	
	return (passed);
};

VisualFormValidator.prototype.routeValidation = function() {

	if (this.value.length != 0) {
		var v = this.validator;
		if (!v.validate()){
			this.binder.reject(this, this.validator.errorMessage);
		}else{
			this.binder.accept(this, this.validator.errorMessage);
		}
	}
};

VisualFormValidator.prototype.bind = function() {
	this.pageForm.router = this;
	this.pageForm.onsubmit = this.validate;
	
	var theName, router = this;		
	this.validators.forEach(function() {
		theName = this.pageField;
		this.pageField = this.router.pageForm.elements[this.pageField];
		//alert(this.errorMessage);
		this.pageField.onblur = router.routeValidation;
		this.pageField.validator = this;
		VisualConfig.bind(this.pageField);
	});
};
