var perio, t, ntot, capi, eche, devise;
ntot  = 12;
function veriform(form) {
	capi  = form.capit.value;
	perio = form.periode.options[form.periode.selectedIndex].value;
	t     = parseFloat(form.tclient.value)/(100 * perio);
	var ans = parseInt(form.durans.options[form.durans.selectedIndex].value);
	var mois = form.durmois.options[form.durmois.selectedIndex].value;
	ntot = parseInt((ans + (mois / 12)) * perio);
	//Affiche les calculs simulés
	form.tdure.value = ntot; 
	eche = ECHEANCE(capi, t, ntot); 
	form.echu.value = fix(eche, 2, ",");
	form.total.value = fix(ntot * eche, 2, ",");
	form.teg.value  = fix(TACTU(t,perio),3, ",");
	devise = 'Francs';
	if (form.cdevise[1].checked) devise = 'Euros';
	}

function capacite(form) {
	var capa  = parseInt(form.capacit.options[form.capacit.selectedIndex].value);
	perio = form.periode.options[form.periode.selectedIndex].value;
	t     = parseFloat(form.tclient.value)/(100 * perio);
	var ans = parseInt(form.durans.options[form.durans.selectedIndex].value);
	var mois = form.durmois.options[form.durmois.selectedIndex].value;
	ntot = parseInt((ans + (mois / 12)) * perio);
	//Affiche les calculs simulés
	form.tdure.value = ntot;
    with (Math) {
        capi = round(capa * (pow((1+t),ntot) - 1) / (100 * t * pow((1+t),ntot))) * 100; 
		}
	eche = ECHEANCE(capi, t, ntot); 
	form.capit.value = fix(capi, 0, ",");
	form.echu.value = fix(eche, 2, ",");
	form.total.value = fix(ntot * eche, 2, ",");
	form.teg.value  = fix(TACTU(t,perio),3, ",");
	devise = 'Francs';
	if (form.cdevise[1].checked) devise = 'Euros';
	}
	
function aidepret() {
	var aideFenetre = window.open("","","status = 0, scrollbars=1,resizable=1,width=700,height=310") 
	aideFenetre.document.write(
	'<HTML><HEAD><TITLE>ImmoDHEM : Aide sur le calcul des mensualites du pret</TITLE></HEAD><BODY text="Black" link="Black" vlink="Black" alink="Black"><basefont size=4><center>'+
	'<table width=350 border=5 bgcolor=lightsteelblue>'+
	'<tr><th bgcolor=steelblue colspan=3 align=center><font size=+2>PRETS BANCAIRES</th></tr>'+
	'</table></center><br><font size="-1">'+
	'Ce programme vous permet, connaissant un capital emprunté, le nombre d\'échéances avec la périodicité et le taux du crédit, de simuler les résultats.<br>'+
	'Les valeurs décimales sont indifférement saisies avec un point ou la virgule comme séparateur décimal.<BR>'+
	'<b>Le résultat de la simulation comporte :</b><i><BR>'+
	'<li>Le total des remboursements.'+
	'<li>Le montant de l\'échéance.'+
	'<li>Le nombre entier d\échéances.'+
	'<li>Le taux effectif global en tenant compte de la composition périodique des intérêts.'+
	'<li>Le tableau d\'amortissement détaillé.<br></i></font>'+
	'<center><form><input type=button value="Fermer" onClick="self.close();"></form></center>'+
	'</BODY></HTML>')
	aideFenetre.document.close()
}

function CUMULEPARGNE(form) {
    capi    = parseFloat(form.capital.value);
    var tx  = parseFloat(form.taux.value) / 100;
	var ans = parseInt(form.durans.options[form.durans.selectedIndex].value);
	var mois = form.durmois.options[form.durmois.selectedIndex].value;
	perio = form.periode.options[form.periode.selectedIndex].value; 
	var n = ans + (mois/12);
	ntot = parseInt((ans + (mois / 12)) * perio);
    var rente = parseFloat(form.rente.value);
	//Calcul actuariel du solde agios cumulés
	var solde =  ARRET(capi, rente, tx, perio, ntot);
	form.valfinal.value = fix(solde,2,",");
}

