// js/fa.js

var asset_popup = null;
var uploader_popup = null;
function fa_document_ready()
{
	var loop, _ids, comma, the_id;
	Date.firstDayOfWeek = 0;
	Date.format = 'mm/dd/yyyy';
	
	$('#header').addClass('dont_print_this');
	$('#selCourt,#selCounty,#txtPlaintiff,#txtDefendant,#selPlaintiffParty,#txtCaseNumber').addClass('save_me');
	
	// case style
	$('#selCourt,#selCounty')
		.bind('change keyup',function(){
			var selector = '#' + this.id + ' option:selected';
			var val = $(selector).text();
			update_printable(this.id, val.toUpperCase());
		})
		.trigger('change');
	$('#txtPlaintiff')
		.bind('blur',function(){
			var val = blur_text_field(this.id, {upper:1});
			if ( val == '' ) val = '(Plaintiff)';
			$('#optAffiant_Plaintiff').html(val);
			$('#selAffiant').trigger('change');
		})
		.trigger('blur');
	$('#txtDefendant')
		.bind('blur',function(){
			var val = blur_text_field(this.id, {upper:1});
			if ( val == '' ) val = '(Defendant)';
			$('#optAffiant_Defendant').html(val);
			$('#selAffiant').trigger('change');
		})
		.trigger('blur');
	$('#selAffiant')
		.bind('change keyup',function(){
			var tmp = '#' + this.value;
			var val = $(tmp).val();
			update_printable(this.id, val.toUpperCase());
			update_printable(this.id+'2', val);
			update_printable(this.id+'3', val.toUpperCase());
			tmp = ( this.value == 'txtDefendant' ) ? '#txtPlaintiff' : '#txtDefendant';
			val = $(tmp).val();
			update_printable('selSpouse', val);
			$('#selPlaintiffParty').trigger('change');
		})
		.trigger('change');
	$('#selPlaintiffParty')
		.bind('change keyup',function(){
			var val = this.value;
			update_printable(this.id, val);
			var val2 = ( val == 'Plaintiff' ) ? 'Defendant' : 'Respondent';
			update_printable('selDefendantParty', val2+'.');
			if ( $('#selAffiant').val() == 'txtPlaintiff' )
			{
				update_printable('txtParty', val);
				update_printable('txtParty2', val);
			}
			else
			{
				update_printable('txtParty', val2);
				update_printable('txtParty2', val2);
			}
		})
		.trigger('change');
	
	// section 1
	$('#txtAffiantAge,#txtSpouseAge')
		.bind('blur',function(){
			var val = Math.bound(this.value, 0, 99);
			if ( !val ) val = '';
			this.value = val;
			update_printable(this.id, val);
		})
		.trigger('blur');
	$('#selCaseType')
		.bind('change keyup', function(){
			var val = parseInt(this.value);
			if ( val == 0 )
			{
				$('#txtDateMarriage').attr('disabled','');
				$('#txtDateSeparation').attr('disabled','');
				$('#txtDateDivorce').attr('disabled','disabled');
				$('#trCaseType0').removeClass('dont_print_this');
				$('#trCaseType1').addClass('dont_print_this');
			}
			else
			{
				$('#txtDateMarriage').attr('disabled','disabled');
				$('#txtDateSeparation').attr('disabled','disabled');
				$('#txtDateDivorce').attr('disabled','');
				$('#trCaseType1').removeClass('dont_print_this');
				$('#trCaseType0').addClass('dont_print_this');
			}
		})
		.trigger('change');
	$("#txtDateMarriage,#txtDateSeparation,#txtDateDivorce")
		.bind('blur',function(){
			var _id = '#' + this.id;
			var val = vali_date(_id, '');
			update_printable(this.id, val);
		})
		.trigger('blur');
	_ids = '';
	comma = '';
	for ( loop=1; loop<=6; loop++ )
	{
		_ids += comma +  '#txtOurKidName' + loop + ',#txtOurKidResidesWith' + loop;
		_ids += 		',#txtAffKidName' + loop + ',#txtAffKidResidesWith' + loop;
		comma = ',';
	}
	$(_ids)
		.bind('blur',function(){
			var _id = '#' + this.id;
			var val = blur_text_field(this.id);
			var which = ( _id.indexOf('Our') > 1 ) ? 'Our' : 'Aff';
			check_print_kids_section(which);
		})
		.trigger('blur');
	_ids = '';
	comma = '';
	for ( loop=1; loop<=6; loop++ )
	{
		_ids += comma + '#txtOurKidBirthDate' + loop + ',#txtAffKidBirthDate' + loop;
		comma = ',';
	}
	$(_ids)
		.bind('blur',function(){
			var _id = '#' + this.id;
			var val = vali_date(_id, '');
			update_printable(this.id, val);
		})
		.trigger('blur');
	
	// section 3a
	update_gross_income_total();
	_ids = '';
	comma = '';
	for ( loop=1; loop<=22; loop++ )
	{
		_ids += comma + '#txtGrossIncome' + loop;
		comma = ',';
	}
	$(_ids)
		.bind('focus', function(){
			var _id = '#' + this.id;
			VT_DOLLAR.prepare_from_id(_id);
			var val = ( VT_DOLLAR.stripped == '0.00' ) ? '' : VT_DOLLAR.stripped;
			$(_id).val(val);
		})
		.bind('blur', function(){
			var _id = '#' + this.id;
			VT_DOLLAR.prepare_from_id(_id);
			$(_id).val(VT_DOLLAR.formatted);
			_id = _id._repl('txt','tr');
			if ( VT_DOLLAR.formatted == '$0.00' )
			{
				$(_id).addClass('dont_print_this');
			}
			else
			{
				$(_id).removeClass('dont_print_this');
			}
			update_gross_income_total();
		})
		.trigger('blur');
	
	// section 3b
	$('#txtIncomeEmplBenefits')
		.bind('blur', function(){
			var val = $('#txtIncomeEmplBenefits').val();
			val = $.trim(val);
			val = strip_pipe(val);
			if ( val == '' ) val = 'Affiant receives no benefits other than compensation.';
			$('#txtIncomeEmplBenefits').val(val);
			val = '<p>' + val._repl('\n','</p><p>') + '</p>';
			update_printable(this.id, val);
		})
		.trigger('blur')
		.textlimit('#txtIncomeEmplBenefits_counter',250);
	
	// section 3c
	$('#txtNetIncome')
		.bind('focus', function(){
			VT_DOLLAR.prepare_from_id('#txtNetIncome');
			var val = ( VT_DOLLAR.stripped == '0.00' ) ? '' : VT_DOLLAR.stripped;
			$('#txtNetIncome').val(val);
		})
		.bind('blur', function(){
			VT_DOLLAR.prepare_from_id('#txtNetIncome');
			$('#txtNetIncome').val(VT_DOLLAR.formatted);
			$('#__txtSec2_3c').val(VT_DOLLAR.formatted);
		})
		.trigger('blur');
	$('#selIncomePayPeriod')
		.bind('blur', function(){
			var val = $('#selIncomePayPeriod option:selected').text();
			update_printable(this.id, val);
		})
		.trigger('blur');
	
	// section 4
	asset_popup = new popup();
	asset_popup.which = 0;
	asset_popup.init(
		'fa_asset_popup',
		'generic_bg',
		function(){
			$("#generic_bg")
				.bind('click', function(){
					asset_popup.which = 0;
					asset_popup.devoke();
				});
			var val = $(this._caller_id).val();
			VT_DOLLAR.prepare(val);
			val = ( val == 'unknown' || val == 'undetermined' || VT_DOLLAR.stripped == '0.00' ) ? '' : VT_DOLLAR.stripped;
			$('#txtAssetPopup').val(val).focus().select();
		},
		function(){
			var val, check;
			switch ( asset_popup.which )
			{
				case 1:
					val = 'unknown';
					break;
				case 2:
					val = 'undetermined';
					break;
				default:
					VT_DOLLAR.prepare_from_id('#txtAssetPopup');
					val = VT_DOLLAR.formatted;
					break;
			}
			$("#generic_bg").unbind('click');
			$(this._caller_id).val(val).focus();
			return val;
		},
		-9,
		-14
	);
	$('#txtAssetPopup')
		.bind('keypress', function(e){
			if ( e.keyCode == 13 )
			{
				asset_popup.which = 0;
				asset_popup.devoke();
			}
		});
	for ( loop=1; loop<=45; loop++ )
	{
		the_id = '#txtAssetDescription' + loop;
		$(the_id)
			.bind('blur',function(){
				var _id = '#' + this.id;
				var val = $(_id).val();
				val = $.trim(val);
				val = strip_pipe(val);
				if ( val == '' )
				{
					var loop = parseInt(this.id._repl('txtAssetDescription',''));
					this.value = descriptions.A[loop];
				}
				update_printable(this.id, val);
			})
			.trigger('blur');
	}
	
	// section 5a
	_ids = '';
	comma = '';
	for ( loop=1; loop<=60; loop++ )
	{
		_ids += comma + '#txtExpense' + loop;
		comma = ',';
	}
	$(_ids)
		.bind('focus', function(){
			var _id = '#' + this.id;
			VT_DOLLAR.prepare_from_id(_id);
			var val = ( VT_DOLLAR.stripped == '0.00' ) ? '' : VT_DOLLAR.stripped;
			$(_id).val(val);
		})
		.bind('blur', function(){
			var _id = '#' + this.id;
			VT_DOLLAR.prepare_from_id(_id);
			if ( VT_DOLLAR.value < 0 ) VT_DOLLAR.prepare();
			$(_id).val(VT_DOLLAR.formatted);
			update_expense_total();
		})
		.trigger('blur');
	for ( loop=1; loop<=60; loop++ )
	{
		the_id = '#txtExpenseDescription' + loop;
		$(the_id)
			.bind('blur',function(){
				var _id = '#' + this.id;
				var val = $(_id).val();
				val = $.trim(val);
				val = strip_pipe(val);
				if ( val == '' )
				{
					var loop = parseInt(this.id._repl('txtExpenseDescription',''));
					this.value = descriptions.E[loop];
				}
				update_printable(this.id, val);
			})
			.trigger('blur');
	}
	check_expense_controls();
	
	// section 5b
	_ids = '';
	comma = '';
	for ( loop=1; loop<=20; loop++ )
	{
		_ids += comma + '#txtCreditorBalance' + loop + ',#txtCreditorPayment' + loop;
		comma = ',';
	}
	$(_ids)
		.bind('focus', function(){
			var _id = '#' + this.id;
			VT_DOLLAR.prepare_from_id(_id);
			var val = ( VT_DOLLAR.stripped == '0.00' ) ? '' : VT_DOLLAR.stripped;
			$(_id).val(val);
		})
		.bind('blur', function(){
			var _id = '#' + this.id;
			VT_DOLLAR.prepare_from_id(_id);
			if ( VT_DOLLAR.value < 0 ) VT_DOLLAR.prepare();
			$(_id).val(VT_DOLLAR.formatted);
			update_creditor_total(_id);
		})
		.trigger('blur');
	for ( loop=1; loop<=20; loop++ )
	{
		the_id = '#txtCreditorDescription' + loop;
		$(the_id)
			.bind('blur',function(){
				var _id = '#' + this.id;
				var val = $(_id).val();
				val = $.trim(val);
				val = strip_pipe(val);
				if ( val == '' )
				{
					var loop = parseInt(this.id._repl('txtCreditorDescription',''));
					this.value = descriptions.C[loop];
				}
				update_printable(this.id, val);
			})
			.trigger('blur');
	}
	
	// signature block
	var now, M, M_next, D, Y, Y_next, opt_text;
	now = new Date();
	M = now.getMonth();
	M_next = M + 1;
	if ( M_next == 12 ) M_next = 0;
	D = now.getDateOrdinal();
	Y = now.getFullYear();
	Y_next = M_next ? Y : Y + 1;
	opt_text = 'This ' + D + ' day of ' + Date.monthNames[M] + ', ' + Y + '.';
	$('#selSignatureDate_opt1').text(opt_text);
	opt_text = 'This _______ day of ' + Date.monthNames[M] + ', ' + Y + '.';
	$('#selSignatureDate_opt2').text(opt_text);
	opt_text = 'This _______ day of ' + Date.monthNames[M_next] + ', ' + Y_next + '.';
	$('#selSignatureDate_opt3').text(opt_text);
	$('#selSignatureDate')
		.bind('change keyup',function(){
			var selector = '#' + this.id + ' option:selected';
			var val = $(selector).text();
			update_printable(this.id, val);
		})
		.trigger('change');
	
	// endnotes
	$('#txtEndnotes1,#txtEndnotes2,#txtEndnotes3,#txtEndnotes4,#txtEndnotes5')
		.bind('blur', function(){
			var _id = '#' + this.id;
			var page_num = _id._repl('#txtEndnotes','Endnotes for Page ');
			var val = $(_id).val();
			val = $.trim(val);
			val = strip_pipe(val);
			val = '<p>' + val._repl('\n','</p><p>') + '</p>';
			if ( val != '' ) val = '<p class="b"><span class="u">' + page_num + '</span>:</p> ' + val;
			update_printable(this.id, val);
			check_to_print_endnotes();
			_id = _id._repl('txtE','e');
			$(_id).slideUp('slow');
		});
	$('#txtEndnotes1').textlimit('#endnotes_counter1',500);
	$('#txtEndnotes2').textlimit('#endnotes_counter2',500);
	$('#txtEndnotes3').textlimit('#endnotes_counter3',500);
	$('#txtEndnotes4').textlimit('#endnotes_counter4',500);
	$('#txtEndnotes5').textlimit('#endnotes_counter5',500);
	check_to_print_endnotes();
	
	// worksheet controls
	uploader_popup = new popup();
	uploader_popup.init(
		'uploader_popup',
		'generic_bg',
		function(){
			$("#generic_bg")
				.bind('click', function(){
					uploader_popup.devoke();
				});
			$('#butLoadFilePopup').attr('disabled','disabled');
			$('#fileForUpload').focus();
		},
		function(){
			$("#generic_bg").unbind('click');
			$('#butLoadFilePopup').attr('disabled','');
			return 'Load';
		},
		0,
		-270
	);
	
	$("#please_wait_bg").fadeOut('slow');
	return;
}

