/////////////////////////////////////////////////////////////////////////////////////////
// GLOBALS
/////////////////////////////////////////////////////////////////////////////////////////
var institutions = new Array();
var sequence = 1;

var new_institution = new Institution();
var new_personal_account = new PersonalAccount();
var new_business_account = new BusinessAccount();

new_personal_account.id = "new";
new_business_account.id = "new";
new_institution.id = "new";

var institution_helped = false;
var should_warn = false;
var known_people = new Array();
var known_eins = new Array();

var calculate_insurance_flag = false;

/////////////////////////////////////////////////////////////////////////////////////////
// CLASSES
/////////////////////////////////////////////////////////////////////////////////////////

function Institution(name) {
	
	this.id = get_sequence();
	this.name = name;
	this.personal_accounts = new Array();
	this.business_accounts = new Array();

	this.add_personal_account = function(account) {
		this.personal_accounts.push(account);
	}
	
	this.remove_personal_account = function(accountid) {
		var new_array = new Array();
		for(var i = 0; i < this.personal_accounts.length; i++) {
			if (this.personal_accounts[i].id != accountid) {
				new_array.push(this.personal_accounts[i]);
			}
		}
		
		this.personal_accounts = new_array;
	}
	
	this.add_business_account = function(account) {
		this.business_accounts.push(account);
	}
	
	this.remove_business_account = function(accountid) {
		var new_array = new Array();
		for(var i = 0; i < this.business_accounts.length; i++) {
			if (this.business_accounts[i].id != accountid) {
				new_array.push(this.business_accounts[i]);
			}
		}
		
		this.business_accounts = new_array;
	}
}

function PersonalAccount(name) {
	
	this.id = get_sequence();
	this.name = name;
	this.owners = new Array();
	this.balance = null;
	this.type = null;
	this.beneficiaries = new Array();
	
	this.add_owner = function(owner) {
		this.owners.push(owner);
	}
	
	this.remove_owner = function(ownerid) {
		var new_array = new Array();
		for(var i = 0; i < this.owners.length; i++) {
			if (this.owners[i].id != ownerid) {
				new_array.push(this.owners[i]);
			}
		}
		
		this.owners = new_array;
	}
	
	this.add_beneficiary = function(ben) {
		this.beneficiaries.push(ben);
	}
	
	this.remove_beneficiary = function(benid) {
		var new_array = new Array();
		for(var i = 0; i < this.beneficiaries.length; i++) {
			if (this.beneficiaries[i].id != benid) {
				new_array.push(this.beneficiaries[i]);
			}
		}
		
		this.beneficiaries = new_array;
	}
	
}

function BusinessAccount(name) {
	
	this.id = get_sequence();
	this.name = name;
	this.balance = null;
	this.ein = null;
	this.account_name = null;
	this.owner = null;
	
}

function Owner(name) {
	
	this.id = get_sequence();
	this.name = name;
	
}

function Beneficiary(name) {
	
	this.id = get_sequence();
	this.name = name;
	this.type = null;
}

/////////////////////////////////////////////////////////////////////////////////////////
// CONTROLLER FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////

function populate_calculator(inst, p_acct, b_acct) {

	var institution = inst;
	var account = p_acct;
	var baccount = b_acct;
	
	var validate_institutionfield = true;
	
	if(!institution) {
		if(institutions.length) {
			institution = institutions[0];
		} else {
			institution = new_institution;
			var validate_institutionfield = false;
		}
	}
	
	var validate_after_populate = true;
	if(baccount || account) {
		$('#business_personal_chooser').hide();
		$('.soleprop').hide();
	} else {
		if(institution.personal_accounts.length + institution.business_accounts.length > 49) {
			$('#business_personal_chooser').hide();
			$('#account_limit').show();
		} else {
			$('#business_personal_chooser').show();
			$('#account_limit').hide();
		}
		
		$('.soleprop').show();
		$('#business_div').hide();
		$('#personal_div').hide();
		$('#button_div').hide();
		$('input[name=business_personal]').attr('checked', false);
		if(institution.personal_accounts.length + institution.business_accounts.length) {
			$('#add_account_text').text("Add next account...");
		} else {
			$('#add_account_text').text("Add first account...");
		}
		validate_after_populate = false;
	}
	
	if(baccount) {
		$('#active_account_id').val(baccount.id)
		account = new_personal_account;
		$('input[name=business_personal]').filter('[value=business]').click();
	} else {
		if(!account) {
			account = new_personal_account;
		} else {
			$('input[name=business_personal]').filter('[value=personal]').click();
		}
		$('#active_account_id').val(account.id)
		baccount = new_business_account;
	}

	//$('#institution').val(institution.name || "");
	
	// Setup the personal account fields
	
	$('#account_name').val(account.name || "");
	$('#account_balance').val(account.balance || "");
	$('#account_type').val(account.type || "");	
	$('#owner_tmpl').hide();
	
	if(account.owners.length == 1) {
	
		$('input[name=owner_last]').val(account.owners[0].name);
		$('input[name=owner_last_living]').val(['yes']);
	
	} else if(account.owners.length > 1) {
	
		for(var i = 0; i < account.owners.length; i++) {
			$('input[name=owner_last]').val(account.owners[i].name);
			$('input[name=owner_last_living]').val(['yes']);
		
			if(i != account.owners.length - 1) {
				add_additional_owner();
			}
		}
		
	} else {
		var owner_ids = $.map($('input.ownerclass'), function(e) { return e.name; });

		$.each(owner_ids, function() { if(this != 'owner_last') remove_owner(this); });
		reset_owner_all('owner_last');
		$('#add_additional_owner_btn').hide();
	}
	
	if(account.type == "Trust" || account.type == "ITF") {
		show_beneficiaries();
		var owner_ids = $.map($('input.ownerclass'), function(e) { return e.name; });

		if(account.beneficiaries.length == 1) {
			var beneficiary = account.beneficiaries[0];
			
			$('input[name=beneficiary_last]').val(beneficiary.name);
			if(beneficiary.type == "person") $('input[name=beneficiary_last_living]').val(['yes']);
			if(beneficiary.type == "charity") $('input[name=beneficiary_last_charity]').val(['yes']);

			$('select[name=beneficiary_last_type]').val(beneficiary.type);

		} else if(account.beneficiaries.length > 1) {

			for(var i = 0; i < account.beneficiaries.length; i++) {
				var beneficiary = account.beneficiaries[i];

				$('input[name=beneficiary_last]').val(beneficiary.name);
				if(beneficiary.type == "person") $('input[name=beneficiary_last_living]').val(['yes']);
				if(beneficiary.type == "charity") $('input[name=beneficiary_last_charity]').val(['yes']);

				$('select[name=beneficiary_last_type]').val(beneficiary.type);

				if(i != account.beneficiaries.length - 1) {
					add_additional_beneficiary();
				}
			}

		} else {
			var ben_ids = $.map($('input.beneficiaryclass'), function(e) { return e.name; });
			$.each(ben_ids, function() { if(this != "beneficiary_last") remove_beneficiary(this); });
			reset_beneficiary_all('beneficiary_last');
		}
		
	} else {
		var ben_ids = $.map($('input.beneficiaryclass'), function(e) { return e.name; });
		$.each(ben_ids, function() { if(this != "beneficiary_last") remove_beneficiary(this); });
		reset_beneficiary_all('beneficiary_last');
		hide_beneficiaries();
	}
	
	// setup the business account fields

	$('#business_account_type').val(baccount.account_type || "");
	$('#business_account_name').val(baccount.account_name || "");
	$('#business_name').val(baccount.name || "");
	$('#business_account_balance').val(baccount.balance || "");
	$('#ein').val(baccount.ein || "");
	
	if(baccount.id != 'new') {
		$('input[name=sole_proprietorship]').filter('[value=no]').click();
	} else {
		$('input[name=sole_proprietorship]').attr('checked', false);
	}
	
	// If we're editing, validate, otherwise skip validation and reset the validation markers
	
	if(validate_after_populate) {
		validate_calculator();
		$('#button_div').empty();
		$('<input type="button" value="Return Account to Report"/>&nbsp;').appendTo('#button_div').bind('click', function(e) { process_calculator() });
		
		var remove_account_func = function() { remove_account($('#active_account_id').val()); };
		
		$('<input type="button" value="Remove From Report"/>&nbsp;').appendTo('#button_div').bind('click', function(e) { show_confirm("Do you really want to remove this account?", remove_account_func) });
		
		// also change button wording and add a remove from report button for both business and personal
	} else {
		$('img[alt=Status]').attr("src",'images/check_grey.gif');
		$('#button_div').empty();
		$('<input type="button" value="Add to report"/>&nbsp;').appendTo('#button_div').bind('click', function(e) { process_calculator() });
		
		if(validate_institutionfield) validate_institution();

	}
		
	window.scroll(0,100);
}



function process_calculator() {
	
	if(!validate_calculator()) {
		show_alert('<p>Please make sure all fields are filled out completely<br/>and correctly before saving this account.<br/>Move the arrow over any red <img src="images/check_red.gif"/> icons for more detail.</p>');
		return;
	}
	
	var account = null;
	var institution = null;
	
	var accountid = $('#active_account_id').val();
	
	if(get_account_type() == "personal" && !validate_trust_balance(accountid)) {
		show_alert('<p><img src="images/check_red.gif"> E-SIC cannot currently calculate the insurance coverage of revocable trust deposits that exceed $1,250,000 per owner. Please contact NCUA at 1-800-755-1030 for assistance in determining your insurance coverage.</p>');
		return;
	}
	
	if(accountid && accountid != 'new') {
		account = find_account(accountid);
		institution = institutions[0];
		if(!institution) { alert('An error occurred: Missing institution.'); return }
		
	} else if(accountid == 'new') {
		if(get_account_type() == "personal") account = new PersonalAccount();
		if(get_account_type() == "business") account = new BusinessAccount();

		if(institutions.length)
			institution = institutions[0];
		else {
			institution = new Institution($('#institution').text());
			institutions.push(institution);
		}
		
		if(get_account_type() == "personal") institution.add_personal_account(account);
		if(get_account_type() == "business") institution.add_business_account(account);
	}
	
	if(!account) { alert("An error occurred: Couldn't process form."); return; }
	
	if(get_account_type() == "personal") {
		
		account.name = $('#account_name').val();
		account.balance = $('#account_balance').val();
		account.type = $('#account_type').val();
		account.owners = new Array();
		account.beneficiaries = new Array();
		
		var owner_ids = $.map($('input.ownerclass'), function(e) { return e.name; });
		
		for(var i = 0; i < owner_ids.length; i++) {
			var owner = new Owner();
			owner.name = $('input[name='+owner_ids[i]+']').val();
			account.add_owner(owner);
		}
		
		if(account.type == 'Trust' || account.type == 'ITF') {
			var ben_ids = $.map($('input.beneficiaryclass'), function(e) { return e.name; });

			for(var i = 0; i < ben_ids.length; i++) {
				var ben = new Beneficiary();
				ben.name = $('input[name='+ben_ids[i]+']').val();
				ben.type = $('select[name='+ben_ids[i]+'_type]').val();

				account.add_beneficiary(ben);
			}
		}
	} else {

		institution.name = $('#institution').text();
		account.balance = $('#business_account_balance').val();
		account.name = $('#business_name').val();
		account.ein = $('#ein').val();
		account.account_name = $('#business_account_name').val();

	}
		
	populate_calculator();
	
	calculate_insurance_flag = false;
	render_report();
}

