/**
 * KATIA FALCOT custom scripts
 *
 * Requires Prototype 1.6.
 *
 * @author Tournier Guillaume <guillaume@ciblo.net>
 * @legals © 2008 Ciblo SA.
 */

// If fields are not empty, calc age
function bindAges() {
	var func = function(editor) {
			var age = editor && editor.next('span.age');
			if (!editor || !age || editor.disabled) return;
			var birthday = Date.parseFormattedString(editor.value);
			var calc = calcAge(birthday);
			age.update(birthday && !isNaN(calc) ? calc + ' ans' : '');
		};
	$$('img.datePicker').each(function(img) { func(img && img.previous('input.date')) });
	$$('input.date').invoke('observe', 'blur', function(e) { func(e.element()); });
}
/**
 * Grabs calendar decorations for date input fields and make them popup the calendar.
 * This assumes the image is on the same parent element as the input field.
 */
function bindDatePickers() {
	document.observe('click', function(e) {
		var activator = e.findElement('img.datePicker');
		if (!activator) return;
		var editor = activator.previous('input.date');
		if (editor.disabled) return;
//		editor.writeAttribute('readonly', true);
		var age = editor.next('span.age'),
			onchange = age ? function() {
				var birthday = Date.parseFormattedString($F(this));
				age.update(birthday ? calcAge(birthday) + ' ans' : '');
			} : Prototype.emptyFunction,
			year = new Date().getFullYear(), birthday = editor.hasClassName('birthday'),
			minYear = birthday ? year - 110 : year,
			maxYear = birthday ? year : year + 60;
		new CalendarDateSelect(editor, {
			buttons: false, popup: 'force', onchange: onchange,
			minYear: minYear, maxYear: maxYear
		});
	});
} // bindDatePickers

// Calc age
function calcAge(birthday) {
	var today = new Date(), age = today.getFullYear() - birthday.getFullYear();
	var tm = today.getMonth(), bm = birthday.getMonth();
	return (tm == bm && today.getDate() < birthday.getDate()) || tm < bm ? age - 1 : age;
} // calcAge


document.observe('dom:loaded', function() {
	bindDatePickers();
	bindAges.delay(0.1);
});