function blur_text_field(id)
{
	var options = arguments.length > 1 ? arguments[1] : {};
	var _id = '#' + id;
	var val = $(_id).val();
	val = $.trim(val);
	val = strip_pipe(val);
	var printable = val;
	if ( options.upper != undefined ) printable = printable.toUpperCase();
	update_printable(id, printable);
	return val;
};

function update_printable(id, val)
{
	id = '#__' + id;
	if ( $(id) ) $(id).html(val);
}

function check_print_kids_section(which)
{
	var the_id, check;
	var print_me = false;
	for ( loop=1; loop<=6; loop++ )
	{
		the_id = '#txt' + which + 'KidName' + loop;
		if ( $(the_id).val() != '' ) print_me = true;
		the_id = '#txt' + which + 'KidResidesWith' + loop;
		if ( $(the_id).val() != '' ) print_me = true;
		the_id = '#txt' + which + 'KidBirthDate' + loop;
		if ( $(the_id).val() != '' ) print_me = true;
	}
	if ( print_me )
	{
		the_id = ( which == 'Our' ) ? '#fa_section1c' : '#fa_section1d';
		$(the_id).removeClass('dont_print_this');
		the_id = '#__p' + which + 'KidsEmpty';
		$(the_id).css('display','none');
	}
	else
	{
		the_id = ( which == 'Our' ) ? '#fa_section1c' : '#fa_section1d';
		$(the_id).addClass('dont_print_this');
		the_id = '#__p' + which + 'KidsEmpty';
		$(the_id).css('display','');
	}
}