function RENTEPEL(form) {
    capi     = parseFloat(form.capital.value);
    var tx   = parseFloat(form.taux.value) / 100;
    var cib  = parseFloat(form.cible.value);
	perio = form.periode.options[form.periode.selectedIndex].value;
	var ans  = parseInt(form.durans.options[form.durans.selectedIndex].value);
	ntot = parseInt(ans * perio);
	// initialisations
    var test_calcul, test_prec, rente_prec, k;
	var rente = (capi  - cib) / ntot;   
	var pas   = 100;
    var limite = 0.0001;
	var prov =  ARRET(capi, -rente, tx, perio, ntot);
	test_calcul = prov - cib  
    test_prec = test_calcul;
	k = 0;
    while (Math.abs(test_calcul)>limite && k<100) {
		k++
        rente_prec = rente;
        rente      = rente + pas;      // nouvelle rente
        test_calcul = ARRET(capi, -rente, tx, perio, ntot) - cib;
        if (test_calcul * test_prec >0 && Math.abs(test_calcul) > Math.abs(test_prec)) {
        	pas = - pas;
            rente = rente_prec;
            }
        if (test_calcul * test_prec <0) {
        	rente = rente_prec;
            pas = 0.5 * pas;
            }
        }
    rente = fix(rente, 0, ".");
	form.rente.value = rente;
	//alert("Itérations = " + k + " écart de calcul = " + fix(test_calcul, 2, ".") + "\nRésultat = " + fix(rente, 2, ".") + "\nNbre versements = "+ ntot );
}

function EPARGNEPEL(form) {
    capi    = parseFloat(form.capital.value);
	var el = form.PELCEL.options[form.PELCEL.selectedIndex].value;
	PARAMPEL(el);
	var ans = parseInt(form.durans.options[form.durans.selectedIndex].value);
	perio = form.periode.options[form.periode.selectedIndex].value; 
	ntot = parseInt(ans * perio);
    var rente = parseFloat(form.rente.value);
	if (rente * perio < 3600) {
		alert ("Versement insuffisant minimum 3600 Francs l'an !"); 
		return false;
		}
	var plafond = 10000;
	var maxint 	= plafond * denomin / numerat;
	if (ans <4) {
		numerat = 1;
		tepel = (denomin - numerat) * tpel / denomin;
		maxint = (denomin  - numerat) * maxint / denomin;
		denomin = denomin - numerat;
		}
	var maxprime = numerat * maxint / denomin;
	//Calcul actuariel du solde agios cumulés
	
	var epargne = capi;
	var interbr, solde, stop, i, nl;
	stop = 0;
	with (Math) {
		var  Utx  = pow((1 + tpel/100), 1/perio);	
		var Y = Utx;
		//form.tn_bp.value  = fix(round(100000 * perio * (pow(1 + tpbp / 100, 1 / perio) - 1))/1000, 3, ",");
		solde  =  capi;
		var preced = capi * Utx;
		for (i = 1; i< ntot; i++) {
			epargne  += rente;
			solde     = (preced + rente) * Y
			if (stop == 0 && (solde -epargne)>maxint) {
				nl = log(maxint + epargne) / (preced + rente)/ log(Y);
				stop = 1;
				solde = (preced + rente)* pow(Y, nl);
				Y = pow((1 + tpbp/100), 1/perio);
				solde *= pow(Y, (1 - nl));
				}
			interbr = solde  - epargne;
			if (stop ==0) {
				prime = numerat * interbr / denomin;
				}
			else {	
				prime = maxprime;
				}
			preced = solde;
		}
	}
	form.epargne.value = fix(epargne,0,",");
	form.valfinal.value = fix(solde,2,",");	
	form.interbrut.value = fix(interbr, 2,",");
	form.prime.value = fix(prime, 2, ",");
	if (stop ==1) {
		//Calcul pour tenir comptye de la réduction du taux
		flux = new makeArray(2);
		flux[1]  = new MakeFlux(rente, ntot - 1);
		flux[2]  = new MakeFlux(-solde, ntot);
		var taux  = TEQUIV(-capi, 0, 0, perio, flux);
		form.tn_cl.value  = fix(TACTU(taux / (100 * perio), perio), 3, ",");
		}
	else {	
		form.tn_cl.value  = fix(tpel, 3, ",");
		}
	return true;
}

function PARAMPEL(el) {

	if (el == "PEL 4.50 %") {
		tpel = 4.50;
		tpbp = 3.27;
		numerat = 2;
		denomin = 7;
		}
	
	if (el == "PEL 3.60 %") {
		tpel = 3.6;
		tpbp = 2.61;
		numerat = 2;
		denomin = 7;
		}
	if (el == "PEL 4.00 %") {
		tpel = 4.0;
		tpbp = 2.90;
		numerat = 2;
		denomin = 7;
		}
	if (el == "PEL 4.25 %") {
		tpel = 4.25;
		tpbp = 3.10;
		numerat = 2;
		denomin = 7;
		}
	if (el == "PEL 5.25 %") {
		tpel = 5.25;
		tpbp = 3.84;
		numerat = 2;
		denomin = 7;
		}
	if (el == "PEL 6.00 %") {
		tpel = 6.0;
		tpbp = 4.62;
		numerat = 1;
		denomin = 4;
		}
	if (el == "PEL 7.50 %") {
		tpel = 7.5;
		tpbp = 4.75;
		numerat = 2;
		denomin = 5;
		}
}

