var FormCheck_securimage = new Class({
	
	Implements: [Options, Events],
	Extends: FormCheck,

	captchaUrl: 'mooCheck.php',
	captchaElt: null,
	captchaCode: '',
	captchaError : '',
	
	initialize : function(form, options) {
		this.setOptions(options);
		this.captchaUrl = this.options.captchaUrl;
		this.form = $(form);
		this.parent(this.form,this.options);
		this.captchaElt = this.form.getElement("*[class*=captcha]");

		if ($type(this.captchaElt) == 'element') {
			this.getCaptchaCode();
			this.captchaError = ($type(formcheckLanguage.captcha)) ? formcheckLanguage.captcha : "Captcha does not match";
		}
	},

	getCaptchaCode: function() {
		new Request({
			url: this.captchaUrl,
			method: this.form.getProperty('method'),
			data : {action: 'init'},
			onSuccess: function(code){
				this.captchaCode = code;
			}.bind(this)
		}).send();
	},

	validate : function(el) {
		if (this.options.validateDisabled && el.get('disabled')) return true;
		if (this.options.trimValue && el.value) el.value = el.value.trim();

		//On valide l'element qui n'est pas un radio ni checkbox
		el.errors = [];
		el.isOk = true;
		el.validation.each(function(rule) {
			if(this.isChildType(el)) {
				if (this.validateGroup(el) == false) {
					el.isOk = false;
				}
			} else {
				var ruleArgs = [];
				if(rule.match(/^.+\[/)) {
					var ruleMethod = rule.split('[')[0];
					ruleArgs = eval(rule.match(/^.+(\[.+\])$/)[1].replace(/([A-Z\._]+)/i, "'$1'"));
				} else var ruleMethod = rule;
				if (this.regex.contains(ruleMethod) && el.get('tag') != "select") {
					if (this.validateRegex(el, ruleMethod, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				
				if (ruleMethod == 'confirm') {
					if (this.validateConfirm(el, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				if (ruleMethod == 'differs') {
					if (this.validateDiffers(el, ruleArgs) == false) {
						el.isOk = false;
					}
				}
				if (el.get('tag') == "select" || (el.type == "checkbox" && ruleMethod == 'required')) {
					if (this.simpleValidate(el) == false) {
						el.isOk = false;
					}
				}
				if(rule.match(/_[a-zA-Z0-9_]+$/) || (el.isOk && rule.match(/~[a-zA-Z0-9_]+$/))) {
					if(eval(rule.slice(1)+'(el)') == false) {
						el.isOk = false;
					}
				}
				if (ruleMethod == 'captcha') {
					if (this.validateCaptcha(el) == false) {
						el.errors.push(this.captchaError);
						el.isOk = false;
					}
				}
			}
		}, this);
		
		if (el.isOk) return true;
		else return false;
	},

	validateCaptcha: function (el) {
		if (el.get('value').toLowerCase().md5() == this.captchaCode) return true;
			return false;
	}
});