function check_to_print_endnotes()
{
	var loop, _id, check, need_page = false;
	for ( loop=1; loop<=5; loop++ )
	{
		_id = '#__txtEndnotes' + loop;
		check = $(_id).text();
		$(_id).hide();
		if ( check.length > 0 )
		{
			$(_id).show();
			need_page = true;
		}
	}
	$('#fa_sigblock').removeClass('page_break');
	$('#fa_endnotes').hide();
	if ( need_page )
	{
		$('#fa_sigblock').addClass('page_break');
		$('#fa_endnotes').show();
	}
}

function update_gross_income_total()
{
	var the_id;
	var total = 0;
	for ( var loop=1; loop<=22; loop++ )
	{
		the_id = '#txtGrossIncome' + loop;
		VT_DOLLAR.prepare_from_id(the_id);
		total += VT_DOLLAR.value;
	}
	total = Math.max(total, 0);
	VT_DOLLAR.prepare(total);
	$('#txtGrossIncomeTotal').val(VT_DOLLAR.formatted);
	$('#__txtSec2_3a').val(VT_DOLLAR.formatted);
}

function update_expense_total()
{
	var the_id, idx, grand_total, check;
	var total = [];
	total[1] = 0;
	total[2] = 0;
	total[3] = 0;
	total[4] = 0;
	total[5] = 0;
	idx = 1;
	for ( var loop=1; loop<=60; loop++ )
	{
		if ( (loop == 15) || (loop == 19) || (loop == 31) || (loop == 35) ) idx++;
		the_id = '#txtExpense' + loop;
		VT_DOLLAR.prepare_from_id(the_id);
		total[idx] += VT_DOLLAR.value;
	}
	grand_total = 0;
	for ( loop=1; loop<=5; loop++ )
	{
		the_id = '#txtExpenseSummary' + loop;
		check = Math.max(total[loop], 0);
		VT_DOLLAR.prepare(check);
		$(the_id).val(VT_DOLLAR.formatted);
		grand_total += check;
	}
	check = Math.max(grand_total, 0);
	VT_DOLLAR.prepare(check);
	$('#txtExpenseTotal').val(VT_DOLLAR.formatted);
	$('#__txtSec2_5a').val(VT_DOLLAR.formatted);
	update_monthly_expenses();
}