function remove_account(accountid) {
	var institution = institutions[0];
	
	institution.remove_personal_account(accountid);	
	institution.remove_business_account(accountid);	
	populate_calculator();
	calculate_insurance_flag = false;
	render_report(); 
}

function start_over() {
	institutions = new Array();
	$('#printme').hide();
	calculate_insurance_flag = false;
	swap_institution_back();
	show_calculator();
	populate_calculator();
	render_report();
}

function render_actions() {
	$('<table border="0" cellpadding="5" cellspacing="0" width="500"><tr><td align="right"><input id="print_button" type="button" value="Printable Report" class="actionbutton"></td><td valign="middle" align="left">Click here to print this report.</td></tr><tr><td align="right"><input type="button" value="Start Over" class="actionbutton" id="start_over_button"></td><td valign="middle" align="left">Click here to start over.</td></tr></table>').appendTo('#actions_div');
	
	$('#print_button').bind('click', function() { print_report(); });
	
	var callback = function() { start_over(); };
	
	$('#start_over_button').bind('click', function() { show_confirm('If you start the E-SIC program over again, you will lose all data entered in this session.', callback); });
	
}

/////////////////////////////////////////////////////////////////////////////////////////
// REPORT RENDERING / CALCULATION FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////

function render_report() {
	
	$('#report_div').empty();
	known_people = new Array();
	
	var people_map = new Array();
	var have_accounts = false;
	
	for(var i = 0; i < institutions.length; i++) {
		var institution = institutions[i];
		
		if(institution.personal_accounts.length == 0 && institution.business_accounts.length == 0)
			continue;
		
		have_accounts = true;
		
		for(var j = 0; j < institution.personal_accounts.length; j++) {
			var account = institution.personal_accounts[j];
			var names = $.map(account.owners, function(e) { return e.name });
			for(var k = 0; k < names.length; k++) people_map[names[k].toLowerCase()] = names[k];
				
			names = $.map(account.beneficiaries, function(e) { return e.name });
			for(var k = 0; k < names.length; k++) people_map[names[k].toLowerCase()] = names[k];
			
		}
		
		for(var j = 0; j < institution.business_accounts.length; j++) {
			var account = institution.business_accounts[j];
			if(account.owner) people_map[account.owner.name.toLowerCase()] = account.owner.name;
		}
		
		render_institution(institution);
	}
	
	for(var n in people_map) {
		known_people.push(people_map[n]);
	}
	
	if(have_accounts) {
		show_report();
		$('#add_another').show();
		if(calculate_insurance_flag)
			$('#print_button').attr('disabled', false);
		else
			$('#print_button').attr('disabled', true);
			
		show_actions();
	} else {
		hide_report();
		$('#print_button').attr('disabled', true);
		$('#add_another').hide();
		//hide_actions();
	}
	
	setup_autocompletes();
}

function setup_autocompletes() {
	$('input[name=owner_last]').autocomplete(known_people);
	$('input[name=beneficiary_last]').autocomplete(known_people);
}

function print_generic_window(source_selector) {
	var generic_win = window.open('printgeneric.html','popwin','status=0,toolbar=0,location=0,menubar=1,directories=0,resizable=1,scrollbars=1,height=550,width=700');
	
	
	$(generic_win.document).ready(function() {

		setTimeout(function() { 
			var clone = $(source_selector).clone();
			$(generic_win.document.body).find('#main_area').html(clone.html());
			$(generic_win.document.body).find('.help_button_div').remove();
		}, 1000);
		
		setTimeout(function() { 
			generic_win.print();
		}, 2000);
		
	});

}

function print_report() {
	var report_win = window.open('print.html','reportwin','status=0,toolbar=0,location=0,menubar=1,directories=0,resizable=1,scrollbars=1,height=550,width=700');

	$(report_win.document).ready(function() {

		setTimeout(function() { 
			var clone = $('#report_div').clone();
			$(report_win.document.body).find('#main_area').html(clone.html());
			$(report_win.document.body).find('.pointer').remove();

		}, 1000);
		
		setTimeout(function() { 
			report_win.print();
		}, 2000);
		
	});
	
}

function render_institution(institution) {
	
	var total_accounts = institution.business_accounts.length + institution.personal_accounts.length;
	var status_graphic = '<img src="images\/report_green.gif" alt="Checkmark" id="institution_'+institution.id+'_status" width="28" height="28" border="0">';
		
	$('<table border="0" cellpadding="5" cellspacing="0" width="580"><tbody id="institution_report_'+institution.id+'">'+
	'<tr><td align="right">'+status_graphic+'</td><th colspan="2" align="left">Institution: '+institution.name+'</th>' +
	'<th colspan="2" align="right">Number of Accounts: '+total_accounts+'</th></tr><tr><td valign="top"></td><td colspan="4" valign="top" align="left" id="report_summary"></td></tr></tbody></table>').appendTo('#report_div');
	
	var covered = true;
	
	var single_ownership_accounts = new Array();
	var joint_ownership_accounts = new Array();
	var retirement_accounts = new Array();
	var trust_accounts = new Array();
	var business_accounts = institution.business_accounts;
	
	for(var i = 0; i < institution.personal_accounts.length; i++) {
		var account = institution.personal_accounts[i];
		if(account.type == 'Trust' || account.type == 'ITF') {
			trust_accounts.push(account);
		} else if(account.type == "Retirement") {
			retirement_accounts.push(account);
		} else if(account.type == "Single") {
			single_ownership_accounts.push(account);
		} else if(account.type == "Joint") {
			joint_ownership_accounts.push(account);	
		}
	}
	
	var balance = 0;
	var insured = 0;
	var uninsured = 0;
	
	var res = render_ownership(single_ownership_accounts, institution, "Single Ownership Accounts", "Single Ownership", 250000, trust_accounts);
	
	if(res) {
		balance += res[0];
		insured += res[1];
		uninsured += res[2];
	}
	
	res = render_ownership(joint_ownership_accounts, institution, "Joint Ownership Accounts", "Joint Ownership", 250000);
	if(res) {
		balance += res[0];
		insured += res[1];
		uninsured += res[2];
	}
	
	res = render_ownership(retirement_accounts, institution, "Retirement Accounts", "Retirement Account", 250000);
	if(res) {
		balance += res[0];
		insured += res[1];
		uninsured += res[2];
	}
		
	res = render_living_trust(trust_accounts, institution);
	if(res) {
		balance += res[0];
		insured += res[1];
		uninsured += res[2];
	}
	
	res = render_business(business_accounts, institution);
	if(res) {
		balance += res[0];
		insured += res[1];
		uninsured += res[2];
	}
	
	var content = render_institution_summary("Total for all accounts at "+institution.name, balance, insured, uninsured);
	content.appendTo('#institution_report_'+institution.id);
	
	var summary = render_report_summary(uninsured);
	summary.appendTo('#report_summary').show();
	if(!calculate_insurance_flag)
		summary.effect("highlight", {"color":"#ffff99"},1500);
	
	// set status graphic
	if(!calculate_insurance_flag) {
		$('#printme').hide();
		$('#institution_'+institution.id+'_status').attr('src', 'images/report_stop3.gif');
		$('<tr><td valign="top"></td><td valign="top" colspan="4" align="center"><input type="button" class="calculate_btn" value="Calculate"/></td></tr>').appendTo('#institution_report_'+institution.id);
	} else if(uninsured > 0) {
		$('#printme').show();
		$('#institution_'+institution.id+'_status').attr('src', 'images/report_alert.gif');
	} else {
		$('#printme').show();
	}
	
	if($('.calculate_btn').length) {
		$('.calculate_btn').bind('click', function(e) { calculate_insurance_flag = true; render_report(); });
	}
	
	// End table
	$('<tr><td valign="top"></td><td valign="top" colspan="4" align="left"><b>This calculation assumes that all of the above accounts are on deposit in an NCUA-insured credit union, and that the account owners do not have accounts other than those listed above at '+institution.name+'.</b></td></tr>').appendTo('#institution_report_'+institution.id);
}

