
$(function(){
	var updateVille = function() {
		$('#search_ville optgroup').hide();
		$('#search_ville optgroup').each(function(){
			if($(this).attr('label') == $('#search_departement').val()) {
				$(this).show();
				$('#search_ville').val($($('option', this)[0]).attr('value'));
			}
		});	
	}
	updateVille();
	$('#search_departement').change(updateVille);
	
	// Si on a une valeur de définie pour le champ ville, on la remet au chargement de la page
	if("<?= $this->searchEngine->getElement('search_ville')->getValue(); ?>") {
		$('#search_ville').val("<?= $this->searchEngine->getElement('search_ville')->getValue(); ?>");
	}
	
	
function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }    return s.join(dec);
}	
	
	
	// Script de simulation d'emprunt
	$('#calculer').click(function(){
		var mensualites = 0;
		var total		= 0;
		var capital		= $('#montant').val().replace(',','.').replace(' ','');
		var taux		= $('#taux').val().replace(',','.').replace(' ','');
		var nbMensualites = $('#duree').val().replace(',','.').replace(' ','') * 12;

		if(!isNaN(capital) && !isNaN(taux) && !isNaN(nbMensualites) && capital != '' && taux != '' && nbMensualites != '') {
			mensualites = ( (capital * (taux/12)) / ( 100 * (1 - Math.pow( ( 1 + (taux/1200) ), -nbMensualites) ) ) );
			total = mensualites * nbMensualites;
			
			$('#mensualite').val(number_format(mensualites, 2, ',', ' ') + ' €');
			$('#total').val(number_format(total, 2, ',', ' ') + ' €');
		}
		else {
			$('#mensualite').val('');
			$('#total').val('');
		}
	});
});