function update_creditor_total(_id)
{
	var category = ( _id.indexOf('txtCreditorBalance') > -1 ) ? '#txtCreditorBalance' : '#txtCreditorPayment';
	var the_id;
	var total = 0;
	for ( var loop=1; loop<=20; loop++ )
	{
		the_id = category + loop;
		VT_DOLLAR.prepare_from_id(the_id);
		total += VT_DOLLAR.value;
	}
	the_id = category + 'Total';
	check = Math.max(total, 0);
	VT_DOLLAR.prepare(check);
	$(the_id).val(VT_DOLLAR.formatted);
	if ( category == '#txtCreditorPayment' )
	{
		$('#__txtSec2_5b').val(VT_DOLLAR.formatted);
		update_monthly_expenses();
	}
}

function update_monthly_expenses()
{
	VT_DOLLAR.prepare_from_id('#__txtSec2_5a');
	var exp1 = VT_DOLLAR.value;
	VT_DOLLAR.prepare_from_id('#__txtSec2_5b');
	var exp2 = VT_DOLLAR.value;
	var total = exp1 + exp2;
	VT_DOLLAR.prepare(total);
	$('#__txtSec2_5c').val(VT_DOLLAR.formatted);
}

function do_asset_switch()
{
	var alpha, omega;
	if ( arguments.length == 2 )
	{
		alpha = arguments[0];
		omega = arguments[1];
	}
	else
	{
		alpha = $("input[name=radAssetAlpha]:checked").val();
		omega = $("input[name=radAssetOmega]:checked").val();
	}
	if ( !alpha || !omega || (alpha == omega) ) return;
	
	
	var D1 = '#txtAssetDescription' + alpha;
	var M1 = '#txtAssetM' + alpha;
	var H1 = '#txtAssetH' + alpha;
	var W1 = '#txtAssetW' + alpha;
	
	var D2 = '#txtAssetDescription' + omega;
	var M2 = '#txtAssetM' + omega;
	var H2 = '#txtAssetH' + omega;
	var W2 = '#txtAssetW' + omega;
	
	var tmpD = $(D1).val();
	var tmpM = $(M1).val();
	var tmpH = $(H1).val();
	var tmpW = $(W1).val();
	
	$(D1).val($(D2).val());
	$(M1).val($(M2).val());
	$(H1).val($(H2).val());
	$(W1).val($(W2).val());
	
	$(D2).val(tmpD);
	$(M2).val(tmpM);
	$(H2).val(tmpH);
	$(W2).val(tmpW);
}