function render_ownership(accounts, institution, header, type, insured_per_owner, trust_accounts) {
	
	if(!trust_accounts) trust_accounts = new Array();
	
	if(accounts.length || trust_accounts.length) {
		
		var tempid = get_sequence();
		var account_header = render_account_header(header, 'temp_header'+tempid);
		account_header.appendTo('#institution_report_'+institution.id);
		
		var distinct_owners = [];		

		var running_balance = 0;
	
		for(var i = 0; i < accounts.length; i++) {
			var account = accounts[i];
			for(var j = 0; j < account.owners.length; j++) {

				var owner = account.owners[j];
				if(!distinct_owners[owner.name.toLowerCase()]) distinct_owners[owner.name.toLowerCase()] = 0;
				distinct_owners[owner.name.toLowerCase()] += money_to_float(account.balance) / account.owners.length;
			}
			
			running_balance += money_to_float(account.balance);

			render_account(institution, account);
		}

		for(var i = 0; i < trust_accounts.length; i++) {
			var account = trust_accounts[i];
			var account_balance = 0;
			
			var slice = money_to_float(account.balance) / (account.owners.length * account.beneficiaries.length);
			for(var j = 0; j < account.owners.length; j++) {
				var owner = account.owners[j];
				for(var k = 0; k < account.beneficiaries.length; k++) {
					var bene = account.beneficiaries[k];
					
					if(bene.type == 'other') {
						if(!distinct_owners[owner.name.toLowerCase()]) distinct_owners[owner.name.toLowerCase()] = 0;
						distinct_owners[owner.name.toLowerCase()] += slice;
						
						running_balance += slice;
						render_trust_account(institution, account, owner.name.toLowerCase(), bene.name.toLowerCase(), slice);

					}
				}
			}
		}

		if(!running_balance) { $('.temp_header'+tempid).remove(); return null; }

		$('<tr><td valign="top"></td><td valign="top" class="accounttype" align="left"><b>'+type+' Insurance Summary</b></td><td valign="top" class="accounttype" align="right">Balance</td><td valign="top" class="accounttype" align="right">Insured</td><td valign="top" class="accounttype" align="right">Uninsured</td></tr>').appendTo('#institution_report_'+institution.id);
	
		var total_insured = 0;
		var total_uninsured = 0;		
		
		for(var ownername in distinct_owners) {
			var total = distinct_owners[ownername];
			var classname = "";
			var insured = total;
			var uninsured = 0;
			if(total > insured_per_owner) {
				classname = "uninsured";
				insured = insured_per_owner;
				uninsured = total - insured_per_owner;
			}
			total_insured += insured;
			total_uninsured += uninsured;
			
			if(calculate_insurance_flag) {
				$('<tr><td valign="top"></td><td valign="top" class="'+classname+'" align="left">'+cap_firsts(ownername)+' '+type+'</td><td valign="top" class="'+classname+'" align="right">'+currency_format(roundit(total))+'</td><td valign="top" class="'+classname+'" align="right">'+currency_format(roundit(insured))+'</td><td valign="top" class="'+classname+'" align="right"><span class="'+classname+'">'+currency_format(roundit(uninsured))+'</span></td></tr>').appendTo('#institution_report_'+institution.id);	
			} else {
				$('<tr><td valign="top"></td><td valign="top" align="left">'+cap_firsts(ownername)+' '+type+'</td><td valign="top" align="right">'+currency_format(roundit(total))+'</td><td valign="top" align="right">--</td><td valign="top" align="right"><span>--</span></td></tr>').appendTo('#institution_report_'+institution.id);
			}				
		}
		
		// fix rounding errors
		if(total_uninsured == 0) { total_insured = running_balance; }
		
		return [running_balance, total_insured, total_uninsured];
		
	}
	
	return null;
}

function render_living_trust(trust_accounts, institution) {
		
	if(trust_accounts.length) {
		
		var account_header = render_account_header("Living Trust/ITF/POD Accounts", "lt_header");
		account_header.appendTo('#institution_report_'+institution.id);
		
		var combinations = [];
		
		var running_balance = 0;

		var insured_per_owner_bene = 250000;
	
		for(var i = 0; i < trust_accounts.length; i++) {
			var account = trust_accounts[i];
			var account_balance = 0;
			var benes = new Array();
			
			var slice = money_to_float(account.balance) / (account.owners.length * account.beneficiaries.length);
			for(var j = 0; j < account.owners.length; j++) {
				var owner = account.owners[j];
				if(!combinations[owner.name.toLowerCase()]) combinations[owner.name.toLowerCase()] = [];
				for(var k = 0; k < account.beneficiaries.length; k++) {
					var bene = account.beneficiaries[k];	
					// these get thrown in with single ownership
					if(bene.type == "other") continue;
								
					if(!combinations[owner.name.toLowerCase()][bene.name.toLowerCase()])
						combinations[owner.name.toLowerCase()][bene.name.toLowerCase()] = 0;
					combinations[owner.name.toLowerCase()][bene.name.toLowerCase()] += slice;
						
					running_balance += slice;
					account_balance += slice;
				}
			}
			
			if(account_balance)
				render_account(institution, account);
		}
		
		if(!running_balance) { $('.lt_header').remove(); return null; }

		$('<tr><td valign="top"></td><td valign="top" class="accounttype" align="left"><b>Living Trust/ITF/POD Insurance Summary</b></td><td valign="top" class="accounttype" align="right">Balance</td><td valign="top" class="accounttype" align="right">Insured</td><td valign="top" class="accounttype" align="right">Uninsured</td></tr>').appendTo('#institution_report_'+institution.id);
	
		var total_insured = 0;
		var total_uninsured = 0;		
		
		for(var ownername in combinations) {
			var total_for_owner = 0;
			var total_benes_for_owner = 0;
			var bene_names = new Array();
			for(var benename in combinations[ownername]) {
				var total = combinations[ownername][benename];
				total_for_owner += total;
				total_benes_for_owner += 1;
				bene_names.push(cap_firsts(benename));
			}

			if(total_for_owner == 0) continue;
			
			if(total_for_owner <= 1250000) {
				var insured = total_benes_for_owner * insured_per_owner_bene;
				var uninsured = 0;
				
				if(total_for_owner > insured) uninsured = total_for_owner - insured;
				if(uninsured == 0) insured = total_for_owner;
				
				total_insured += insured;
				total_uninsured += uninsured;
				var classname = "";
				if(uninsured > 0) {
					classname = "uninsured";
				}
				
				var benestring = bene_names.join(", ");
				
				if(calculate_insurance_flag) {
					$('<tr><td valign="top"></td><td valign="top" class="'+classname+'" align="left">'+cap_firsts(ownername)+' LT/ITF/POD<br>'+benestring+'</td><td valign="top" class="'+classname+'" align="right">'+currency_format(roundit(total_for_owner))+'</td><td valign="top" class="'+classname+'" align="right">'+currency_format(roundit(insured))+'</td><td valign="top" class="'+classname+'" align="right"><span class="'+classname+'">'+currency_format(roundit(uninsured))+'</span></td></tr>').appendTo('#institution_report_'+institution.id);
				} else {
					$('<tr><td valign="top"></td><td valign="top" align="left">'+cap_firsts(ownername)+' LT/ITF/POD<br>'+benestring+'</td><td valign="top" align="right">'+currency_format(roundit(total_for_owner))+'</td><td valign="top" align="right">--</td><td valign="top" align="right"><span>--</span></td></tr>').appendTo('#institution_report_'+institution.id);
				}
			} else {
				// shouldn't get here for now until we get this clear
				/**
				for(var benename in combinations[ownername]) {
					var total = combinations[ownername][benename];
					var classname = "";
					var insured = total;
					var uninsured = 0;
					if(total > insured_per_owner_bene) {
						classname = "uninsured";
						insured = insured_per_owner_bene;
						uninsured = total - insured_per_owner_bene;
					}
					total_insured += insured;
					total_uninsured += uninsured;

					$('<tr><td valign="top"></td><td valign="top" class="'+classname+'" align="left">'+cap_firsts(ownername)+' LT/ITF/POD<br>'+cap_firsts(benename)+'</td><td valign="top" class="'+classname+'" align="right">'+currency_format(total)+'</td><td valign="top" class="'+classname+'" align="right">'+currency_format(insured)+'</td><td valign="top" class="'+classname+'" align="right"><span class="'+classname+'">'+currency_format(uninsured)+'</span></td></tr>').appendTo('#institution_report_'+institution.id);
				}
				**/
			}
		}
		
		// fix rounding errors
		if(total_uninsured == 0) { total_insured = running_balance; }
		
		return [running_balance, total_insured, total_uninsured];
		
	}
	
	return null;
	
}

function render_business(business_accounts, institution) {
	
	if(business_accounts.length) {
		
		var account_header = render_business_account_header("Business Accounts");
		account_header.appendTo('#institution_report_'+institution.id);
		
		var distinct_eins = [];		

		var running_balance = 0;
		var insured_per_ein = 250000;
	
		for(var i = 0; i < business_accounts.length; i++) {
			var account = business_accounts[i];
			var ein = account.ein;
			if(!distinct_eins[ein]) distinct_eins[ein] = 0;
			distinct_eins[ein] += money_to_float(account.balance);
			
			running_balance += money_to_float(account.balance);
			render_business_account(institution, account);
		}
	
		$('<tr><td valign="top"></td><td valign="top" class="accounttype" align="left"><b>Business Accounts Insurance Summary</b></td><td valign="top" class="accounttype" align="right">Balance</td><td valign="top" class="accounttype" align="right">Insured</td><td valign="top" class="accounttype" align="right">Uninsured</td></tr>').appendTo('#institution_report_'+institution.id);
	
		var total_insured = 0;
		var total_uninsured = 0;		
		
		for(var ein in distinct_eins) {
			var total = distinct_eins[ein];
			var classname = "";
			var insured = total;
			var uninsured = 0;
			if(total > insured_per_ein) {
				classname = "uninsured";
				insured = insured_per_ein;
				uninsured = total - insured_per_ein;
			}
			total_insured += insured;
			total_uninsured += uninsured;
			
			if(calculate_insurance_flag)			
				$('<tr><td valign="top"></td><td valign="top" class="'+classname+'" align="left">EIN: '+ein+'</td><td valign="top" class="'+classname+'" align="right">'+currency_format(roundit(total))+'</td><td valign="top" class="'+classname+'" align="right">'+currency_format(roundit(insured))+'</td><td valign="top" class="'+classname+'" align="right"><span class="'+classname+'">'+currency_format(roundit(uninsured))+'</span></td></tr>').appendTo('#institution_report_'+institution.id);
			else
				$('<tr><td valign="top"></td><td valign="top" align="left">EIN: '+ein+'</td><td valign="top" align="right">'+currency_format(roundit(total))+'</td><td valign="top" align="right">--</td><td valign="top" align="right"><span>--</span></td></tr>').appendTo('#institution_report_'+institution.id);
		}
		
		// fix rounding errors
		if(total_uninsured == 0) { total_insured = running_balance; }
		
		return [running_balance, total_insured, total_uninsured];
		
	}
	
	return null;
}

function render_business_account_header(title) {
	
	return $('<tr><td valign="top"></td><td valign="top" class="accounttypeheader" colspan="4" align="left">'+title+'</td></tr>'+
		'<tr><td valign="top"></td><td valign="top" align="left"><b>Business Name</b></td>'+
		'<td valign="top" align="left"><b>EIN</b></td>'+
		'<td valign="top" align="left"><b>Account Nickname</b></td>' +
		'<td valign="top" align="right"><b>Balance</b></td></tr>');
}

function render_account_header(title, id) {
	
	if(!id) id = "";
	
	return $('<tr class="'+id+'"><td valign="top"></td><td valign="top" class="accounttypeheader" colspan="4" align="left">'+title+'</td></tr>'+
		'<tr class="'+id+'"><td valign="top"></td><td valign="top" align="left"><b>Account Nickname</b></td>'+
		'<td valign="top" align="left"><b>Owner(s)</b></td><td valign="top" align="left"><b>Beneficiaries</b></td>'+
		'<td valign="top" align="right"><b>Balance</b></td></tr>');
}

