Tauri.RegistrationError = Class.create({
	message: '',
	field:   null,
	initialize : function (fieldName, messageId) {
		this.message = fieldName + ' - ' + Tauri.Lang.get(messageId);
	}
});

Tauri.RegistrationField = Class.create({
	id:        null,
	required:  false, 
	minlength: 0, 
	maxlength: 0,
	initialize : function (id, opts) {
		var t = this;
		this.id = id;
		$H(opts).each(function (p) {
			t[p.key] = p.value;
		});
	},
	validate : function () {
		var value = $F(this.id);
		if (value.strip() === '' && this.required) {
			throw new Tauri.RegistrationError(this.name, 'fieldRequired');
		}
		if ((this.minlength > 0 && this.minlength > value.length) ||
		    (this.maxlength > 0 && this.maxlength < value.length)) {
			throw new Tauri.RegistrationError(this.name, 'wrongLength');
		}
		if (this.id === 'password' && value !== $F('retype_' + this.id)) {
			throw new Tauri.RegistrationError(this.name, 'passMismatch');
		}
		return true;
	}	
});

Tauri.Registration = Class.create({
	fields : null,
	initialize : function () {
		this.fields = $H();
	},
	addField : function (fieldId, opts) {
		this.fields.set(fieldId, (new Tauri.RegistrationField(fieldId, opts)));
	},
	errors : function (errors) {
		var msgs, box = $('messagesSpace').update();
		if (errors.length) {
			 msgs = (new Element('div')).addClassName('messages');
			 errors.each(function (error) {
			 	msgs.insert(
			 		(new Element('p')).insert(error.escapeHTML())
			 	);
			 });
			 box.insert(msgs);
			 //window.location.href = '#messagesSpace';
			 return false;
		}
		return true;
	},
	register : function () {
		var errors = [];
		this.fields.each(function (p) {
			try {
				p.value.validate();
			} catch (e) {
				errors.push(e.message);
			}
		});
		if (this.errors(errors)) {
			$('registerForm').submit();
		}
	},
	checkPass : function () {
		try {
			this.fields.get('reg-password').validate();
		} catch (e) {
			this.errors([e.message]);
		}
	}
});
Tauri.Registration = new Tauri.Registration();