function check_insert_asset(where)
{
	// gatekeeper check (max num of assets is 45)
	if ( next_asset > 45 )
	{
		safe_alert('The maximum number of assets that can be displayed is 45.  You can either delete another row first, or change the contents of another row, or perhaps add an endnote to this section.');
		return;
	}
	
	// unhide next row
	var _id = '#rowAsset' + next_asset;
	$(_id).css('display','');
	next_asset++;
	
	// shift everything down until "blank" row is in correct position
	var alpha, omega;
	omega = next_asset - 1;
	alpha = omega - 1;
	while ( alpha > where )
	{
		do_asset_switch(alpha, omega);
		omega--;
		alpha--;
	}
	
	// focus on newly added row
	_id = '#txtAssetDescription' + omega;
	$(_id).dblclick();
}

function check_delete_asset(where)
{
	// gatekeeper check (can't delete last row)
	if ( next_asset == 2 )
	{
		safe_alert("You can't delete the last row.");
		return;
	}
	next_asset--;
	
	// shift everything up to current position
	var alpha, omega;
	alpha = where;
	omega = alpha + 1;
	while ( alpha < next_asset )
	{
		do_asset_switch(alpha, omega);
		alpha++;
		omega++;
	}
	
	// reset "last" row
	var _id = '#txtAssetDescription' + next_asset;
	$(_id).val('[other asset]');
	_id = '#txtAssetM' + next_asset;
	$(_id).val('0.00');
	_id = '#txtAssetH' + next_asset;
	$(_id).val('0.00');
	_id = '#txtAssetW' + next_asset;
	$(_id).val('0.00');
	
	// hide "last" row
	_id = '#rowAsset' + next_asset;
	$(_id).css('display','none');
}

