$(function() {
	$('#content form .dateInput').date_input({
		stringToDate: stringToDate,
		dateToString: dateToString
	}).after('<img src="picture/interface/calendar_picker.gif" alt="picker" class="imgPicker" />');
	
	$('#content form .imgPicker').click(function() { 
		$(this).prev('.dateInput').focus(); 
		return false; 
	});
	
	$('#content a.help').click(function() {
		return false;
	});
	$('#content a.help').hover(function(){
		$('#helpContainer, .help_'+$(this).parent().attr('for')).show();	
	}, function() {
		$('#helpContainer, .help_'+$(this).parent().attr('for')).hide();
	});
	
	$.validator.addMethod('minDate', function(value, element, param) { 
		return stringToDate(value) >= stringToDate(param);
	}, $.format('ce champ doit être supérieure ou égal au {0}'));
	
	$.validator.addMethod('maxDate', function(value, element, param) { 
		return stringToDate(value) <= stringToDate(param);
	}, $.format('ce champ doit être inférieur ou égal au {0}'));	
	
	$('#content form').validate({
		errorPlacement: function(error, element) {
			error.appendTo(element.parent());
		},
		focusInvalid: false,
		rules: {
			loyer_actuel: {
				required: true,
				number: true
			},
			date_loyer: {
				required: true,
				minDate: '01.01.1983',
				maxDate: dateToString(new Date())
			},
			date_entree: {
				required: function() { return $('.notification:checked').val() == 0 },
				minDate: function() { return $('.notification:checked').val() == 0 ? '01.01.1983' : '' },
				maxDate: dateToString(new Date())
			}
		},
		messages: {
			loyer_actuel: {
				required: 'ce champ est requis',
				number: 'ce champ doit être numérique'
			},
			date_loyer: {
				required: 'ce champ est requis'
			},
			date_entree: {
				required: 'ce champ est requis'
			},
			date_echeance: {
				required: 'ce champ est requis'
			}									
		}
	});
	
	$('.notification').click(function() {
		if ($(this).val() == 1) {
			$('#block_date_entree').hide();
		} else {
			$('#block_date_entree').show();
		}
	});
});

function stringToDate(string) {
	var matches;
	if (matches = string.match(/^(\d{1,2})\.(\d{1,2})\.(\d{2,4})$/)) 
		return new Date(matches[3], matches[2] - 1, matches[1]);	
	else 
		return null;
}

function dateToString(date) {
	var month = (date.getMonth() + 1).toString();
	var dom = date.getDate().toString();
	if (month.length == 1) month = '0' + month;
	if (dom.length == 1) dom = '0' + dom;
	return dom + '.' + month + '.' + date.getFullYear();
}