function makeArray(n) {
        this.length = n;
        for (var i=0 ; i<=n ; i++) { this[i]= 0 }
        return this;
        }

function MakeFlux(echeance, dure) {
        this.echeance  = echeance;
        this.dure      = dure;
        return this;
        }

function TEQUIV(cap, dossier, assur, p, fl) {
        var limite = 0.000001;
        var pas = 2;
        var t_calcul = 3;
        var t   = t_calcul / (100 * p);
        var test_calcul = cap - dossier - VACTUEL(fl, assur, t);
        var test_prec = test_calcul;
        var t_prec;

        while (Math.abs(test_calcul)>limite) {
                t_prec      = t_calcul;
                t_calcul    = t_calcul + pas;
                t           = t_calcul / (100 * p);
                test_calcul = cap - dossier - VACTUEL(fl, assur, t);
                if (test_calcul * test_prec >0 && Math.abs(test_calcul) > Math.abs(test_prec)) {
                        pas      = - pas;
                        t_calcul = t_prec;
                        }
                if (test_calcul * test_prec <0) {
                        t_calcul = t_prec;
                        pas      = 0.5 * pas;
                        }
               } 
          return t_calcul;
        }

function VACTUEL(obj, a, t) {
        var   n = obj.length;
        var act = new makeArray(n);
        act[0] = 0;
        var k;
        for (k = 1; k <= n; k++) act[k] = COEFACTU(t, parseFloat(obj[k].dure));
        var van = 0 ;
        for (k = 1; k <= n; k++)  {
                van = van + (a + parseFloat(obj[k].echeance)) * (act[k] - act[k -1]);
                }
        return van;
        }

function COEFACTU(t,d) {
        var u = Math.pow((1 + t), d);
        return (u - 1) / (t * u);
        }

function ARRET(cap, r, t, p, n) {
	var Utx = Math.pow((1 + t), 1/p)
	var vac    = cap;
	var preced = cap * Utx;
	for (var i = 1; i< n; i++) {
		vac = (preced + r) * Utx
		preced = vac;
		}
	return vac;	
	}

function ECHEANCE(capi, t, n) {
        var eche;
        if (t>0)                       
                { 
                eche = Math.round(100 * capi * t * Math.pow((1+t), n) / (Math.pow((1+t), n) - 1)) / 100;
                }
        else
                {
                eche = Math.round(100 * capi / n) / 100;
                }
        return eche;
        }

function REMBOURS(capi, t, k, n) {
        var eche;
        if (t>0)                       
                { 
                eche = Math.round(100 * capi * t * Math.pow((1+t), k-1) / (Math.pow((1+t), n) - 1)) / 100;
                }
        else
                {
                eche = Math.round(100 * capi / n) / 100;
                }
        return eche;
        }

function TACTU(t,p) {
	return Math.round(1000 * (Math.pow((1 + t), p) -1) * 100) / 1000;		
	}

function fix(num,places, dec) {
	shift = Math.pow(10,places);
	//Traitement des valeurs négatives et inférieures à 1
	var vabs = Math.abs(num);		
	if (vabs < 1) {
		vabs += 1;
		var infer = 1;
		}
	totalDecimal = ""
	totalDecimal +=  Math.round(vabs * shift);
	integer = totalDecimal.substring(0,totalDecimal.length - places );
	if (infer == 1) integer = "0";
	if (integer.length == 0) integer = "0";
    decimal = totalDecimal.substring(totalDecimal.length -  places , totalDecimal.length);
	for (var i = 1; i<=places; i++) decimal += "0";
	
	if (places>0) {
		if (num<0) {
			return ("-" +  integer + dec + decimal.substring(0, places));
			
			}
		else { 
			return( integer + dec + decimal.substring(0, places));			
			}
		}
	else    {
		return(integer);
		}
	}

function validnum(obj, min, max) {
	  var chaine = obj.value;
	  var msg = "Donnée invalide : " + chaine;
	  
	  for (var i = 0; i < chaine.length; i++) {
		var ch = chaine.substring(i, i+1);
		if (ch == ",") {
				ch = ".";
		 		chaine = chaine.substring(0,i) + "." + chaine.substring(i+1,chaine.length);
				obj.value = chaine;
				}
		
		if ((ch < '0'|| '9' < ch) && ch != '.') {
			alert(msg);
			return false;
			}
		}
	var num = 0  + chaine;
	if (num < min || max < num) {
		alert ("Donnée hors limites : [ " + min + " - " + max + " ] ");
		obj.focus();
		return false;
		}
	obj.value     = chaine;
	return true;
	}
//---->
