$(document).ready( function() {
	$(".readonly").keydown( function() {
		return false;
	})
	$(".readonly").keypress( function() {
		return false;
	});
	$(".number").keyup( function() {
		val = $(this).val();
		val = val.replace(/[^0-9]/g, "");
//		val = val.toString();
		z = "";
		for (i=val.length-1;i>=0;i--) {
			z += val.charAt(i);
		}
		z = z.replace(/(\d{3})/g, "$1 ");
		if (z.slice(-1) == " ") {
			z = z.slice(0, -1);
		}
		val = "";
		for (i=z.length-1;i>=0;i--) {
			val += z.charAt(i);
		}
		$(this).val(val);
		calculate();
	})
	$(".float").keyup( function() {
		val = $(this).val();
		val = val.replace(/[^0-9\.,]/g, "");
		val = val.replace(".", ",");
		z = "";
		for (i=val.length-1;i>=0;i--) {
			z += val.charAt(i);
		}
		z = z.replace(/(\d{3})/g, "$1 ");
		if (z.slice(-1) == " ") {
			z = z.slice(0, -1);
		}
		val = "";
		for (i=z.length-1;i>=0;i--) {
			val += z.charAt(i);
		}
		$(this).val(val);
		calculate();
	})
} )

function calculate() {
	cost = numFormatRemove($("#cost").val());
	pay = numFormatRemove($("#pay").val());
	rate = (numFormatRemove($("#rate").val())/100) / 12;
	months = numFormatRemove($("#repayability").val()) * 12;
	
	mortgage = cost - pay;
	payment = Math.floor((mortgage*rate)/(1-Math.pow(1+rate,(-1*months)))*100)/100;
	
	$("#cost").val(numFormat(cost));
	$("#mortgage").val(numFormat(mortgage));
	$("#payment").val(numFormat(payment));
}
function rnd(number, decimals){
	return Math.round(number*Math.pow(10,decimals))/Math.pow(10,decimals);
}
function numFormat(nStr){
	//nStr = numFormatRemove(nStr);
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	return x1 + x2;
}
function numFormatRemove(str){
	var hodnota = str.replace(",", ".").toString(); // += "";
	var result = "";
	if (hodnota == "") { hodnota = "0"; }
	for(i=0; i<hodnota.length; i++){
		if (hodnota.charAt(i) != " "){
			result += hodnota.charAt(i);
		}
	}
	return parseFloat(result);
}

$(document).ready( function() {
	calculate();
} );

