/**
 * => Mootools 1.2
 * 	=> Core
 * @classDescription
 * Classe permettant de vérifier un champs de formulaire en live
 * @author M@nu/Baphira
 */
var FieldChecker = new Class({
	
	/**
	 * @param {Element} form
	 * @param {String} fieldName
	 * @param {Function} checkFunct (return true or false)
	 * @param {Object[]} args
	 */
	initialize: function(formEl, fieldName, checkFunct, argsFunct) {
		this.formEl = formEl;
		this.field = formEl.getElements('[name='+fieldName+']');
		if(this.field.length <= 0) {
			return;
		}
		this.fieldType = this.field[0].getProperty('type');
		this.checkFunct = checkFunct;
		this.argsFunct = argsFunct;
		this.addEvents();
    },
	
	addEvents: function() {
		if (this.fieldType == 'text' || this.fieldType == 'password') {
			this.field.addEvent('keyup', function(e){
				this._check();
			}.bind(this));
			this.field.addEvent('blur', function(e){
				this._check();
			}.bind(this));
		}
		if (this.fieldType == 'text' || this.fieldType == 'radio' || this.field[0].get('tag') == 'select' || this.fieldType == 'checkbox') {
			this.field.addEvent('change', function(e){
				this._check();
			}.bind(this));
		}
	},
	
	_check: function() {
		try {
  			if (this.checkFunct.run(this.argsFunct)) {
				this.showValid();
			} else {
				this.showInvalid();
			}
  		} catch(e) {
  			//le champs n'existe pas dans ce formulaire
  		}
	},
	
	check: function() {
		if (!formEl.hasClass('already-checked')) {
			return;
		}
		this._check();
	},
	
	showValid: function() {
		this.field.each(function(el) {
			el.addClass('form-valid');
			el.removeClass('form-invalid');
		});
		this.changeImage(this.field[this.field.length-1], 'valid');
	},
	
	showInvalid: function() {
		this.field.each(function(el) {
			el.addClass('form-invalid');
			el.removeClass('form-valid');
		});
		this.changeImage(this.field[this.field.length-1], 'invalid');
	},
	
	changeImage: function(el, type) {
		var container = el.getParent().getElement('.validation');
		if($chk(container)) {
			var img = container.getElement('img');
			if(!$chk(img)) {
				img = new Element('img').inject(container);
			}
			if(type == 'valid' && $chk(validSrc)) {
				img.setProperty('src',validSrc);
			} else if(type == 'invalid' && $chk(invalidSrc)) {
				img.setProperty('src',invalidSrc);
			}	
		}
	}
});
