/*
Class: FormValidation
	

Arguments:
	el - the $(element) to apply the transformation to.
	options - optional. The options object.

Options:
	
*/

var Validation = new Class({

    Implements: Options,
    
    options: {
        checkEvent: 'blur'
    },
    
    initialize: function(frm, fields, options){
		this.setOptions(options);
		this.form = $(frm);
		this.fields = [];
		
		fields.each(function(field){
			this.fields.push({
				'field': $(field.field), // блеять...
				check: field.check,
				passed: field.passed || this.options.onPassed || $empty,
				failed: field.failed || this.options.onFailed || $empty,
				valid: -1
			});
		}, this);
		
		this.fields.each(function(record, index){
		    record.field.addEvent(this.options.checkEvent, this.onCheck.bindWithEvent(this, index));
			record.field.addEvent('change', function(){
				record.valid = -1;
			});
		}, this);
		
		this.form.addEvent('submit', (function(e){
		    if (!this.checkAll()){
				e.stop();
		    }
		}).bind(this));
    },
	
	onCheck: function(event, record){
		this.check(record);
	},
    
    check: function(record){
		with(this.fields[record]){
			if (valid == -1){
				valid = check(field, field.value);
			}
			
			var answer = valid;
			
			if ($defined(answer)){
				if (answer === true) {
					passed(field);
				} else {
					failed(field, answer);
				}
				return (answer === true);
			}
			
			return true;
		}
    },
    
    checkAll: function(){
		var passed = true;
		this.fields.each(function(field, index){
			passed = this.check(index) && passed;
		}, this);

		return passed;
    },
	
	pass: function(element){
		for (var i = 0; i < this.fields.length; ++i){
			if (this.fields[i].field == element){
				this.fields[i].valid = true;
				this.fields[i].passed(element);
				break;
			}
		}
	},
	
	fail: function(element, error){
		for (var i = 0; i < this.fields.length; ++i){
			if (this.fields[i].field == element){
				this.fields[i].valid = error;
				this.fields[i].failed(element, error);
				break;
			}
		}
	}

});
