function format_float(value, precision) {
	numbervalue = String(value).replace(/,/g,'');
	if (isNaN(Number(value).toFixed(precision))) { return value; }
	return format_number(String(Number(value).toFixed(precision)));
}

function format_number(value)
{
	value = String(value);
	var matches = value.match(/^(\-)?([\d,]+)(\.\d+)?$/);
	if (!matches) { return value; }
	prefix = matches[1] ? matches[1] : '';
	number_value = matches[2] ? matches[2] : '';
	suffix = matches[3] ? matches[3] : '';
	
	number_value = String(number_value).replace(/,/g,'');
	var new_txt = '';
	for (var n=0; n < number_value.length; n++) {
		new_txt = number_value.substr(number_value.length - (n+1),1) + new_txt;
		if (n % 3 == 2 && n+1 < number_value.length) { new_txt = ','+new_txt; }
	}

	return prefix+new_txt+suffix;
}

function convert_to_number(value) {
	value = String(value).replace(/,/g, '');
	if (value=='') { return 0; }
	var float_val = parseFloat(value, 10);
	return !isNaN(float_val) ? float_val : 0;
}

function sumCostAnalysis(frm)
{
	var total = 0;
	var subtotals = {};

	var elms = frm.getElementsByTagName('input');

	for (var i=0; i < elms.length; i++) {
		var elm = elms[i];
		if (elm.value) {
			for (var j=0; j < sections.length; j++) {
				if (elm.name && elm.name.indexOf(sections[j]+'_')==0) {
					var section_name = sections[j];
					var val = convert_to_number(elm.value);
					total += val;
					if (!subtotals[section_name]) { subtotals[section_name] = 0; }
					subtotals[section_name] += val;
				break;
				}
			}
		}
	}

	for (var i=0; i < sections.length; i++) {
		var subtotal_div = sections[i]+'_subtotal';
		var elm = $(subtotal_div);
		if (elm && subtotals[sections[i]]) { elm.innerHTML = format_float( subtotals[sections[i]], 2 ); }
	}

	var elm = $('total');
	if (elm && total) { elm.innerHTML = format_float( total, 2 ); }
	
}