function render_account(institution, account, balance_override) {
	
	var owner_names = $.map(account.owners, function(e) { return cap_firsts(e.name) });
	var name_string = owner_names.join("<br/>");
	var balance_string = balance_override ? currency_format(balance_override) : account.balance;
	
	var bene_names = $.map(account.beneficiaries, function(e) { return cap_firsts(e.name) });
	var bene_string = bene_names.join("<br/>");
	if(!bene_string) bene_string = "NA";
	
	$('<tr><td valign="top" width="80" align="left"><img src="images\/btn_edit.gif" alt="Edit" width="32" height="18" hspace="1" border="0" id="account_'+account.id+'_edit_button" class="pointer"><img src="images\/btn_delete.gif" alt="Delete" width="44" height="18" border="0" id="account_'+account.id+'_remove_button" class="pointer"></td><td valign="top" class="account" align="left"><b>'+account.name+'</b></td><td valign="top" class="account" align="left">'+name_string+'</td><td valign="top" class="account" align="left">'+bene_string+'</td><td valign="top" class="account" align="right">'+balance_string+'</td></tr>').appendTo('#institution_report_'+institution.id);

	$('#account_'+account.id+'_edit_button').bind('click', function(e) { populate_calculator(); populate_calculator(institution, account); });
	
	var remove_account_func = function() { remove_account(account.id); };
	
	$('#account_'+account.id+'_remove_button').bind('click', function(e) { show_confirm("Do you really want to remove this account?", remove_account_func) });
}

function render_trust_account(institution, account, name, bene_name, amount) {
	
	var seq = get_sequence();
	
	$('<tr><td valign="top" width="80" align="left"><img src="images\/btn_edit.gif" alt="Edit" width="32" height="18" hspace="1" border="0" id="account_'+account.id+'_edit_button_'+seq+'" class="pointer"><img src="images\/btn_delete.gif" alt="Delete" width="44" height="18" border="0" id="account_'+account.id+'_remove_button_'+seq+'" class="pointer"></td><td valign="top" class="account" align="left"><b>'+account.name+'</b></td><td valign="top" class="account" align="left">'+cap_firsts(name)+'</td><td valign="top" class="account" align="left">'+cap_firsts(bene_name)+' (ineligible beneficiary)</td><td valign="top" class="account" align="right">'+currency_format(amount)+'</td></tr>').appendTo('#institution_report_'+institution.id);

	$('#account_'+account.id+'_edit_button_'+seq).bind('click', function(e) { populate_calculator(); populate_calculator(institution, account); });
	
	var remove_account_func = function() { remove_account(account.id); };
	
	$('#account_'+account.id+'_remove_button_'+seq).bind('click', function(e) { show_confirm("Do you really want to remove this account?", remove_account_func) });
	
}

function render_business_account(institution, account) {

	$('<tr><td valign="top" width="80" align="left"><img src="images\/btn_edit.gif" alt="Edit" width="32" height="18" hspace="1" border="0" id="account_'+account.id+'_edit_button" class="pointer"><img src="images\/btn_delete.gif" alt="Delete" width="44" height="18" border="0" id="account_'+account.id+'_remove_button" class="pointer"></td><td valign="top" class="account" align="left"><b>'+account.name+'</b></td><td valign="top" class="account" align="left">'+account.ein+'</td><td valign="top" class="account" align="left">'+account.account_name+'</td><td valign="top" class="account" align="right">'+account.balance+'</td></tr>').appendTo('#institution_report_'+institution.id);

	$('#account_'+account.id+'_edit_button').bind('click', function(e) { populate_calculator(); populate_calculator(institution,null,account); });
	
	var remove_account_func = function() { remove_account(account.id); };
	
	$('#account_'+account.id+'_remove_button').bind('click', function(e) { show_confirm("Do you really want to remove this account?", remove_account_func) });

}

function render_institution_summary(title, balance, insured, uninsured) {
	
	var classname = "";
	
	if(uninsured) classname = "uninsured";
	
	if(calculate_insurance_flag)
		return $('<tr><td valign="top" colspan="5"></td></tr><tr><td valign="top"></td><td colspan="4" valign="top" align="left" class="accounttype"><b>'+title+'</b></td></tr><tr><td colspan="3"></td><td valign="top" align="right"><b>Balance</b></td><td valign="top" align="right">'+currency_format(roundit(balance))+'</td></tr><tr><td colspan="3"></td><td valign="top" align="right"><b>Insured</b></td><td valign="top" align="right">'+currency_format(roundit(insured))+'</td></tr><tr><td valign="top"></td><td colspan="2" class="'+classname+'"></td><td valign="top" align="right" class="'+classname+'"><b>Uninsured</b></td><td valign="top" align="right" class="'+classname+'"><span class="'+classname+'">'+currency_format(roundit(uninsured))+'</span></td></tr><tr><td valign="top" colspan="5"></td></tr>');
	else
		return $('<tr><td valign="top" colspan="5"></td></tr><tr><td valign="top"></td><td colspan="4" valign="top" align="left" class="accounttype"><b>'+title+'</b></td></tr><tr><td colspan="3"></td><td valign="top" align="right"><b>Balance</b></td><td valign="top" align="right">'+currency_format(roundit(balance))+'</td></tr><tr><td colspan="3"></td><td valign="top" align="right"><b>Insured</b></td><td valign="top" align="right">--</td></tr><tr><td valign="top"></td><td colspan="2"></td><td valign="top" align="right"><b>Uninsured</b></td><td valign="top" align="right"><span>--</span></td></tr><tr><td valign="top" colspan="5"></td></tr>');
}

function render_report_summary(uninsured) {
	
	if(!calculate_insurance_flag) {
		report_status = '<div class="explain"><p><b>What\'s Next?</b></p><ul><li>If needed, you can add more accounts.</li><li>If all your accounts at this credit union have been entered, click the button below to calculate your coverage.</li></ul><p><b>Remember:</b> If you edit or delete one of the accounts below after generating a report, you will need to click the button below to recalculate your coverage.</p><p style="text-align: center"><input type="button" value="Calculate" class="calculate_btn"></p></div>';
	} else if(uninsured) {
		report_status = '<div class="uninsured">ATTENTION: E-SIC estimates that some of your money in this financial institution exceeds NCUA limits and is currently not NCUA-insured.</div>';
	} else {
		report_status = '<div>Looks good. According to the information you have entered, E-SIC estimates that your deposit accounts at this financial institution appear to be fully NCUA-insured. But, it is always a good idea to be familiar with NCUA coverage limits and use E-SIC regularly to make sure you are within them.</div>';		
	}
	
	return $(report_status);
}

/////////////////////////////////////////////////////////////////////////////////////////
// VALIDATION FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////

function validate_money(val) {
	
	if(val.match(/^\$?[0-9,]+(.\d\d)?$/)) {
		val = val.replace(/[^0-9\.]/g, "");
		return currency_format(parseFloat(val));
	}
	
	return "";
}

function validate_calculator() {
	
	if(get_account_type() == "personal") {
		return validate_calculator_personal();
	} else {
		return validate_calculator_business();
	}
}

function validate_trust_balance(accountid) {

	var institution = null;
	if(institutions.length) {
		institution = institutions[0];
	} else {
		institution = new Institution();
	}
	
	if($('#account_type').val() != 'ITF' && $('#account_type').val() != 'Trust') return true;
	
	var owners = new Array();

	for(var i = 0; i < institution.personal_accounts.length; i++) {
		var account = institution.personal_accounts[i];
		if(account.id == accountid) continue;
		var balance = money_to_float(account.balance);
		var slice = balance / (account.owners.length * account.beneficiaries.length);
		for(var j = 0; j < account.owners.length; j++) {
			var owner = account.owners[j];
			if(!owners[owner.name.toLowerCase()]) owners[owner.name.toLowerCase()] = 0;
			for(var k = 0; k < account.beneficiaries.length; k++) {
				var bene = account.beneficiaries[k];
				if(bene.type == 'other') continue;
				owners[owner.name.toLowerCase()] += slice;
			}
		}
	}
	
	var owner_ids = $.map($('input.ownerclass'), function(e) { return e.name; });
	var bene_ids = $.map($('input.beneficiaryclass'), function(e) { return e.name; });
	var balance = money_to_float($('#account_balance').val());
	var slice = balance / (owner_ids.length * bene_ids.length);
	for(var i = 0; i < owner_ids.length; i++) {
		var name = $('input[name='+owner_ids[i]+']').val();
		if(!owners[name.toLowerCase()]) owners[name.toLowerCase()] = 0;
		for(var j = 0; j < bene_ids.length; j++) {
			if($('select[name='+bene_ids[j]+'_type]').val() == 'other') continue;
			owners[name.toLowerCase()] += slice;
		}
	}
	
	
	for(var i in owners) {
		if(owners[i] > 1250000) {
			//$('#account_balance_valid').attr('src', 'images/check_red.gif');
			//set_error_message('account_balance_valid','account_balance_valid_trust_over_500');
			return false;
		}
	}
	
	return true;
}

function validate_calculator_business() {

	var valid = true;
	
	if(!validate_institution()) valid = false;
	if(!validate_sole_proprietorship()) valid = false;
	if(!validate_business_name()) valid = false;
	if(!validate_ein()) valid = false;
	if(!validate_business_account_name()) valid = false;
	if(!validate_business_account_balance()) valid = false;
		
	return valid;
}

function validate_calculator_personal() {
	var owner_ids = $.map($('input.ownerclass'), function(e) { return e.name; });
	
	var valid = true;
	if(!validate_institution()) valid = false;
	if(!validate_account_name()) valid = false;
	if(!validate_account_balance()) valid = false;
	if(!validate_account_type(true)) valid = false;
	
	for(var i = 0; i < owner_ids.length; i++) {
		if(!validate_owner_all(owner_ids[i])) {
			valid = false;
		}
	}
	
	if($('#account_type').val() == 'Trust' || $('#account_type').val() == 'ITF') {
		var b_ids = $.map($('input.beneficiaryclass'), function(e) { return e.name; });
		
		for(var i = 0; i < b_ids.length; i++) {
			if(!validate_beneficiary_all(b_ids[i])) {
				valid = false;
			}
		}
	}
	
	return valid;
}

function set_error_message(name, clone) {
	$("#cluetip-close").click();
	
	var key = name;
	if(clone) key = clone;
	
	$('#'+name).attr('title','Error Status');
	$('#'+name).attr('rel', 'messages/'+key+'.txt');
		
	$('#'+name).cluetip({
		arrows: true,
		dropShadow: false, 
		cluetipClass: 'jtipred',
		sticky: true,
		closeText: 'Close',
		onActivate: function() { if($('#'+name).attr('rel')) { return true; } else { return false; } }
	});
}

