/**
 * BS_validation.js
 *
 * Requires:
 *		String.trim()
 *		String.checkEmail()
 */
function UserRegisterValidation(fields) {
	this.fieldset = fields.fieldset;
}

UserRegisterValidation.prototype.total = 0;

UserRegisterValidation.prototype.errors = new Array();
UserRegisterValidation.prototype.error = false;

UserRegisterValidation.prototype.getDisplayObject = function(o) {
	return document.getElementById(o + '-display');
}
UserRegisterValidation.prototype.getFieldObject = function(o) {
	return document.getElementById(o);
}
UserRegisterValidation.prototype.getFieldValue = function(o) {
	return o.value.trim();
}

UserRegisterValidation.prototype.validate = function(form) {
	this.error = false;
	this.errors = new Array();
	this.total = this.fieldset.length;
	for (var i = 0; i < this.total; i++) {
		// object field
		f = this.fieldset[i];
		of = this.getFieldObject(f.id);
		value = this.getFieldValue(of);
		switch (f.type) {
			case 'string':
				if (value.length < f.min || value.length > f.max || value == '') {
					o = { error: [{errid: f.id, description: f.name + ' es obligatorio y debe tener entre ' + f.min + ' y ' + f.max + ' caracteres.'}]};
					this.error = true;
				} else {
					o = { error: [{errid: f.id, description: ''}]};
				}
				this.errors.push(o);
				break;
				
			case 'email':
				if (!value.checkEmail()) {
					o = { error: [{errid: f.id, description: f.name + ' debe ser un e-Mail v&aacute;lido.'}]};
					this.error = true;
				} else {
					o = { error: [{errid: f.id, description: ''}]};
				}
				this.errors.push(o);
				break;
		}
	}
	
	if (this.error) {
		totalErrors = this.errors.length;
		for (i = 0; i < totalErrors; i++) {
			/**
			 * TODO: check (and fix too) this error object construction...
			 */
			errorObj = this.errors[i].error[0];
			errID = errorObj.errid;
			errDescription = errorObj.description;
			
			oDisplay = this.getDisplayObject(errID);
			oInput = this.getFieldObject(errID);
			if (errDescription != '') {
				oDisplay.innerHTML = errDescription;
				oDisplay.className = 'error';
				oInput.className = 'error';
			} else {
				oDisplay.className = 'noerror';
				oInput.className = 'noerror';
			}
		}
	} else {
		form.submit();
	}
};
