alertCheckValors = "Validacions:\n";
alertNumericInteres = "     - Tipus d'interès anual no és numèric\n";
alertNumericAnys = "     - Anys no és numèric\n";
alertNumericTotal = "     - Import total no és numèric\n";
alertNumericQuota = "     - Quota mensual no és numèric\n";

alertInteres = "Introdueix un valor vàlid pel camp tipus d'interès anual.";
alertCampsRequerits = "Introdueix el tipus d'interès anual i dos dels tres camps restants.";

function isBlank(val){
	if(val==null){
		return true;
	}
	for(var i=0;i<val.length;i++){
		if((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){
			return false;
		}
	}
	return true;
}

function isNumeric(val){
	if(isBlank(val)) return true;
	val = val.replace(',','.');
	return(parseFloat(val,10)==(val*1));
}

function calculaImportHipoteca() {
	interes = document.calculadora.interes.value; // Interès anual
	anys = document.calculadora.anys.value; // Anys
	total = document.calculadora.total.value; // Import total
	quota = document.calculadora.quota.value; // Quota mensual
	
	//Validacions
	checkValors = true;
	if(!isNumeric(interes)){
		checkValors = false;
		alertCheckValors += alertNumericInteres;
	}
	if(!isNumeric(anys)){
		checkValors = false;
		alertCheckValors += alertNumericAnys;
	}
	if(!isNumeric(total)){
		checkValors = false;
		alertCheckValors += alertNumericTotal;
	}
	if(!isNumeric(quota)){
		checkValors = false;
		alertCheckValors += alertNumericQuota;
	}

	if(checkValors){
		if(isNaN(interes) || interes<=0) {
			alert(alertInteres);
		} else if(!isNaN(anys) && anys>0 && !isNaN(total) && total>0) {
			quota = total * (interes/1200) / (1-Math.pow(1+interes/1200,-anys*12));
			document.calculadora.quota.value = Math.round(quota*100)/100; 
		} else if(!isNaN(total) && total>0 && !isNaN(quota) && quota>0) {
			anys = Math.round(Math.log(1-(total*interes/(quota*1200)))/(-12*Math.log(1+interes/1200)));
			document.calculadora.anys.value = anys;
			quota = total * (interes/1200) / (1-Math.pow(1+interes/1200,-anys*12));
			document.calculadora.quota.value = Math.round(quota*100) / 100; 
		} else if(!isNaN(anys) && anys>0 && !isNaN(quota) && quota>0) {
			total = quota * (1-Math.pow(1+interes/1200,-anys*12)) / (interes/1200);
			document.calculadora.total.value = Math.round(total*100) / 100;
		} else {
			alert(alertCampsRequerits);
		}
	}else{
		alert(alertCheckValors);
	}
}