function clear_error_message(val) {
	$("#cluetip-close").click();
	if(val) $('#'+val).attr('rel', '');
}

function set_help_messages_all() {
	$('span[class=help]').attr('title', 'Help');
	$.each(["institution_help","account_balance_help","business_account_balance_help",
		"business_account_name_help", "account_name_help", "account_type_help",
		"owner_help", "owner_living_help", "beneficiary_help", "beneficiary_living_help",
		"beneficiary_charity_help", "sole_proprietorship_help", "business_name_help", "ein_help" ],
	
	function() {
		$('#'+this).attr('rel','messages/'+this+'.txt').cluetip({
			arrows: true,
			dropShadow: false, 
			cluetipClass: 'jtipgreen',
			sticky: true,
			closeText: 'Close'
		});
	});

}

function validate_sole_proprietorship() {
	if($('#active_account_id').val() != 'new') return true;
	
	if(!$("input[name=sole_proprietorship]:checked").val()) {
		$('#sole_proprietorship_valid').attr('src', 'images/check_red.gif');
		set_error_message('sole_proprietorship_valid');
		return false;
		
	} else if($("input[name=sole_proprietorship]:checked").val() == "yes") {
		if($('input[name=business_account_name]').val()) {
			$('input[name=account_name]').val($('input[name=business_account_name]').val());
			validate_account_name();
		}
		if($('input[name=business_account_balance]').val()) {
			$('input[name=account_balance]').val($('input[name=business_account_balance]').val());
			validate_account_balance();
		}

		$('input[name=business_personal]').filter('[value=personal]').click();
		$('#sole_proprietorship_valid').attr('src', 'images/check_grey.gif');
		clear_error_message('sole_proprietorship_valid');
		$("input[name=sole_proprietorship]").attr("checked", false);
		return true;
	} else {
		$('#sole_proprietorship_valid').attr('src', 'images/check_green.gif');
		clear_error_message('sole_proprietorship_valid');
		return true;
	}
}

function validate_ein() {
	trim_spaces($('input[name=ein]'));
	
	var ein = $('input[name=ein]').val();
	var einvalid = false;
	
	if(!ein) {
		$('#ein_valid').attr('src', 'images/check_red.gif');
		set_error_message('ein_valid');
		return false;
	}
	
	if(ein.match(/\d{3}(-|\s)\d{2}(-|\s)\d{4}/)) {
		$('#ein_valid').attr('src', 'images/check_red.gif');
		set_error_message('ein_valid','ein_valid_format');
		return false;
	}
	
	if(ein.match(/^\d{9}$/)) {
		$('#ein_valid').attr('src', 'images/check_green.gif');
		clear_error_message('ein_valid');
		var formatted = ein.substr(0,2)+"-"+ein.substr(2,7);
		$('input[name=ein]').val(formatted);
		einvalid = true;
	}
	
	if(ein.match(/^\d{2}\s\d{7}$/)) {
		$('#ein_valid').attr('src', 'images/check_green.gif');
		clear_error_message('ein_valid');
		var formatted = ein.replace(/\s/,'-');
		$('input[name=ein]').val(formatted);
		einvalid = true;
	}
	
	if(!einvalid && !ein.match(/^\d{2}-\d{7}$/)) {
		$('#ein_valid').attr('src', 'images/check_red.gif');
		set_error_message('ein_valid','ein_valid_format');
		return false;
	}
	
	return validate_ein_names();

}

function validate_business_name() {
	trim_spaces($('input[name=business_name]'));

	if(!$('input[name=business_name]').val()) {
		$('#business_name_valid').attr('src', 'images/check_red.gif');
		set_error_message('business_name_valid');
		return false;
	} else {
	
		if(!validate_ein_names()) {
			return false;
		}
		
		$('#business_name_valid').attr('src', 'images/check_green.gif');
		clear_error_message('business_name_valid');
		return true;
	}
}

function validate_ein_names() {
	var bname = $('input[name=business_name]').val();
	var ein = $('input[name=ein]').val();
	var institution = institutions.length ? institutions[0] : null;
	
	if(bname && ein && institution) {
		var accounts = institution.business_accounts;
		
		for(var i = 0; i < accounts.length; i++) {
			if(accounts[i].id != $('#active_account_id').val()) {
				if(accounts[i].name.toLowerCase() == bname && accounts[i].ein != ein) {
					$('#ein_valid').attr('src', 'images/check_red.gif');
					set_error_message('ein_valid', 'ein_valid_namedupe');
					return false;
				}
			}
		}
	}
	
	if(ein) {
		$('#ein_valid').attr('src', 'images/check_green.gif');
		clear_error_message('ein_valid');
	}
	
	return true;
}

function validate_business_account_name() {
	trim_spaces($('input[name=business_account_name]'));
	
	if(!$('input[name=business_account_name]').val()) {
		$('#business_account_name_valid').attr('src', 'images/check_red.gif');
		set_error_message('business_account_name_valid');
		return false;
	} else {
		$('#business_account_name_valid').attr('src', 'images/check_green.gif');
		clear_error_message('business_account_name_valid');
		return true;
	}
}

function validate_business_account_balance() {
	trim_spaces($('input[name=business_account_balance]'));

	if($('input[name=business_account_balance]').val() == "" || $('input[name=business_account_balance]').val() == null) {
		$('#business_account_balance_valid').attr('src', 'images/check_red.gif');
		set_error_message('business_account_balance_valid');
		return false;
	}
	
	var balance = validate_money($('input[name=business_account_balance]').val() || "");
	if(balance == "") {
		$('#business_account_balance_valid').attr('src', 'images/check_red.gif');
		set_error_message('business_account_balance_valid','business_account_balance_valid_non_numeric');
		return false;
	} else if(balance == "$0.00") {
		$('#business_account_balance_valid').attr('src', 'images/check_red.gif');
		set_error_message('business_account_balance_valid');
		return false;
	} else {
		$('#business_account_balance_valid').attr('src', 'images/check_green.gif');
		$('input[name=business_account_balance]').val(balance);
		clear_error_message('business_account_balance_valid');
		return true;
	}
}

function validate_account_name() {
	trim_spaces($('input[name=account_name]'));
	
	if(!$('input[name=account_name]').val()) {
		$('#account_name_valid').attr('src', 'images/check_red.gif');
		set_error_message('account_name_valid');
		return false;
	} else {
		$('#account_name_valid').attr('src', 'images/check_green.gif');
		clear_error_message('account_name_valid');
		return true;
	}
}

function validate_institution() {	
	should_warn = true;
	
	if(!$('input[name=institution]').length) {
		$('#institution_valid').attr('src', 'images/check_green.gif');
		clear_error_message('institution_valid');
		return true;
	}
	
	trim_spaces($('input[name=institution]'));
	
	if(!$('input[name=institution]').val()) {
		$('#institution_valid').attr('src', 'images/check_red.gif');
		set_error_message('institution_valid');
		return false;
	} else {
		if($('input[name=business_personal]:checked').length) swap_institution();
		
		$('#institution_valid').attr('src', 'images/check_green.gif');
		clear_error_message('institution_valid');
		return true;
	}
}

function validate_account_balance() {
	
	if($('input[name=account_balance]').val() == "" || $('input[name=account_balance]').val() == null) {
		$('#account_balance_valid').attr('src', 'images/check_red.gif');
		set_error_message('account_balance_valid');
		return false;
	}
	
	trim_spaces($('input[name=account_balance]'));
	
	var balance = validate_money($('input[name=account_balance]').val() || "");
	
	if(balance == "") {
		$('#account_balance_valid').attr('src', 'images/check_red.gif');
		set_error_message('account_balance_valid','account_balance_valid_non_numeric');
		return false;
	} else if(balance == "$0.00") {
		$('#account_balance_valid').attr('src', 'images/check_red.gif');
		set_error_message('account_balance_valid');
		return false;
	} else {
		$('input[name=account_balance]').val(balance);
		clear_error_message('account_balance_valid');
		$('#account_balance_valid').attr('src', 'images/check_green.gif');
		return true;
	}
}

function validate_account_type(submitted, manual_select) {
	
	if(!submitted) submitted = false;
	
	if(!$("#account_type").val()) {
		$('#account_type_valid').attr('src', 'images/check_red.gif');
		set_error_message('account_type_valid');
		return false;
	} else {
		hide_beneficiaries();

		if(($('#account_type').val() == 'Retirement' || $('#account_type').val() == 'Single') && $('.ownerclass').length > 1) {
			if(!$('input[name=owner_last]').val()) { remove_owner('owner_last', true); }
		}

		if($('#account_type').val() == 'Retirement' && $('.ownerclass').length > 1) {
			$('#account_type_valid').attr('src', 'images/check_red.gif');
			set_error_message('account_type_valid','account_type_valid_retirement');
			return false;
		}
		
		if($('#account_type').val() == 'Single' && $('.ownerclass').length > 1) {
			$('#account_type_valid').attr('src', 'images/check_red.gif');
			set_error_message('account_type_valid','account_type_valid_single');
			return false;
		}
		
		if($('#account_type').val() == 'Retirement' || $('#account_type').val() == 'Single') {
			$('#add_additional_owner_btn').hide();
		} else {
			$('#add_additional_owner_btn').show();
		}

		if(($('#account_type').val() == 'Trust' || $('#account_type').val() == 'ITF') && $('.ownerclass').length > 3) {
			show_alert("<p>E-SIC cannot calculate the insurance coverage of Living Trust or ITF/POD accounts with more than 3 owners. Please contact NCUA at 800-755-1030 for assistance in determining the insurance coverage of your accounts.</p>");
			$('#account_type').val('');
			return validate_account_type(submitted);
		}
		
		if(submitted) {
			if($('#account_type').val() == 'Joint' && $('.ownerclass').length == 1) {
				$('#account_type_valid').attr('src', 'images/check_red.gif');
				set_error_message('account_type_valid','account_type_valid_joint');
				return false;
			}
		}
		
		if(manual_select) {
			if($('#account_type').val() == 'Joint' && $('.ownerclass').length == 1) {
				add_additional_owner(true);
			}
		}
		
		if($("#account_type").val() == 'Other') {
			$('#account_type_valid').attr('src', 'images/check_red.gif');
			set_error_message('account_type_valid', 'account_type_valid_other');
			return false;
		}
		
		$('#account_type_valid').attr('src', 'images/check_green.gif');
		clear_error_message('account_type_valid');
		
		if($('#account_type').val() == 'Trust' || $('#account_type').val() == 'ITF') {
			show_beneficiaries();
		}
		
		return true;
	}
}