function check_insert_expense()
{
	// gatekeeper check (max num of additional expenses is 14 (ids 47 thru 60))
	if ( next_expense > 60 )
	{
		safe_alert('The maximum number of additional expenses that can be displayed is 14.  You can either delete another row first, or change the contents of another row, or perhaps add an endnote to this section.');
		return;
	}
	
	// unhide next row
	var _id = '#rowExpense' + next_expense;
	$(_id).css('display','');
	
	// focus on newly added row
	_id = '#txtExpenseDescription' + next_expense;
	$(_id).dblclick();
	
	// ready for next
	next_expense++;
	check_expense_controls();
}

function check_delete_expense()
{
	// gatekeeper check
	if ( next_expense == 47 )
	{
		safe_alert("You can only delete 'additional' expenses listed in the 'Other Expenses' category.  The other listed items are required by Rule to be listed.");
		return;
	}
	next_expense--;
	
	// reset "last" row
	var _id = '#txtExpenseDescription' + next_expense;
	$(_id).val('[other expense]');
	_id = '#txtExpense' + next_expense;
	$(_id).val('0.00');
	
	// hide "last" row
	_id = '#rowExpense' + next_expense;
	$(_id).css('display','none');
	
	// update totals
	update_expense_total();
	
	// reset for next
	check_expense_controls();
}

function check_expense_controls()
{
	var val = ( next_expense == 47 ) ? 'disabled' : '';
	$('#butExpenseDelete').attr('disabled',val);
	val = ( next_expense > 60 ) ? 'disabled' : '';
	$('#butExpenseInsert').attr('disabled',val);
}

