function addCommas(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 addDebt() { 
 	//fields to add up
	debtsToAdd = new Array(7)
	debtsToAdd[1] = document.calc.mortgage;
	debtsToAdd[2] = document.calc.creditCard;
	debtsToAdd[3] = document.calc.other;
	debtsToAdd[4] = document.calc.funeral;
	debtsToAdd[5] = document.calc.lumpSum;
	debtsToAdd[6] = document.calc.personalLoans;
	debtsToAdd[7] = document.calc.carLoans;
	
	var counter = 1
	var total = 0
	while (counter <= 7) {
	aNum = debtsToAdd[counter].value;
	//lose commas and spaces
	aNum=aNum.replace(/,/g,"");
	aNum=aNum.replace(/\s/g,"");
	debtsToAdd[counter].value = aNum;
	//check for valid numbers
	if(isNaN(aNum)) {
		debtsToAdd[counter].style.backgroundColor = '#ff9966';
		alert ("Please enter whole numbers");
		 }
	else {
	// if a field is empty reset it to zero to avoid NaN error
		if (debtsToAdd[counter].value==null||debtsToAdd[counter].value=="") {
			debtsToAdd[counter].value = 0
			}
			debtsToAdd[counter].style.backgroundColor = '#ccc';
			total=total+parseInt(debtsToAdd[counter].value,10);
			}
			counter++
			
	}
	document.forms.calc.debtTotal.value = addCommas(total);
}

function addCurrentCover() { 
 	//fields to add up
	currentCover = new Array(4)
	currentCover[1] = document.calc.currentDeath;
	currentCover[2] = document.calc.currentSuper;
	currentCover[3] = document.calc.currentSavings;
	currentCover[4] = document.calc.otherSavings;
	
	var counter = 1
	var total = 0
	while (counter <= 4) {
	aNum = currentCover[counter].value;
	//lose commas and spaces
	aNum=aNum.replace(/,/g,"");
	aNum=aNum.replace(/\s/g,"");
	currentCover[counter].value = aNum;
	//check for valid numbers
	if(isNaN(currentCover[counter].value)) {
		currentCover[counter].style.backgroundColor = '#ff9966';
		alert ("Please enter whole numbers");
		 }
	else {
	// if a field is empty reset it to zero to avoid NaN error
		if (currentCover[counter].value==null||currentCover[counter].value=="") {
			currentCover[counter].value = 0
			}
			currentCover[counter].style.backgroundColor = '#ccc';
			total=total+parseInt(currentCover[counter].value,10);
			}
			counter++
			
	}
	document.forms.calc.currentCoverTotal.value = addCommas(total);
}