function validate_owner_all(oid) {
	var valid = true;
	
	if(!validate_owner_name(oid)) {
		valid = false;
	}
	
	if(!validate_owner_living(oid)) {
		valid = false;
	}
	
	return valid;
}

function check_for_compound_owner(eid) {
	var value = $('input[name='+eid+']').val();
	
	if(value.match(/(\sand\s|&)/i)) {
		show_confirm("It appears you're trying to put two owners in the same field. Each person's name must be added separately.<br/><br/>If E-SIC has caught this by mistake please press Proceed. Otherwise, please hit Cancel and correct this.",
		function() {
			validate_owner_name(eid);
		},
		function() {
			$('input[name='+eid+']').focus();
		});
		
		return true;
	}
}

function check_for_compound_beneficiary(eid) {
	var value = $('input[name='+eid+']').val();
	
	if(value.match(/(\sand\s|&)/i)) {
		show_confirm("It appears you're trying to put two beneficiaries in the same field. Each person's name must be added separately.<br/><br/>If E-SIC has caught this by mistake please press Proceed. Otherwise, please hit Cancel and correct this.",
		function() {
			validate_beneficiary_name(eid);
		},
		function() {
			$('input[name='+eid+']').focus();
		});
		
		return true;
	}
}

function validate_owner_name(oid, do_compound_check) {
	
	trim_spaces($('input[name='+oid+']'));
	
	if(do_compound_check && check_for_compound_owner(oid)) {
		return false;
	}
		
	if(!$('input[name='+oid+']').val()) {
		$('#'+oid+'_valid').attr('src', 'images/check_red.gif');
		set_error_message(oid+'_valid','owner_last_valid');
		return false;
	} else {
		return cross_validate_all_names();
	}
	
}

function cross_validate_all_names() {
	var owner_ids = $.map($('input.ownerclass'), function(e) { return e.name; });
	var bene_ids = $.map($('input.beneficiaryclass'), function(e) { return e.name; });

	var seen = get_owner_name_counts();
	var benes = get_beneficiary_name_counts();

	var valid = true;
	
	for(var i = 0; i < owner_ids.length; i++) {
		var oid = owner_ids[i];
		if(seen[$('input[name='+oid+']').val().toLowerCase()] > 1) {
			$('#'+oid+'_valid').attr('src', 'images/check_red.gif');
			set_error_message(oid+'_valid','owner_last_valid_dupe');
			valid = false;
		} else if($('input[name='+oid+']').val()) {
			$('#'+oid+'_valid').attr('src', 'images/check_green.gif');
			clear_error_message(oid+'_valid');
		}
	}
	
	if($('#account_type').val() == 'Trust' || $('#account_type').val() == 'ITF') {
		for(var i = 0; i < bene_ids.length; i++) {
			var bid = bene_ids[i];
			var bidvalid = true;
			
			if(benes[$('input[name='+bid+']').val().toLowerCase()] > 1) {
				$('#'+bid+'_valid').attr('src', 'images/check_red.gif');
				set_error_message(bid+'_valid','beneficiary_last_valid_dupe');
				valid = false;
				bidvalid = false;
			}
			
			if(seen[$('input[name='+bid+']').val().toLowerCase()]) {
				$('#'+bid+'_valid').attr('src', 'images/check_red.gif');
				set_error_message(bid+'_valid','beneficiary_owner_dupe');
				valid = false;
				bidvalid = false;
			}
			
			if(bidvalid && $('input[name='+bid+']').val()) {
				$('#'+bid+'_valid').attr('src', 'images/check_green.gif');
				clear_error_message(bid+'_valid');
			}
		}
	}
	
	return valid;

}

function validate_owner_living(oid) {
	
	if($("input[name="+oid+"_living]:checked").length == 0) {
		$('#'+oid+'_living_valid').attr('src', 'images/check_red.gif');
		set_error_message(oid+'_living_valid', 'owner_last_living_valid');
		return false;
	} else if($("input[name="+oid+"_living]:checked").val() != 'yes') {
		$('#'+oid+'_living_valid').attr('src', 'images/check_red.gif');
		set_error_message(oid+'_living_valid', 'owner_last_living_valid_deceased');
		return false;
	} else {
		$('#'+oid+'_living_valid').attr('src', 'images/check_green.gif');
		clear_error_message(oid+'_living_valid');
		return true;
	}

}

function validate_beneficiary_all(bid) {
	var valid = true;
	
	if(!validate_beneficiary_name(bid)) {
		valid = false;
	}
	
	if(!validate_beneficiary_type(bid)) {
		valid = false;
	}
	
	if(!validate_beneficiary_charity(bid)) {
		valid = false;
	}
	
	if(!validate_beneficiary_living(bid)) {
		valid = false;
	}
	
	return valid;
}

function validate_beneficiary_name(bid, do_compound_check) {
	
	trim_spaces($('input[name='+bid+']'));
	
	if(do_compound_check && check_for_compound_beneficiary(bid)) {
		return false;
	}
	
	if(!$('input[name='+bid+']').val()) {
		$('#'+bid+'_valid').attr('src', 'images/check_red.gif');
		set_error_message(bid+'_valid', 'beneficiary_last_valid');
		return false;
	} else {

		return cross_validate_all_names();
	}
	
}

function validate_beneficiary_type(bid, manualchange) {
	toggle_beneficiary_type_checks(bid, manualchange);

	if(!$("select[name="+bid+"_type]").val()) {
		$('#'+bid+'_type_valid').attr('src', 'images/check_red.gif');
		set_error_message(bid+'_type_valid', 'beneficiary_last_type_valid');
		return false;
	}
	
	
	if($("select[name="+bid+"_type]").val() == 'trust') {
		$('#'+bid+'_type_valid').attr('src', 'images/check_red.gif');
		set_error_message(bid+'_type_valid', 'beneficiary_last_type_valid_trust');
		return false;
	}
	
	$('#'+bid+'_type_valid').attr('src', 'images/check_green.gif');
	clear_error_message(bid+'_type_valid');
	return true;
}
	
function validate_beneficiary_living(bid) {
	
	if($('select[name='+bid+'_type]').val() != "person") return true;
	if($("input[name="+bid+"_living]:checked").length == 0) {
		$('#'+bid+'_living_valid').attr('src', 'images/check_red.gif');
		set_error_message(bid+'_living_valid', 'beneficiary_last_living_valid');
		return false;
	} else if($("input[name="+bid+"_living]:checked").val() != 'yes') {
		$('#'+bid+'_living_valid').attr('src', 'images/check_red.gif');
		set_error_message(bid+'_living_valid', 'beneficiary_last_living_valid_deceased');
		return false;
	} else {
		$('#'+bid+'_living_valid').attr('src', 'images/check_green.gif');
		clear_error_message(bid+'_living_valid');
		return true;
	}

}

function validate_beneficiary_charity(bid) {
	
	if($('select[name='+bid+'_type]').val() != "charity") return true;
	if($("input[name="+bid+"_charity]:checked").length == 0) {
		$('#'+bid+'_charity_valid').attr('src', 'images/check_red.gif');
		set_error_message(bid+'_charity_valid', 'beneficiary_last_charity_valid');
		return false;
	} else if($("input[name="+bid+"_charity]:checked").val() != 'yes') {
		$('#'+bid+'_charity_valid').attr('src', 'images/check_red.gif');
		set_error_message(bid+'_charity_valid', 'beneficiary_last_charity_valid_no');
		return false;
	} else {
		$('#'+bid+'_charity_valid').attr('src', 'images/check_green.gif');
		clear_error_message(bid+'_charity_valid');
		return true;
	}

}


/////////////////////////////////////////////////////////////////////////////////////////
// DOM FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////

function reset_owner_all(oid) {
	
	$('input[name='+oid+'_living]').attr('checked',false);
	$('input[name='+oid+']').val('');
	$('#'+oid+'_valid').attr('src', 'images/check_grey.gif');
	$('#'+oid+'_living_valid').attr('src', 'images/check_grey.gif');
	clear_error_message(oid+'_valid');
	clear_error_message(oid+'_living_valid');
}

function add_additional_owner(skip_previous_validation) {
	
	if($('#account_type').val() == 'Retirement') {
		show_alert("<p>An IRA can only have one owner.</p>");
		return;
	}
	
	if($('#account_type').val() == 'Single') {
		show_alert("<p>A single account can only have one owner.  If this account has more than one owner and does not name beneficiaries, select Joint Account in the Ownership Type field in order to add an additional owner.</p>");
		return;
	}

	var owner_ids = $.map($('input.ownerclass'), function(e) { return e.name; });
 	
	if($('#account_type').val() == 'Joint' && owner_ids.length >= 10) {
		show_alert("<p>Joint Ownership Accounts may only have a maximum of 10 owners.</p>");
		return;
	}
	
	if(($('#account_type').val() == 'Trust' || $('#account_type').val() == 'ITF') && owner_ids.length >= 3) {
		show_alert("<p>E-SIC cannot calculate the insurance coverage of Living Trust or ITF/POD accounts with more than 3 owners. Please contact NCUA at 800-755-1030 for assistance in determining the insurance coverage of your accounts.</p>");
		return;
	}
	
	validate_owner_all('owner_last');
	
	var new_id = 'owner_'+get_sequence();
	$('#owner_last_tr_line').clone().attr('id',new_id+'_tr_line').insertBefore('#owner_last_tr_line');

	$('<tr id="'+new_id+'_tr"><td valign="top" align="left"><nobr><span class="help" title="Help" id="'+new_id+'_help"><img src="images\/help.gif" alt="Help" width="22" height="18" border="0">Owner</span></nobr></td><td valign="top" align="left"><nobr><input name="'+new_id+'" maxlength="25" size="30" type="text" style="width: 180px;" class="ownerclass"><img src="images\/check_grey.gif" width="22" height="20" alt="Status" border="0" class="valid" id="'+new_id+'_valid"></nobr></td><td valign="top" align="left"><nobr><span class="help" title="Help" id="'+new_id+'_living_help"><img src="images\/help.gif" alt="Help" width="22" height="18" border="0">Is the owner living?</span><img src="images\/check_grey.gif" width="22" height="20" alt="Status" border="0" id="'+new_id+'_living_valid"></nobr><br/><input name="'+new_id+'_living" type="radio" value="yes"> Yes<br/><input name="'+new_id+'_living" type="radio" value="no"> No</td></tr>').insertBefore('#owner_last_tr_line');

	if($("input[name=owner_last_living]:checked").val()) 
		$("input[name="+new_id+"_living]").val([$("input[name=owner_last_living]:checked").val()]);
	if($('input[name=owner_last]').val())
		$('input[name='+new_id+']').val($('input[name=owner_last]').val());

	$("input[name="+new_id+"_living]").bind("click", function(e) { validate_owner_living(new_id); });
	$('input[name='+new_id+']').bind("blur", function(e) { validate_owner_name(new_id, true); });
	$('#'+new_id+'_help').attr('rel','messages/owner_help.txt').cluetip({
			arrows: true,
			dropShadow: false, 
			cluetipClass: 'jtipgreen',
			sticky: true,
			closeText: 'Close'
	});
		
	$('#'+new_id+'_living_help').attr('rel','messages/owner_living_help.txt').cluetip({
			arrows: true,
			dropShadow: false, 
			cluetipClass: 'jtipgreen',
			sticky: true,
			closeText: 'Close'
	});
	
	$('<a href="javascript:remove_owner(\''+new_id+'\')"><img src="images\/delete.gif" alt="Delete" width="22" height="20" border="0"/></a>').insertAfter('#'+new_id+'_tr .valid');
	if(!$('#owner_last_tr #owner_last_link').length) $('<a id="owner_last_link" href="javascript:remove_owner(\'owner_last\')"><img src="images\/delete.gif" alt="Delete" width="22" height="20" border="0"/></a>').insertAfter('#owner_last_tr .valid');
	
	reset_owner_all('owner_last');
	if(!skip_previous_validation) {
		validate_owner_all(new_id);
	} else {
		if($('input[name='+new_id+']').val()) {
			validate_owner_name(new_id);
		}
		if($('input[name='+new_id+'_living]:checked').val()) {
			validate_owner_living(new_id);
		}
	}
	
	$('input[name='+new_id+']').autocomplete(known_people);
}

