/*
 * Bibliothèque de validation de formulaires
 * Requiert Mootools v1.1 minimum
*/

// Tableau de validations des formulaires, a remplir pour chaque formulaire (cf form.tpl)
var validation = new Array();
var validation_message = ' est requis ou invalide';
var basics = new Hash({ 'r': '.+', 'e': '^[\\w._-]+@[\\w._-]+$'});

Window.addEvent('domready', validateforms);

function validateforms() {
	$$('form.valid').each( function(f) {
		id = f.getProperty('id');
		f.addEvent('submit', function(e) { if (!validator(f, false)) new Event(e).stop(); });
		f.getElements('input').each( function(input) {
			if (input.value) checkfield(input, id);
			input.addEvent('keyup', function(e) { checkfield(input, id); });
			input.addEvent('blur', function(e) { checkfield(input, id); });
		});
		f.getElements('textarea').each( function(input) {
			if (input.value) checkfield(input, id);
			input.addEvent('keyup', function(e) { checkfield(input, id); });
			input.addEvent('blur', function(e) { checkfield(input, id); });
		});
		f.getElements('select').each( function(select) {
			select.addEvent('change', function(e) {
				checkfield(select, id);
				select.getElements('option').each( function (option) {
					if (option.hasClass('preciser') && option.selected) {
						$('r'+option.getProperty('value')).setStyle('display', 'block');
					} else if (option.hasClass('preciser')) {
						$('r'+option.getProperty('value')).setStyle('display', 'none');
					}
				} );
			} );
			select.fireEvent('change');
		});
	});
	if (window.Calendar) {
		Calendar._DN.length = Calendar._DN.length-1;
		Calendar.dayNames = Calendar._DN;
		Calendar.format = Calendar._TT["DEF_DATE_FORMAT"].replace('%Y', 'yyyy').replace('%d', 'dd').replace('%m', 'mm');
		Calendar.monthNames = Calendar._MN;
		Calendar.startDay = Calendar._FD;
	}
	$$('form.valid div.date input').each( function (input) {
		new DatePicker(input, Calendar);
	});

}

// Validation des formulaires
function validator(f, noalert) {
	var errors = Array();
	for (var i=0;i<f.elements.length;i++) {
		champ = $(f.elements[i]);
//		champ.parentNode.getElements('span').each( function(span) { span.remove(); } );
		if (['text', 'textarea', 'file', 'password', 'select-one', 'select-multiple'].contains(champ.type)) {
			if (!checkfield(champ, f.getProperty('id'))) {
				if (errors.length == 0) champ.focus();
//				if (noalert) new Element('span').appendText('!').injectAfter(champ);

				label = champ.getProperty('title') || getLabelForId(champ.name).textContent || champ.name.replace(/_/g, ' ');
				errors.push(label.substring(0,1).toUpperCase()+label.substring(1) + ' ' + validation_message);
			}
		}
	}
	if (errors.length > 0) {
		if (!noalert) { alert('- '+errors.join('\n- ')); }
		return false;
	}
	return true;
}

function getLabelForId(id) {
	var label, labels = document.getElementsByTagName('label');
	for (var i = 0; (label = labels[i]); i++) {
		if (label.htmlFor == id) return label;
	}
	return false;
} 

function checkfield(champ, formid) {
	champ = $(champ);
	value = champ.getValue();
	valid = true;
	regexps = new Array();
	// Récupérer les expressions régulières du champ (tableau validation)
	if (validation[formid] && validation[formid][champ.getProperty('id')]) { regexps = $A(validation[formid][champ.getProperty('id')]); }
	// Ajouter les classes CSS pour les vérifs basiques : (r)equis et (e)mail
	champ.className.split(' ').each( function(val) { if (basics.hasKey(val)) { regexps.push(basics.get(val)); } } );
	// Valider le champ
	if (!champ.hasClass('r') && value == '') valid = true;
	else regexps.each( function(t) {
		// Si la regexp commence par '=', on doit comparer la valeur avec celle du champ nommé par le '='
		// ex: =password : on doit vérifier que la valeur du champ à valider est égale à celle du champ 'password'
		if (t.indexOf('=') == 0) {
			field = $(t.substring(1));
			if (!field || !field.getValue || field.getValue() != value) {
				valid = false;
			}
		} else {
			if (!new RegExp(t).test(value)) { valid = false; }
		}
	 } );
	// Mettre la classe CSS
	if (valid) { champ.removeClass('missing'); }
	else { champ.addClass('missing'); }

	return valid;
}
