$(document).ready(function() {
	// ----- initialize
	
	// check the hidden rows
	$.each($('#itemized tr.item.hide'),function() {
		if ($(this).find('input').val()) {
			$(this).removeClass('hide');
			$(this).addClass('show');
		}
	});
						   
	// click-events
	$('#btn_add_row').click(function() {
		var itemized_rows = $('#itemized tr.item.show').length+1;
		addrow(itemized_rows);
	});
	
});

function initialize() {
	total_amt('amount');
	total_amt('amount-request');	
	total_amt('inkind-amount');
	total_amt('cash-amount');
}

function total_amt(fieldname) {
	var total = 0;	
	var rowCount = document.getElementById("itemized").getElementsByTagName("tr").length + 5;
	// get values from all "amount fields"
	for (var i = 1;i < rowCount;i++) {
		var field = 'p'+i+'_'+fieldname;		
		if (document.getElementById(field) && document.getElementById(field).value) {	
			total = total + parseFloat(document.getElementById(field).value);
		}
	}
	document.getElementById('ptotal_'+fieldname).value = total.toFixed(2);	
	if (fieldname == 'amount') {
		document.getElementById('t_amount').value = total.toFixed(2);			
	}
	if (fieldname == 'amount-request') {
		document.getElementById('t_amount-request').value = total.toFixed(2);			
	}	
	if ((fieldname == 'cash-amount') || (fieldname == 'inkind-amount')) {
		var cash = parseFloat(document.getElementById('ptotal_cash-amount').value);
		var inkind = parseFloat(document.getElementById('ptotal_inkind-amount').value);
		var contrib = cash + inkind;
		document.getElementById('t_contribution').value = contrib.toFixed(2);
	}
}

function addrow(row) {
	var currow = 'r'+row;
	var curele = $('#'+currow);
	var curproj = 'p'+row;
	var nextint = row+1;
	var nextrow = 'r'+nextint;
	var nextproj = 'p'+nextint;
	var addtext,regex1,regex2;
	if (row%2 == 0) {
		var class_color="even";
	} else {
		var class_color="odd";
	}
	// check to see if a hidden row is available
	if ($('#r'+row).length > 0) {
		$('#r'+row).removeClass('hide').addClass('show');
	} else {
		// get html for previous entry of same even/odd-ness and increment ids
		regex1 = new RegExp('p('+(row-2)+')','gi');				
		regex2 = new RegExp('('+(row-2)+')\.','gi');
		addtext = '<tr id="r'+row+'" class="'+$('#r'+(row-2)).attr('class')+'">' + $('#r'+(row-2)).html().replace(regex1,'p'+row).replace(regex2,row+'.') + '</tr>';
		$('#r_add').before(addtext);
	}
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {		
		limitField.value = limitField.value.substring(0, limitNum);
		limitField.scrollTop = limitField.scrollHeight;
	} else {
		document.getElementById(limitCount).innerHTML = limitNum - limitField.value.length;
	}
}