function do_creditor_switch()
{
	var alpha, omega;
	if ( arguments.length == 2 )
	{
		alpha = arguments[0];
		omega = arguments[1];
	}
	else
	{
		alpha = $("input[name=radCreditorAlpha]:checked").val();
		omega = $("input[name=radCreditorOmega]:checked").val();
	}
	if ( !alpha || !omega || (alpha == omega) ) return;
	
	var D1 = '#txtCreditorDescription' + alpha;
	var B1 = '#txtCreditorBalance' + alpha;
	var P1 = '#txtCreditorPayment' + alpha;
	
	var D2 = '#txtCreditorDescription' + omega;
	var B2 = '#txtCreditorBalance' + omega;
	var P2 = '#txtCreditorPayment' + omega;
	
	var tmpD = $(D1).val();
	var tmpB = $(B1).val();
	var tmpP = $(P1).val();
	
	$(D1).val($(D2).val());
	$(B1).val($(B2).val());
	$(P1).val($(P2).val());
	
	$(D2).val(tmpD);
	$(B2).val(tmpB);
	$(P2).val(tmpP);
}

function check_insert_creditor(where)
{
	// gatekeeper check (max num of creditors is 20)
	if ( next_creditor > 20 )
	{
		safe_alert('The maximum number of creditors that can be displayed is 20.  You can either delete another row first, or change the contents of another row, or perhaps add an endnote to this section.');
		return;
	}
	
	// unhide next row
	var _id = '#rowCreditor' + next_creditor;
	$(_id).css('display','');
	next_creditor++;
	
	// shift everything down until "blank" row is in correct position
	var alpha, omega;
	omega = next_creditor - 1;
	alpha = omega - 1;
	while ( alpha > where )
	{
		do_creditor_switch(alpha, omega);
		omega--;
		alpha--;
	}
	
	// focus on newly added row
	_id = '#txtCreditorDescription' + omega;
	$(_id).dblclick();
}

function check_delete_creditor(where)
{
	// gatekeeper check (can't delete last row)
	if ( next_creditor == 2 )
	{
		safe_alert("You can't delete the last row.");
		return;
	}
	next_creditor--;
	
	// shift everything up to current position
	var alpha, omega;
	alpha = where;
	omega = alpha + 1;
	while ( alpha < next_creditor )
	{
		do_creditor_switch(alpha, omega);
		alpha++;
		omega++;
	}
	
	// reset "last" row
	var _id = '#txtCreditorDescription' + next_creditor;
	$(_id).val('[creditor]');
	_id = '#txtCreditorBalance' + next_creditor;
	$(_id).val('0.00');
	_id = '#txtCreditorPayment' + next_creditor;
	$(_id).val('0.00');
	
	// hide "last" row
	_id = '#rowCreditor' + next_creditor;
	$(_id).css('display','none');
	
	// update totals
	update_creditor_total('txtCreditorBalance');
	update_creditor_total('txtCreditorPayment');
}

function save_file()
{
	if ( false == save_file_GATEKEEPER() ) return;
	save_file_SETUP_AJAX();
	ajax.onCompletion = save_file_AJAX_COMPLETE;
	ajax.runAJAX();
}

function save_file_GATEKEEPER()
{
	$('#butSaveFile').attr('disabled', true);
	return true;
}

function save_file_SETUP_AJAX()
{
	ajax = new sack();
	$('.save_me').each(function(){
		var _key = this.id;
		var _val = this.value;
		ajax.setVar(_key, _val);
	});
	ajax.setVar("action", 1);
	ajax.setVar("submission", 'fa');
	ajax.requestFile = "backdoor.php";
}

function save_file_AJAX_COMPLETE()
{
	if ( typeof ajax.response != 'undefined' )
	{
		var work = ajax.response.split('|');
		if ( parseInt(work[0]) != 0 )
		{
			safe_alert(work[1]);
			do_download('download.php?fn='+work[2]+'&type=fa');
		}
	}
	$('#butSaveFile').attr('disabled', false);
}

function load_file()
{
	if ( $('#fileForUpload').val() == '' )
	{
		safe_alert('Please specify a file to upload.');
		return false;
	}
	$('#formFileUploader').submit();
}