function remove_owner(owner_id, skip_previous_validation) {
	
	if(owner_id == 'owner_last') {
		var owner_ids = $.map($('input.ownerclass'), function(e) { if(e.name != 'owner_last') return e.name; });
		var source_id = owner_ids.pop();
		
		$("input[name=owner_last]").val([$("input[name="+source_id+"]").val()] || "");
		if($('input[name='+source_id+'_living]:checked').val())
			$('input[name=owner_last_living]').val([$('input[name='+source_id+'_living]:checked').val()]);
		else
			$('input[name=owner_last_living]').attr("checked", false);
			
		$('#'+source_id+'_tr_line').remove();
		$('#'+source_id+'_tr').remove();
		
        	if(!skip_previous_validation) {
        	        validate_owner_all('owner_last');
	        } else {
        	        if($('input[name=owner_last]').val()) {
	                        validate_owner_name('owner_last');
	                }
        	        if($('input[name=owner_last_living]:checked').val()) {
        	                validate_owner_living('owner_last');
        	        }
		}

	} else {
		$('#'+owner_id+'_tr_line').remove();
		$('#'+owner_id+'_tr').remove();
		cross_validate_all_names();
	}
	
	
	var owner_ids = $.map($('input.ownerclass'), function(e) { return e.name; });
	if(owner_ids.length == 1) {
		$('#owner_last_link').remove();
	}
	
	if($("select[name=account_type]").val()) {
		validate_account_type();
	}
}

function add_additional_beneficiary() {

	var ben_ids = $.map($('input.beneficiaryclass'), function(e) { return e.name; });
 	
	if(($('#account_type').val() == 'Trust' || $('#account_type').val() == 'ITF') && ben_ids.length >= 20) {
		show_alert("<p>E-SIC cannot calculate the insurance coverage of Living Trust or ITF/POD accounts with more than 20 beneficiaries. Please contact NCUA at 800-755-1030 for assistance in determining the insurance coverage of your accounts.</p>");
		return;
	}
	
	validate_beneficiary_all('beneficiary_last');
		
	var new_id = 'beneficiary_'+get_sequence();
	$('#beneficiary_last_tr_line').clone().attr('id',new_id+'_tr_line').insertBefore('#beneficiary_last_tr_line');

	$('<tr id="'+new_id+'_tr" class="beneficiary"><td valign="top" align="left"><nobr><span title="Help" class="help" id="'+new_id+'_help"><img src="images\/help.gif" alt="Help" width="22" height="18" border="0">Beneficiary</span></nobr></td><td valign="top" align="left"><nobr><input name="'+new_id+'" maxlength="25" size="30" type="text" style="width: 180px;" class="beneficiaryclass"><img src="images\/check_grey.gif" width="22" height="20" alt="Status" border="0" class="valid" id="'+new_id+'_valid"></nobr><br/><div id="'+new_id+'_type_div"><nobr><select id="'+new_id+'_type" name="'+new_id+'_type"><option value="">Beneficiary Type...</option><option value="person">Person</option><option value="charity">Charity/Non-profit Org</option><option value="trust">Living Trust</option><option value="other">Other</option></select><img src="images/check_grey.gif" width="22" height="20" alt="Status" border="0" id="'+new_id+'_type_valid"></nobr></div></td><td valign="top" align="left"><div id="'+new_id+'_living_div"><nobr><span class="help" id="beneficiary_living_help"><img src="images/help.gif" alt="Help" width="22" height="18" border="0">Is the beneficiary living?</span><img src="images/check_grey.gif" width="22" height="20" alt="Status" border="0" id="'+new_id+'_living_valid"></nobr><br><input name="'+new_id+'_living" type="radio" value="yes" id="'+new_id+'_living_yes"><label for="'+new_id+'_living_yes">Yes</label> <br><input name="'+new_id+'_living" type="radio" value="no" id="'+new_id+'_living_no"><label for="'+new_id+'_living_no">No</label></div><div id="'+new_id+'_charity_div"><nobr><span class="help" id="beneficiary_charity_help"><img src="images/help.gif" alt="Help" width="22" height="18" border="0">Is this charity/non-profit org.</span><img src="images/check_grey.gif" width="22" height="20" alt="Status" border="0" id="'+new_id+'_charity_valid"><br/>recognized by the IRS?</nobr><br><input name="'+new_id+'_charity" type="radio" value="yes" id="'+new_id+'_charity_yes"><label for="'+new_id+' _charity_yes">Yes</label> <br><input name="'+new_id+'_charity" type="radio" value="no" id="'+new_id+'_charity_no"><label for="'+new_id+'_charity_no">No</label></div></td></tr>').insertBefore('#beneficiary_last_tr_line');
	
	if($("input[name=beneficiary_last_living]:checked").val()) 
		$("input[name="+new_id+"_living]").val([$("input[name=beneficiary_last_living]:checked").val()]);

	if($("input[name=beneficiary_last_charity]:checked").val()) 
		$("input[name="+new_id+"_charity]").val([$("input[name=beneficiary_last_charity]:checked").val()]);
	if($("select[name=beneficiary_last_type]").val())
		$("select[name="+new_id+"_type]").val($("select[name=beneficiary_last_type]").val());
	if($("input[name=beneficiary_last]").val()) 
		$("input[name="+new_id+"]").val([$("input[name=beneficiary_last]").val()]);

	$("input[name="+new_id+"_living]").bind("click", function(e) { validate_beneficiary_living(new_id); });
	$('input[name='+new_id+']').bind("blur", function(e) { validate_beneficiary_name(new_id, true); return true; });
	$('input[name='+new_id+'_charity]').bind("click", function(e) { validate_beneficiary_charity(new_id); });
	$('select[name='+new_id+'_type]').bind("change", function(e) { validate_beneficiary_type(new_id, true); });
	
	toggle_beneficiary_type_checks(new_id);
	
	$('#'+new_id+'_help').attr('rel','messages/beneficiary_help.txt').cluetip({
			arrows: true,
			dropShadow: false, 
			cluetipClass: 'jtipgreen',
			sticky: true,
			closeText: 'Close'
	});
		
	$('#'+new_id+'_living_help').attr('rel','messages/beneficiary_living_help.txt').cluetip({
			arrows: true,
			dropShadow: false, 
			cluetipClass: 'jtipgreen',
			closeText: 'Close',
			sticky: true
	});
	
	$('#'+new_id+'_charity_help').attr('rel','messages/beneficiary_charity_help.txt').cluetip({
			arrows: true,
			dropShadow: false, 
			cluetipClass: 'jtipgreen',
			closeText: 'Close',
			sticky: true
	});


	$('<a href="javascript:remove_beneficiary(\''+new_id+'\')"><img src="images\/delete.gif" alt="Delete" width="22" height="20" border="0"/></a>').insertAfter('#'+new_id+'_tr .valid');
	if(!$('#beneficiary_last_tr #beneficiary_last_link').length) $('<a id="beneficiary_last_link" href="javascript:remove_beneficiary(\'beneficiary_last\')"><img src="images\/delete.gif" alt="Delete" width="22" height="20" border="0"/></a>').insertAfter('#beneficiary_last_tr .valid');
	
	reset_beneficiary_all('beneficiary_last');
	validate_beneficiary_all(new_id);
	$('input[name='+new_id+']').autocomplete(known_people);
	
}

function toggle_beneficiary_type_checks(bid, manualchange) {
	$('#'+bid+'_living_div').hide();
	$('#'+bid+'_charity_div').hide();
	
	var value = $('select[name='+bid+'_type]').val();
	if(value == 'person') {
		if(manualchange) {
			$('input[name='+bid+'_living]').attr('checked', false);
			$('#'+bid+'_living_valid').attr('src', 'images/check_grey.gif');
			clear_error_message(bid+'_living_valid');
		}
		$('#'+bid+'_living_div').show();
	}
	if(value == 'charity') {
		if(manualchange) {
			$('input[name='+bid+'_charity]').attr('checked', false);
			$('#'+bid+'_charity_valid').attr('src', 'images/check_grey.gif');
			clear_error_message(bid+'_charity_valid');
		}
		$('#'+bid+'_charity_div').show();
	}


}

function reset_beneficiary_all(bid) {
	
	$('input[name='+bid+'_living]').attr('checked',false);
	$('input[name='+bid+'_charity]').attr('checked',false);
	$('select[name='+bid+'_type]').val('');
	$('#'+bid+'_living_div').hide();
	$('#'+bid+'_charity_div').hide();
	
	$('input[name='+bid+']').val('');
	$('#'+bid+'_valid').attr('src', 'images/check_grey.gif');
	clear_error_message(bid+'_valid');
	$('#'+bid+'_living_valid').attr('src', 'images/check_grey.gif');
	clear_error_message(bid+'_living_valid');
	$('#'+bid+'_charity_valid').attr('src', 'images/check_grey.gif');
	clear_error_message(bid+'_charity_valid');
	$('#'+bid+'_type_valid').attr('src', 'images/check_grey.gif');
	clear_error_message(bid+'_type_valid');
}

function remove_beneficiary(beneficiary_id) {
	if(beneficiary_id == 'beneficiary_last') {
		var beneficiary_ids = $.map($('input.beneficiaryclass'), function(e) { if(e.name != 'beneficiary_last') return e.name; });
		var source_id = beneficiary_ids.pop();
		
		$("input[name=beneficiary_last]").val([$("input[name="+source_id+"]").val()] || "");
		if($('input[name='+source_id+'_living]:checked').val())
			$('input[name=beneficiary_last_living]').val([$('input[name='+source_id+'_living]:checked').val()]);
		else
			$('input[name=beneficiary_last_living]').attr("checked", false);

		if($('input[name='+source_id+'_charity]:checked').val())
			$('input[name=beneficiary_last_charity]').val([$('input[name='+source_id+'_charity]:checked').val()]);
		else
			$('input[name=beneficiary_last_charity]').attr("checked", false);
				
			
		$('input[name=beneficiary_last]').val($('input[name='+source_id+']').val() || "");
		
		if($("select[name="+source_id+"_type]").val())
			$('select[name=beneficiary_last_type]').val($("select[name="+source_id+"_type]").val());
		
		toggle_beneficiary_type_checks('beneficiary_last');
		
		$('#'+source_id+'_tr_line').remove();
		$('#'+source_id+'_tr').remove();
		
		validate_beneficiary_all('beneficiary_last');
		
	} else {
		$('#'+beneficiary_id+'_tr_line').remove();
		$('#'+beneficiary_id+'_tr').remove();
		cross_validate_all_names();
		
	}
	
	
	var beneficiary_ids = $.map($('input.beneficiaryclass'), function(e) { return e.name; });
	if(beneficiary_ids.length == 1) {
		$('#beneficiary_last_link').remove();
	}

}

function show_beneficiaries() {
	$('.beneficiary').show();
}

function hide_beneficiaries() {
	$('.beneficiary').hide();
}

function show_personal() {
	if($('input[name=institution]').length && $('input[name=institution]').val()) swap_institution();
	should_warn = true;
	$('#personal_div').show();
	$('#button_div').show();
	$('#business_div').hide();
	clear_error_message();
}

function show_business() {
	if($('input[name=institution]').length && $('input[name=institution]').val()) swap_institution();
	should_warn = true;
	$('#business_div').show();
	$('#button_div').show();
	$('#personal_div').hide();
	clear_error_message();
}

function show_calculator() {
	$('#calculator_banner').attr('src','images/hdg_calculator_downarrow.gif');
	$('#calculator_div').show();
	clear_error_message();
	
}

function hide_calculator() {
	$('#calculator_banner').attr('src','images/hdg_calculator_sidearrow.gif');
	$('#calculator_div').hide();
	clear_error_message();
}

function toggle_calculator() {
	if($('#calculator_div').css('display') == 'none') {
		show_calculator();
	} else {
		hide_calculator()
	}
}

function show_report() {
	$('#report_banner').attr('src','images/hdg_report_downarrow.gif');
	$('#report_div').show();
	clear_error_message();
}

function hide_report() {
	$('#report_banner').attr('src','images/hdg_report_sidearrow.gif');
	$('#report_div').hide();
	clear_error_message();
}

function toggle_report() {
	if($('#report_div').css('display') == 'none') {
		show_report();
	} else {
		hide_report();
	}
}

function show_actions() {
	$('#actions_banner').attr('src','images/hdg_actions_downarrow.gif');
	$('#actions_div').show();
	clear_error_message();
}

function hide_actions() {
	$('#actions_banner').attr('src','images/hdg_actions_sidearrow.gif');
	$('#actions_div').hide();
	clear_error_message();
}

function toggle_actions() {
	if($('#actions_div').css('display') == 'none') {
		show_actions();
	} else {
		hide_actions();
	}
}

/////////////////////////////////////////////////////////////////////////////////////////
// UTILITY FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////


function get_owner_name_counts() {
	var owner_names = $.map($('.ownerclass'), function(e) { return e.value.toLowerCase() });
	var seen = new Array();
	for(var i = 0; i < owner_names.length; i++) {
		var name = owner_names[i];
		if(!name) continue;
		
		if(!seen[name])
			seen[name] = 1;
		else
			seen[name] += 1;
	}
	
	return seen;
}
	
function get_beneficiary_name_counts() {
	var ben_names = $.map($('.beneficiaryclass'), function(e) { return e.value.toLowerCase() });
	var seen = new Array();
	for(var i = 0; i < ben_names.length; i++) {
		var name = ben_names[i];
		if(!name) continue;
		
		if(!seen[name])
			seen[name] = 1;
		else
			seen[name] += 1;
	}
	
	return seen;
}

function get_sequence() {
	sequence = sequence + 1;
	return sequence;
}

function get_account_type() {
	return $('input[name=business_personal]:checked').val();
}

function find_account(id) {
	for(var i = 0; i < institutions.length; i++) {
		var institution = institutions[i];
		for(var j = 0; j < institution.personal_accounts.length; j++) {
			var account = institution.personal_accounts[j];
			if(account.id == id) {
				return account;
			}
		}
		for(var j = 0; j < institution.business_accounts.length; j++) {
			var account = institution.business_accounts[j];
			if(account.id == id) {
				return account;
			}
		}		
	}
	
	return null;
}

function cap_firsts(val) {
   
	new_val = '';
	val = val.split(' ');
	for(var c=0; c < val.length; c++) {
		new_val += val[c].substring(0,1).toUpperCase() +
		val[c].substring(1,val[c].length) + ' ';
	}
	
	return trim_spaces(new_val);
}


function money_to_float(val) {
	
	if(!val) { val = "0"; }
	val = val.replace(/[^0-9\.]/g, "");
	return parseFloat(val);
}

function currency_format(number, remove_cents) {
	
	number = "" + number;
	if(!number) number = "0";
	
	var dec = number.indexOf(".");
	var end = ((dec > -1) ? "" + number.substring(dec,number.length) : ".00");

	number = "" + parseInt(number);

	var temp1 = "";
	var temp2 = "";

	if (end.length == 2) end += "0";
	if (end.length == 1) end += "00";
	if (end.length > 2) end = end.substring(0,3);
	
	if (end == "") end += ".00";
	
	var count = 0;
	
	for (var k = number.length-1; k >= 0; k--) {
		var one_char = number.charAt(k);
		if (count == 3) {
			temp1 += ",";
			temp1 += one_char;
			count = 1;
			continue;
		} else {
			temp1 += one_char;
			count ++;
		}
	}

	for (var k = temp1.length-1; k >= 0; k--) {
		var one_char = temp1.charAt(k);
		temp2 += one_char;
	}
	
	if(!remove_cents) temp2 = "$" + temp2 + end;
	else temp2 = "$" + temp2;
	
	return temp2;
}

function trim_spaces(obj) {
	
	if(typeof(obj) == "string") {
		obj = obj.replace(/^\s+/, '');
		obj = obj.replace(/\s+$/, '');
		return obj;
	} else {
		var value = obj.val();
		if(value) {
			value = value.replace(/^\s+/, '');
			value = value.replace(/\s+$/, '');
			obj.val(value);
		}
	}
}


function show_alert(mesg) {
	$('#error_validation_content').empty();
	$('#validation_buttons_area').empty();
	
	$('#error_validation_content').html(mesg);
	$('<input type="button" id="validation_ok" value="&nbsp;&nbsp;Ok&nbsp;&nbsp;"/>').appendTo('#validation_buttons_area');
	$('#validation_ok').bind('click', function() { tb_remove(); });
	
	$('#validation_trigger').click();
}

function show_confirm(mesg, callback, callback_cancel) {
	
	var proceedfunc = function() { callback(); tb_remove(); };
	var cancelfunc = function() { tb_remove(); };
	
	if(callback_cancel != null) cancelfunc = function() { callback_cancel(); tb_remove(); };
	
	$('#confirm_content').empty();
	$('#confirm_buttons_area').empty();
	
	$('#confirm_content').html(mesg);
	$('<input id="confirm_button" type="button" value="&nbsp;&nbsp;Proceed&nbsp;&nbsp;" /><input type="button" value="&nbsp;&nbsp;Cancel&nbsp;&nbsp;" id="cancel_button" />').appendTo('#confirm_buttons_area');
	
	$('#confirm_button').bind('click', proceedfunc);
	$('#cancel_button').bind('click', cancelfunc);
	$('#confirm_trigger').click();
	
}

function contact_trigger() {
	tb_remove();
	setTimeout(function() { 
		show_warning('http://www.ncua.gov/AboutNcua/ncua_directory.html');
	}, 500);
}

function swap_institution() {
	var institution_name = $('#institution').val();
	$('#institution').replaceWith($('<span id="institution">'+institution_name+'</span>'));
}

function swap_institution_back() {
	var institution_name = $('#institution').val();
	$('#institution').replaceWith($('<input id="institution" maxlength="25" size="30" type="text" style="width: 180px;" name="institution">'));
	$('#institution').bind('blur', function(e) { validate_institution(); });
	$('#institution_valid').attr('src', 'images/check_grey.gif');
	clear_error_message('institution_valid');
	
}

function show_warning(target) {

	if(should_warn) {
		show_confirm('If you move away from E-SIC you\'ll lose all of the information you\'ve entered.', function() { location.href = target; });
	} else {
		location.href = target;
	}
	return;
	
}

function check_popups() {
  var win = window.open('printgeneric.html','popwin','status=0,toolbar=0,location=0,menubar=1,directories=0,resizable=1,scrollbars=1,height=50,width=50');
  
  if(win) {
    win.close();
  } else {
    show_alert("It appears you are using Internet Explorer 6 with the popup-blocker enabled. Unfortunately, E-SIC will not function correctly with this setting. Please disable it from the browser's Tools menu before using E-SIC.");
  }
}

function roundit(value) {
  
  var string = value+"";
  if(string.match(/\.99/)) {
    return Math.round(value);
  }
  return value;
}

/////////////////////////////////////////////////////////////////////////////////////////
// MAIN
/////////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function() {
	$('#javascript_div').show();
	$('#printme').hide();
	set_help_messages_all();
	populate_calculator();
	render_actions();
	render_report();
  
	jQuery.each(jQuery.browser, function(i, val) {
    if(i=="msie" && jQuery.browser.version.substr(0,1)=="6")
      check_popups();
  });
  
});