function load_file_COMPLETE(status)
{
	uploader_popup.devoke();
	$('#butLoadFilePopup').attr('disabled', false);
	switch ( parseInt(status) )
	{
		case 1:
			safe_alert('The file you uploaded does not appear to be a valid Financial Affidavit file.  If you believe this is an error, please contact PeachForms.com immediately for further assistance.');
			return false;
		case 2:
			safe_alert('There was a problem uploading your file.  Please contact PeachForms.com immediately for further assistance.');
			return false;
		case 3:
			safe_alert('The ability to load data into a PeachForms.com application is only available to current subscribers.  Your subscription has expired.');
			return false;
		case 4:
			safe_alert('Please log in first.');
			return false;
		default:
			ajax = new sack();
			ajax.setVar("action", 2);
			ajax.setVar("submission", 'fa');
			ajax.requestFile = "backdoor.php";
			ajax.onLoading = function(){$("#please_wait_bg").show();};
			ajax.onCompletion = load_file_COMPLETE_PROCESS_AJAX_RESPONSE;
			ajax.runAJAX();
			return true;
	}
}

function load_file_COMPLETE_PROCESS_AJAX_RESPONSE()
{
	if ( (typeof ajax.response == 'undefined') || (ajax.response == 'problem') )
	{
		safe_alert('There was a problem uploading your file.  Please contact PeachForms.com immediately for further assistance.');
		return false;
	}
	
	var values = ajax.response.split('|');
	var work, _id, _val, _trigger;
	for ( var loop=0, loop_ct=values.length; loop<loop_ct; loop++ )
	{
		work = values[loop].split('~');
		_id = '#' + work[0];
		_val = work[1];
		_trigger = work[2] || 'blur';
		if ( $(_id) ) $(_id).val(_val).trigger(_trigger);
	}
	next_asset = setup_worksheet_default_display('a');
	next_expense = setup_worksheet_default_display('e');
	next_creditor = setup_worksheet_default_display('c');
	$("#please_wait_bg").fadeOut('slow');
	return true;
}

function reset_worksheet()
{
	if ( !safe_confirm('Are you sure you want to reset this worksheet?') ) return false;
	safe_alert('Resetting worksheet now (this may take a moment).');
	$('.save_me').each(function(){
		var _id = '#' + this.id;
		switch ( _id )
		{
			case '#selCourt':
			case '#selCaseType':
				$(_id).val(0);
				break;
			case '#selCounty':
				$(_id).val('001');
				break;
			case '#selPlaintiffParty':
				$(_id).val('Plaintiff');
				break;
			case '#selAffiant':
				$(_id).val('txtPlaintiff');
				break;
			case '#selIncomePayPeriod':
				$(_id).val('weekly');
				break;
			default:
				$(_id).val('');
				if ( (_id.indexOf('txtAssetM') > 0) || (_id.indexOf('txtAssetH') > 0) || (_id.indexOf('txtAssetW') > 0) ) $(_id).val('$0.00');
				break;
		}
		if ( _id.indexOf('txt') > 0 ) $(_id).trigger('blur');
		else $(_id).trigger('change');
	});
	next_asset = setup_worksheet_default_display('a');
	next_expense = setup_worksheet_default_display('e');
	next_creditor = setup_worksheet_default_display('c');
	safe_alert('Worksheet has been reset.');
	return true;
}

function setup_worksheet_default_display(which)
{
	switch ( which )
	{
		case 'a':
			_next = 46;
			_loop = 45;
			_loop_ct = 12;
			_which = 'Asset';
			_which2 = 'asset';
			break;
		case 'e':
			_next = 61;
			_loop = 60;
			_loop_ct = 46;
			_which = 'Expense';
			_which2 = 'expense';
			break;
		case 'c':
			_next = 21;
			_loop = 20;
			_loop_ct = 1;
			_which = 'Creditor';
			_which2 = 'creditor';
			break;
	}
	for ( loop=_loop; loop>_loop_ct; loop-- )
	{
		_id = 'txt' + _which + 'Description' + loop;
		row_id = '#row' + _which + loop;
		css = ( $(_id).val() == '[other ' + _which2 + ']' ) ? 'none' : '';
		$(row_id).css('display',css);
		if ( css ) _next--;
	}
	return _next;
}

// end of file
