// divapp.js - works with divappForm.cfm

var displayWindow;
var originalDuesAmt, initialdualDisc, originalPracAAmt, holdforaplus, holdmsg, errormsg, hardmsg, ethicsOK, ethicsclickcount, glchildWindow, curcolhdrdesc, newcountryCode, displayasconf, addrdisplayasconf, isitlic;
var ddcount=0.0, ddname, ddidx;
// there is one entry in here per division selected on the form
var divlineidxarray = [], 		divlinecodearray = [];
var divlinepublistarray = [],	divlinepubcheckedarray = [];
var linetotalarray = [],		publdollarstrarray = [];
var divlinedescarray = [],		divyearsindivarray = [],  divlinembtypearray = [];
var divselectedpubarray = [],  	divlineotherpubarray = [];

var alldivstring, upperdivstring, isduespaid, apamembtype, apadivlist, apadivlistlen, apalevellist, apalevelarray = [], membyearlist, membyeararray = [], origdivmembtype, divmembtype, isfirstyear = 0, thissectionfeestr, allblanks, firstdivlist, prevpddivlist, upperdivlist, curdivlist;
var sectionidx = 0.0, rateidx = 0.0;
var linetotal,newsectioncode, newsectiondesc, newpublcodelist, publdollarstr, glDivTotDollars, grandbase;
// processingupperdivlist = 1 if we are processing the upperdivlist, otherwise 0.
var processingupperdivlist, divmembcdlist;
// 40 shows hasn't been imported from form
var displaydivdropdown = 40;

var pattern = new RegExp();
// 0 = no debug alerts, 1 = alerts
var isdebug = 0;

function dalrt(s) {
	if(isdebug === 1) {
		alert(s);
	}
}

function chgcountryCode(argdisplayasconf) {
	// executes when a person picks a new countryCode
	var newcountryCode;

	if (argdisplayasconf === 0) {
		newcountryCode = document.getElementById('countryCode').options[document.getElementById('countryCode').selectedIndex].value;
		// set the value of the select
		document.getElementById('countryCode').value = newcountryCode;
	}
	else {
		newcountryCode = document.getElementById('countryCode').value;
	}
	if (newcountryCode.substr(0, 3) == 'USA'){
		// USA
		document.getElementById('state').style.display = '';
		document.getElementById('canProvince').style.display = 'none';
		document.getElementById('province').style.display = 'none';
		document.getElementById('cszstate').style.display='';
		document.getElementById('cszprovince').style.display='none';


	}
	else if (newcountryCode.substr(0, 3) == 'CAN'){
		// Canada
		document.getElementById('state').style.display = 'none';
		document.getElementById('canProvince').style.display = '';
		document.getElementById('province').style.display = 'none';
		document.getElementById('cszstate').style.display='none';
		document.getElementById('cszprovince').style.display='';

	}
	else {
		// foreign
		document.getElementById('state').style.display = 'none';
		document.getElementById('canProvince').style.display = 'none';
		document.getElementById('province').style.display = '';
		document.getElementById('cszstate').style.display='none';
		document.getElementById('cszprovince').style.display='';

	}
}

function initializeRegistration() {
	holdmsg = document.getElementById('holdmsg').value;
	errormsg = document.getElementById('errormsg').value;
	addrdisplayasconf = document.getElementById('addrdisplayasconf').value;
	if (addrdisplayasconf == 1){
			return;
	}

	// go to focus field, if set
	var bkm = document.getElementById('bkm').value;
	if (bkm !== '') {
		alert(errormsg);
		document.getElementById(bkm).focus();
	}
}

function initializeAddress() {

	errormsg = document.getElementById('errormsg').value;
	addrdisplayasconf = document.getElementById('addrdisplayasconf').value;
	if (addrdisplayasconf == 1){
			return;
	}

	chgcountryCode(addrdisplayasconf);

	// go to focus field, if set
	var bkm = document.getElementById('bkm').value;
	if (bkm !== '') {
		alert(errormsg);
		document.getElementById(bkm).focus();
	}
}

function getFeeFromSession(ddind) {
	// go to the right record in the qrates wddx structure. set rateidx, division rate
	var retvar = '', i = 0, qnrows, sectioncodepar;

	sectioncodepar = divlinecodearray[ddind];
	qnrows = 1 * qrates.getRowCount();
	dalrt('getFeeFromSession, sectioncodepar ' + sectioncodepar + ' qnrows ' + qnrows);
	for (i = 0; i < qnrows; i++) {
		if (qrates.getField(i,"sectioncode") == sectioncodepar) {
			// needs to account for multiple lines for a division
			// find the first record in the rates table for the sectioncodepar division
			dalrt ('found sectioncodepar ' + sectioncodepar + ' rateidx ' + i + ' isfirstyear ' + isfirstyear);
			rateidx = i;

			dalrt('rateidx ' + rateidx + ' isfirstyear ' + isfirstyear);

			if (isfirstyear != 1  && qrates.getField(rateidx, "yearsindiv") == '1') {
				// we are NOT using the first year rate in this case, so skip it, and get to the normal rate
				dalrt('incrementing rateidx ' + rateidx);
				rateidx = rateidx + 1;
			}
			// apply rules for "join as"
			divmembtype = origdivmembtype;

			dalrt('divmembtype.. ' + divmembtype);
			// should get null if there is no rate

			retvar = qrates.getField(rateidx, divmembtype);
			dalrt('retvar (rate) ' + retvar);
			if(retvar === null) {
				// this is a division that you cannot join directly. Put in a 0 rate go things continue
				retvar = 0;
			}
			if(1 * retvar == 1 * (-2)) {
				// -2 means "join as professional affiliate"
				divmembtype = 'PROFAFFILIATE';
				retvar = qrates.getField(rateidx,divmembtype);
			}
			retvar = appendDecimal(parseFloat(Math.round(retvar * 100)/100));
			dalrt('getFeeFromSession returning ' + retvar);
			return retvar;
		}
	}
}

function enableSubmitReset() {

	ethicsOK = document.getElementById("idethicsOK").checked;
	// no hold from A+
	// this is checking the yes/no radio button on the ethics statement
	if (ethicsOK) {
		//ethicsOK true
		document.getElementById('idSubmit').disabled=false;
	}
	else {
		//ethicsOK not true
		document.getElementById('idSubmit').disabled=true;
	}
}

function openChild(file,window) {
	var childWindow = open(file,window,'resizable=yes,width=800,height=400,left=0,top=0,scrollbars=yes');
	childWindow.focus();
    if (childWindow.opener === null) {childWindow.opener = self;}
    // set the global handle
    glchildWindow = childWindow;
	return childWindow;
}


function doEthics() {
	// set javascript variable, from the value the user clicked in the form
	ethicsOK = document.getElementById("idethicsOK").checked;
	if (ethicsOK) {
		//ethicsOK true
		ethicsclickcount = ethicsclickcount + 1;
		if (ethicsclickcount > 1) {
			// open a window with the ethics statement
			openChild('../interest/ethics1.cfm','duesUseHelpWindow');
			// change the radio button back to "No"
			// document.getElementById("idethicsNOTOK").checked = 1;
		}
	}
	else {
		//ethicsOK not true   ... change to no-op
		ethicsclickcount = ethicsclickcount + 1;
	}

	enableSubmitReset();
}

function dispHold() {
	alert(holdmsg);
}


function openAfflHelp(formcd,ConstitID,bookmark) {

	var myfile, mywindow, childWindow;
	// building a url that contains the constitid and name (which might contain an apostrophe)
	//.replace(/''/g,'\|') and .replace(/\|/g,'')
	myfile = formcd + 'help.cfm?ConstitID=' + ConstitID + '&membname=' + document.getElementById('membname').value + '&membernum=' + document.getElementById('ConstitID').value + '#' + bookmark;

	mywindow='duesUseHelpWindow';
	// childWindow = open(myfile,mywindow,'resizable=yes,width=800,height=400,left=0,top=0,scrollbars=yes');
	childWindow = open(myfile,mywindow,'resizable=yes,left=0,top=0,width=800,height=550,scrollbars=yes');
	childWindow.focus();
    if (childWindow.opener === null) {childWindow.opener = self;}
    // set the global handle
    glchildWindow = childWindow;
	// return childWindow;
	return;
}


 function openPubChild(file,window) {
	var childWindow;

	// note: this is NOT full screen on a 1024 x 768 monitor. Perhaps we could sniff this
	childWindow = open(file,window,'resizable=yes,width=780,height=550,left=0,top=0,scrollbars=yes,menubar=yes,toolbar=yes');
	childWindow.focus();
    if (childWindow.opener === null) {childWindow.opener = self;}
    // set the global handle
    glchildWindow = childWindow;
    // does NOT return the window handle, so [object] does not appear in the main subscription form
	return;
}

function openLongChild(file,window) {
	// note: this is NOT full screen on a 1024 x 768 monitor. Perhaps we could sniff this
	var childWindow = open(file,window,'resizable=yes,width=800,height=550,left=0,top=0,scrollbars=yes,menubar=yes');
	childWindow.focus();
    if (childWindow.opener === null) {childWindow.opener = self;}
    // set the global handle
    glchildWindow = childWindow;
	return childWindow;
}

function openLongChildNH(file,window) {
	// note: this is NOT full screen on a 1024 x 768 monitor. Perhaps we could sniff this
	var childWindow = open(file,window,'resizable=yes,width=800,height=550,left=0,top=0,scrollbars=yes,menubar=yes');
	childWindow.focus();
    if (childWindow.opener === null) {childWindow.opener = self;}
    // set the global handle
    glchildWindow = childWindow;
    // does NOT return the window handle, so [object] does not appear in the main subscription form
	return;
}
function openLongChildNHOffset(file,window) {
	// note: this is NOT full screen on a 1024 x 768 monitor. Perhaps we could sniff this
	var childWindow = open(file,window,'resizable=yes,width=800,height=550,left=10,top=10,scrollbars=yes,menubar=yes');
	childWindow.focus();
    if (childWindow.opener === null) {childWindow.opener = self;}
    // set the global handle
    glchildWindow = childWindow;
    // does NOT return the window handle, so [object] does not appear in the main subscription form
	return;
}

function noNull(s) {
	if (s === null || s === '' ) {
		return ' ';
	} else {
		return s;
	}
}


function chgToHidden() {
	var locidx;
	// pipe-delimited lists ! Maps all the JS arrays to hidden variables
	// NO ZERO-LENGTH STRINGS... substitute a single blank, including at the end
	dalrt('Into chgToHidden, ddcount ' + ddcount + ' divlinecodearray[locidx] ' + divlinecodearray[0] );

	if (ddcount === 0) {
		document.getElementById('formdivlist').value 		=  ' ';
		document.getElementById('formidxlist').value 		=  ' ';
		document.getElementById('formdollarlist').value 	=  ' ';
		document.getElementById('formpubllist').value 		=  ' ';
		document.getElementById('formpubldollarlist').value =  ' ';
		document.getElementById('formpublchecklist').value  =  ' ';
		document.getElementById('formdesclist').value  		=  ' ';
		document.getElementById('formyearsindivlist').value  		=  ' ';
		document.getElementById('formmbtypelist').value  	=  ' ';
		document.getElementById('formselectedpublist').value  	=  ' ';
		document.getElementById('formotherpublist').value  	=  ' ';
	} else {
		for(locidx = 0; locidx < ddcount; locidx++) {
			dalrt('chgToHidden locidx ' + locidx);
			if (locidx > 0) {
				document.getElementById('formdivlist').value = document.getElementById('formdivlist').value + '|' + noNull(divlinecodearray[locidx]);
				document.getElementById('formidxlist').value = document.getElementById('formidxlist').value + '|' + noNull(divlineidxarray[locidx]);
				document.getElementById('formdollarlist').value = document.getElementById('formdollarlist').value + '|' + noNull(linetotalarray[locidx]);
				document.getElementById('formpubllist').value = document.getElementById('formpubllist').value + '|' + noNull(divlinepublistarray[locidx]);
				document.getElementById('formpubldollarlist').value = document.getElementById('formpubldollarlist').value + '|' + noNull(publdollarstrarray[locidx]);
				document.getElementById('formpublchecklist').value = document.getElementById('formpublchecklist').value + '|' + noNull(divlinepubcheckedarray[locidx]);
				document.getElementById('formdesclist').value  =  document.getElementById('formdesclist').value  + '|' + noNull(divlinedescarray[locidx]);
				document.getElementById('formyearsindivlist').value  =  document.getElementById('formyearsindivlist').value  + '|' + noNull(divyearsindivarray[locidx]);
				document.getElementById('formmbtypelist').value  =  document.getElementById('formmbtypelist').value  + '|' + noNull(divlinembtypearray[locidx]);
				document.getElementById('formselectedpublist').value  =  document.getElementById('formselectedpublist').value  + '|' + noNull(divselectedpubarray[locidx]);
				document.getElementById('formotherpublist').value  = document.getElementById('formotherpublist').value + '|' +  noNull(divlineotherpubarray[locidx]);

			} else {
				document.getElementById('formdivlist').value 		=  noNull(divlinecodearray[locidx]);
				document.getElementById('formidxlist').value 		=  noNull(divlineidxarray[locidx]);
				document.getElementById('formdollarlist').value 	=  noNull(linetotalarray[locidx]);
				document.getElementById('formpubllist').value 		=  noNull(divlinepublistarray[locidx]);
				document.getElementById('formpubldollarlist').value =  noNull(publdollarstrarray[locidx]);
				document.getElementById('formpublchecklist').value  =  noNull(divlinepubcheckedarray[locidx]);
				document.getElementById('formdesclist').value  		=  noNull(divlinedescarray[locidx]);
				document.getElementById('formyearsindivlist').value  =  noNull(divyearsindivarray[locidx]);
				document.getElementById('formmbtypelist').value  	=  noNull(divlinembtypearray[locidx]);
				document.getElementById('formselectedpublist').value  =  noNull(divselectedpubarray[locidx]);
				document.getElementById('formotherpublist').value  =  noNull(divlineotherpubarray[locidx]);
			}
		}
	}

	document.getElementById('ddcount').value 			=  ddcount;
	// this messes up the appearance of the form. Recalculate alldivstring when it is needed
	document.getElementById('alldivstring').value 		=  alldivstring;
	dalrt('leaving chgtoHidden');
}

function addFromHidden() {
	var locidx, lp1;
	// pipe-delimited lists !
	// Maps all the important hidden variables TO JS, for a restart from CC
	// assumes all the hidden variables (including journal selections) are set from before
	glDivTotDollars = 0;
	if (ddcount > 0) {
		for(locidx = 0; locidx < ddcount; locidx++) {
			// ListGetAt starts at element 1
			lp1 = locidx + 1;
			divlinecodearray[locidx] 		= ListGetAt(document.getElementById('formdivlist').value, lp1, '|');
			divlineidxarray[locidx] 		= ListGetAt(document.getElementById('formidxlist').value, lp1, '|');
			dalrt('divlinecodearray ' + divlinecodearray[locidx]);
			linetotalarray[locidx] 			= ListGetAt(document.getElementById('formdollarlist').value, lp1, '|');
			divlinepublistarray[locidx] 	= ListGetAt(document.getElementById('formpubllist').value, lp1, '|');
			publdollarstrarray[locidx] 		= ListGetAt(document.getElementById('formpubldollarlist').value, lp1, '|');
			divlinepubcheckedarray[locidx] 	= ListGetAt(document.getElementById('formpublchecklist').value, lp1, '|');
			divlinedescarray[locidx] 		= ListGetAt(document.getElementById('formdesclist').value, lp1, '|');
			divyearsindivarray[locidx] 		= ListGetAt(document.getElementById('formyearsindivlist').value, lp1, '|');
			divlinembtypearray[locidx] 		= ListGetAt(document.getElementById('formmbtypelist').value, lp1, '|');
			divselectedpubarray[locidx] 	= ListGetAt(document.getElementById('formselectedpublist').value, lp1, '|');
			divlineotherpubarray[locidx] 	= ListGetAt(document.getElementById('formotherpublist').value, lp1, '|');
			// skip divisions that are already paid
			if (processingupperdivlist === 0) {
				glDivTotDollars = glDivTotDollars + 1 * linetotalarray[locidx];
			}
		}
		// this value is meaningless.  Recalculate whenever it is needed??? 		alldivstring = '';

		alldivstring	= RTrim(document.getElementById('alldivstring').value);
		makeDollarFromVar('GrandTotal', glDivTotDollars);

	} else {
		alldivstring = '';
	}
	dalrt('addFromHidden alldivstring ' + alldivstring);
}

function viewDivs() {

	// upperdivstring is for the divisions displayed at the "inactive" part of the form, alldivstring is for the rest (including firstdivlist)
	// 735 is important to agree with the width of the surrounding table, set in HTML
	var strfirst='<TABLE class="aparequest" width="735">';

	var strupperhdr='<TR><TD CLASS="reqlableftinfo" width="35%"><i>Previous or Current Division Memberships</I></TD><TD CLASS="reqlableftinfo" width="35%">&nbsp;</TD><TD CLASS="reqlableftinfo" width="10%">&nbsp;</TD><TD CLASS="reqlabrightinfo" width="10%">&nbsp;</TD><TD CLASS="reqlableftinfo" width="10%">&nbsp;</TD></TR>';

	var strhdr='<TR><TD CLASS="reqlableftinfo" width="35%"><i>Renew or Add These Divisions</I></TD><TD CLASS="reqlableftinfo" width="35%">&nbsp;</TD><TD CLASS="reqlableftinfo" width="10%">&nbsp;</TD><TD CLASS="reqlabrightinfo" width="10%">&nbsp;</TD><TD CLASS="reqlableftinfo" width="10%">&nbsp;</TD></TR>';

	var strlast='</TABLE>';

	// either of the strings can be blank
	if (RTrim(upperdivstring) !== '') {
		// there is a upperdivstring
		if (RTrim(alldivstring) !== '') {
			// there is an alldivstring
			document.getElementById('alldivs').innerHTML = strfirst + strupperhdr + upperdivstring + strhdr + alldivstring + strlast;
		}
		else {
			// there is NOT an alldivstring
			document.getElementById('alldivs').innerHTML = strfirst + strupperhdr + upperdivstring + strlast;
		}

	} else {
		// there is NOT a upperdivstring
		if (RTrim(alldivstring) !== '') {
			// there is an alldivstring
			document.getElementById('alldivs').innerHTML = strfirst + strhdr + alldivstring + strlast;
		}
		else {
			// there is NOT an alldivstring
			document.getElementById('alldivs').innerHTML = '';
		}
	}

	// initialize the section dropdown
	document.getElementById('section').selectedIndex = 0;
	newsectioncode 		= '';

}

// comment out useful function
//function myKeyPressed(e){
//	e = e || window.event;
//	var unicode=e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
//	if (unicode == 13){
//		document.formname.submit();
//	}
//}
// document.onkeypress = myKeyPressed;

// * * * * * * INITIALIZATIONS

function initializeLogin() {
	dalrt('initializeLogin');
	document.getElementById('loginAction').disabled=false;
	document.getElementById('apauserid').focus();
	// turn on processing the enter key
}

function initializeConfirm() {
	// alert('initializeConfirm');
	// set up the grand total ??

	//
	if (parseInt(document.getElementById('ddcount').value) == 0) {
		alert('You have joined no divisions');
		// disable the submission button, so they cant submit a $0 order without any subscription
		document.getElementById('btnPayButton').disabled = true;
	}
}

function initializeDivForm() {

	// for divappEDIT1
	isdebug = 0;

	// get some of the "hidden" values
	holdmsg 			= document.getElementById('holdmsg').value;
	errormsg 			= document.getElementById('errormsg').value;
	apamembtype 		= document.getElementById('apamembtype').value;
	dalrt('apamembtype ' + apamembtype);

	if (displaydivdropdown == 40) {
		// this is the first time JS is trying to figure out what to do
		// this comes from the original form, as modified by JS, perhaps
		displaydivdropdown 	= document.getElementById('displaydivdropdown').value;

		if (displaydivdropdown == 1) {
			if (document.getElementById('origdivmembtypedrop').selectedIndex == 0) {
				origdivmembtype = 'PROFAFFILIATE';
				divmembtype 	= 'PROFAFFILIATE';
			}
			else {
				// dropdown is already initialized. Read it
				origdivmembtype = document.getElementById('origdivmembtype').value;
				divmembtype 	= document.getElementById('divmembtype').value;
			}
		}
		else {
			// dropdown is not being displayed
			origdivmembtype = document.getElementById('origdivmembtype').value;
			divmembtype 	= document.getElementById('divmembtype').value;
		}
	}

	divmembcdlist 	= document.getElementById('divmembcdlist').value;
	// this is 1 if the person has not already selected a divmembtype
	dalrt('displaydivdropdown ' + displaydivdropdown);
	dalrt('origdivmembtype ' + origdivmembtype);
	dalrt('divmembtype ' + divmembtype);
	dalrt('divmembcdlist ' + divmembcdlist);

	// set the dropdown for origdivmembtype, if it is displayed
	if (displaydivdropdown == 1 && document.getElementById('origdivmembtypedrop') != null) {
		// first element is 1
		var divxx = ListFindNoCase(divmembcdlist, origdivmembtype, '|');
		// first item in select is -- Please Select --
		document.getElementById('origdivmembtypedrop').selectedIndex = divxx;
	}

	apadivlist 			= document.getElementById('apadivlist').value;
	dalrt('apadivlist ' + apadivlist);
	apadivlistlen 		= 0;
	apalevellist 		= document.getElementById('apalevellist').value;
	dalrt('apalevellist ' + apalevellist);
	membyearlist 		= document.getElementById('membyearlist').value;
	dalrt('membyearlist ' + membyearlist);
	if(apalevellist !== '') {
		// calculate the length of the list, for use in displaying from JS.  The apaLEVELlist determines how many come from dues
		apalevelarray = apalevellist.split('|');
		apadivlistlen = apalevelarray.length;
	}
	if(membyearlist !== '') {
		membyeararray = membyearlist.split('|');
		membyearlistlen = membyeararray.length;
	}
	isduespaid 		= document.getElementById('isduespaid').value * 1;
	dalrt('isduespaid ' + isduespaid);
	firstdivlist 	= document.getElementById('firstdivlist').value;
	dalrt('firstdivlist ' + firstdivlist);
	prevpddivlist 	= document.getElementById('prevpddivlist').value;
	dalrt('prevpddivlist ' + prevpddivlist);
	curdivlist 	= document.getElementById('curdivlist').value;
	dalrt('curdivlist ' + curdivlist);
	upperdivlist 	= document.getElementById('upperdivlist').value;
	dalrt('upperdivlist ' + upperdivlist);
	publcdlist 		= document.getElementById('publcdlist').value;
	publdesclist 	= document.getElementById('publdesclist').value;


	// grandbase is the amount from dues-type divisions. It is 0 for this form
	grandbase = 0;

	// start with no added divisions to display
	alldivstring = '';
	upperdivstring = '';
	allblanks = '                   ';
	makeDollarFromVar('GrandTotal', 0);

	processingupperdivlist = 0;
	if (RTrim(upperdivlist) != '') {
		processingupperdivlist = 1;
		dalrt ('calling buildHTMLFromDivList(upperdivlist)');
		buildHTMLFromDivList('upperdivlist');
	}


	// PERMANENT save (for this use of the form) of upperdivstring as display of upper part of the form
	// ViewDivs will display it
	upperdivstring = alldivstring;

	// set up alldivstring and the others for reuse for the rest of this form
	alldivstring = '';
	for (locidx = 0; locidx < ddcount; locidx++) {
		clearArrays(locidx);
	}

	displayasconf = document.getElementById('displayasconf').value;
	ddcount = 1 * document.getElementById('ddcount').value;
	processingupperdivlist = 0;

	if (ddcount > 0) {
		// transfer the arrays from the hidden form fields to JS
		// this is for coming back from Bryan's form
		addFromHidden();
	}


	if (RTrim(firstdivlist) != '') {
		dalrt ('calling buildHTMLFromDivList(firstdivlist)');
		buildHTMLFromDivList('firstdivlist');
	}

	// display the HTML for firstdivlist divisions on the form
	viewDivs();

	// 02/10/09 - CLEAR the firstdivlist, since we have used it. This makes things work ok if someone deletes something in the middle of the firstdivlist in a subsequent run
	document.getElementById('firstdivlist').value = '';

	if (displayasconf == 1){
			return;
	}

	// initialize the section dropdown to --Please Select ---
	document.getElementById('section').selectedIndex = 0;
	newsectioncode 		= '';

	// initialize the origdivmembtypedrop dropdown
	// if(document.getElementById('origdivmembtypedrop').selectedIndex  !== undefined) {
	// 	document.getElementById('origdivmembtypedrop').selectedIndex = 0;
	// }

	// go to focus field, if set
	var bkm = document.getElementById('bkm').value;
	if (bkm !== '') {
		alert(errormsg);
		document.getElementById(bkm).focus();
	}
	dalrt('leaving initializeDivForm');
}

function chkParentDiv () {
	var retvar, parentdiv, locidx;
	var parentpattern = new RegExp();

	retvar = 'N';
 	dalrt('chkParentDiv rateidx ' + rateidx + ' parentmembershiprequired ' + qrates.getField(rateidx,"parentmembershiprequired"));
	if (qrates.getField(rateidx,"parentmembershiprequired") == 'Y') {

		parentdiv= qrates.getField(rateidx,"divcode");
		dalrt('searching for match for parent ' + parentdiv);
		parentpattern = parentdiv;
		// comment out old way if(apadivlist.search(parentpattern) >= 0 ) {
		if(ListFindNoCase(apadivlist, parentpattern, '|') >= 1 && isduespaid === 1) {
			// person has joined the required parent
			return 'Y';
		}

		// search the array instead of the hidden variable, to pick up divisions he has just added
		for (locidx = 0; locidx < ddcount; locidx++) {
			if (parentdiv == divlinecodearray[locidx]) {
				return 'Y';
			}
		}
		alert ('To join this section, you must be in division ' + parentdiv + '. Nothing done');
		return 'N';
	} else {
		return 'Y';
	}
}

function getPublDesc (publcode) {
	var publind,retvar;
	publind = ListFindNoCase(publcdlist, publcode, '|');
	retvar = '';
	if (publind > 0) {
		retvar = ListGetAt(publdesclist, publind, '|');
	}
	return retvar;
}

function calcOtherPubDesc(ddind) {
	// returns the description if it is an apa pub, otherwise returns the description that is in the SQL table itself
	// divlineotherpubarray[ddidx]

	var retvar, i;
	retvar = calcOtherPubDescImpl(divlineotherpubarray[ddind - 1]);
	return retvar;
}

function calcOtherPubDescImpl(ppub) {
	// returns the description if it is an apa pub, otherwise returns the description that is in the SQL table itself

	var retvar, i;
	retvar = ppub;
	if (retvar === null) {
		retvar = '';
	}
	// if this is a code for an APA publication, look up the description
	if (retvar !== '' && retvar.length === 3) {
		// match the publication code to get the description
		retvar = getPublDesc(retvar);
	}
	if (retvar !== '') {
		retvar = 'incl. ' +  retvar;
	}
	dalrt('calcOtherPubDescImpl returning ' + retvar);
	return retvar;
}

function addToInner(ix, psectioncode, psectiondesc, divmembtype, publstr, dispdollarstr) {
	// this routine is called ONLY by adjustHTML
	// adds the text for this line to the form
	var firstchkboxstr;
	var publdispstr1, publdispstr2;
	var paidstr;
	var displaymembtype, displaydollarormembtype;
	var isdivonform;
	isdebug = 0;

	// this is the publication string with the checkboxes
	publdispstr1 = publstr;
	// This is a description of an "other pub"
	publdispstr2 = calcOtherPubDesc(ix);

	if (publdispstr1 !== '' && publdispstr2 !== '') {
		publdispstr2 = '<BR>' + publdispstr2;
	}

	if (isfirstyear == 1) {
		firstchkboxstr = '<BR>First year';
	} else {
		firstchkboxstr = '';
	}

	// set up for printing a * if this division cannot be updated from this form
	isdivonform = 0;
	paidstr = ' *';

	for (var kk = 0;  kk < sectionlist.length; kk++) {
		if (sectionlist[kk][0] == psectioncode) {
			paidstr = '';
			isdivonform = 1;
			break;
		}
	}

	if (isdivonform == 0) {
		// must get the name and link for this division from alldivlist
		for (kk = 0;  kk < alldivlist.length; kk++) {
			if (alldivlist[kk][0] == psectioncode) {
				psectiondesc = alldivlist[kk][2];
				break;
			}
		}
	}

	if (processingupperdivlist === 1) {

		// display the level appropriate to the division membership type from dues, if this appears on apadivlist (the divisions from dues)
		kk = ListFindNoCase(apadivlist, psectioncode, '|');
		if (kk >= 1 ) {
			// there is a type in dues
			displaymembtype = apalevelarray[kk - 1];
			displaymembyear = membyeararray[kk - 1];
//			displaymembyear = 2010;
		} else {
			// there is NOT a type in dues.  Use the way this person is running THIS form
			displaymembtype = divmembtype;
		}

		// for PAID, show "PAID". For unpaid, show UNPAID
    	  	dalrt ('debug curdivlist ' + curdivlist);
    	  	dalrt ('debug psectioncode ' + psectioncode);

		if (ListFindNoCase(prevpddivlist, psectioncode, '|') >= 1 ) {
			// division is paid
			paidstr = '<B>PAID' + paidstr + '</B>';
			// do NOT display dollars for paid divisions
			displaydollarormembtype = displaymembtype;
		} else {
			// division is NOT PAID
			paidstr = '<B>UNPAID' + paidstr + '</B>';
			displaydollarormembtype = dispdollarstr;
		}
		displaydollarormembtype = displaymembyear;

	} else {

		// we are not processing upperdivlist.  These are NOT paid
		paidstr = '<A HREF="Javascript:delSection(' + ix + ');">Delete</A>';
		displaymembtype = divmembtype;
		displaydollarormembtype = dispdollarstr;
	}
	if (displaymembtype === undefined) {
			displaymembtype = divmembtype;
    	  	dalrt ('debug 1 displaymembtype ' + displaymembtype);
	}
	alldivstring = alldivstring + '<TR><TD CLASS="reqlableft">' + psectioncode + '. ' +  psectiondesc + '</TD><TD CLASS="reqlableft">' + publdispstr1 + publdispstr2 + '</TD><TD CLASS="reqlableft">' + displaymembtype + firstchkboxstr + '</TD><TD CLASS="reqinprightcentered">' + displaydollarormembtype + '</TD><TD CLASS="reqlableft">&nbsp;&nbsp;' + paidstr + '</TD></TR>';
	dalrt ('leaving addToInner, alldivstring ' + alldivstring);
}

function getChecksandPubl(locidx) {
	var retvar, i, kk, ix, publdesc, chkstr, isitchecked, chkid, picktype,thispubl,clickstr,newpublcodex,pickonepar;
	var pattern = new RegExp();
	var parr = [];
	var parr2 = [];
	var disabledstr;
	var isincludeonly;
	isdebug = 0;

	// ddidx is global, pointing to line in the division display, where first line is [0]
	ix = locidx + 1;
	disabledstr = '';
	if (processingupperdivlist === 1) {
		disabledstr = ' DISABLED';
	}
	retvar = '';
	publdollarstr = 0;
	picktype = '';
	newpublcodelist = divlinepublistarray[locidx];

	// if publcodeXML is NULL, there is nothing to do
	if (newpublcodelist === '' || newpublcodelist === null) {
		return retvar;
	}

	dalrt('newpublcodelist in getChecksandPubl ' + newpublcodelist);
	dalrt('divmembtype in getChecksandPubl ' + divmembtype);

	// if the current divmembtype is NOT on the list in (publcodeXML), then any journal in publcodeXML is "incl. "
	// PATTERN IS ALL CAPS
	pattern = divmembtype;
	isincludeonly = 0;
	if (newpublcodelist.search(pattern) == -1) {
		isincludeonly = 1;
	}

	// for section 5, this is '1,1', '1,0' etc. Otherwise '1' or '0'. Section 5 is never isincludeonly
	isitchecked = divlinepubcheckedarray[ix - 1];
	// defensive in case coming from SA to member.
	// if (divmembtype != 'STUDENTAFFILIATE' && isitchecked == '1,1') {
	//		// can only order one publication in div 5 if not a SA. pick MET
	//		isitchecked = '1,0';
	//	divlinepubcheckedarray[ix - 1] = isitchecked;
	//	divselectedpubarray[ix - 1] = calcSelectedPub(ix - 1);
		// must update the hidden fields, in case we leave the JS now
	//	chgToHidden();
	//}
	dalrt('isitchecked in getChecksandPubl ' + isitchecked);

	dalrt ('getChecksandPubl newpublcodelist ' + newpublcodelist + ' newsectioncode ' + newsectioncode + ' isitchecked ' + isitchecked + ' isincludeonly ' + isincludeonly);

	if (newsectioncode == '05') {

		// newpublcodelist is like PAS,0,MEMBER,LIFESTATUS,PROFAFFILIATE|PAS,21,STUDENTAFFILIATE|MET,0,MEMBER,LIFESTATUS,PROFAFFILIATE|MET,21,STUDENTAFFILIATE

        // changed this on 06/11/2010 so that picktype is pickboth for all member types
		// picktype = 'pickone';
		// if (divmembtype == 'STUDENTAFFILIATE') {
			picktype = 'pickboth';

		// must LOOP over the multiple publication lists
		parr2 = newpublcodelist.split(';');
		for (kk = 0; kk < parr2.length; kk++) {
			// don not do anything unless this string is for this member type
			if (parr2[kk].search(pattern) == -1) {
				continue;
			}
			parr = parr2[kk].split(',');
dalrt('parr.length ' + parr.length);
			publdesc = '';
			chkstr = '';
			thispubl = parr[0];
			if (thispubl == 'MET' && (isitchecked == '1,1' || isitchecked == '1,0')) {
				chkstr = ' CHECKED';
			}
			else if (thispubl == 'PAS' && (isitchecked == '1,1' || isitchecked == '0,1')) {
				chkstr = ' CHECKED';
			}

			// the dollars for this line depend on whether the publication is checked
			if (chkstr == ' CHECKED') {
				publdollarstr = 1 * publdollarstr + 1 * parr[1];
			}
dalrt ('in getChecksandPubl publdollarstr ' + publdollarstr + ' thispubl ' + thispubl);
			// match the publication code to get the description
			publdesc = getPublDesc(thispubl);
dalrt ('publdesc ' + publdesc);

			chkid = 'pchk' + thispubl + ix;
			dalrt('div 5 thispubl ' + thispubl + ' chkid ' + chkid + ' publdollarstr ' + publdollarstr);
			pickonepar = '\'' + picktype + '\'';
			// This is a publication on its own line, with a named checkbox, and an indication whether it is checked
			clickstr = ' onClick="chgPubChk(\'';
			clickstr = clickstr + chkid + '\',' + ix + ',' + pickonepar + ')"';
			retvar = retvar + ' <BR><INPUT TYPE="checkbox" VALUE="1" ID="' + chkid + '"' + chkstr + clickstr + disabledstr + '> Include ' + publdesc;
			// hard codping for the order of appearance on these pubs
			if (picktype == 'pickone' && thispubl == 'MET') {
				retvar = retvar + '<BR>(pick exactly one)';
			}
		} // end of for loop

	} else {
		// sections other than 05
		// newpublcodelist is like PAS,0,MEMBER,LIFESTATUS,PROFAFFILIATE
		newpublcodex = newpublcodelist;
dalrt('getChecksandPubl: newpublcodex ' + newpublcodex);
		// everything but section 5 has only one list like the above (i.e. no semicolons)
		parr = newpublcodex.split(',');
		// dalrt ('parr[0] ' + parr[0]);
		publdesc = '';
		chkstr = '';

		thispubl = parr[0];
		if(isincludeonly == 1) {
			publdollarstr = 0;
			retvar = 'incl. ' + getPublDesc(thispubl);
		} else {
			if (isitchecked == '1') {
				chkstr = ' CHECKED';
			}

			if (chkstr == ' CHECKED') {
				publdollarstr = 1 * parr[1];
			}
	dalrt ('in getChecksandPubl publdollarstr ' + publdollarstr + ' thispubl ' + thispubl);

			// match the publication code to get the description
			publdesc = getPublDesc(thispubl);
			chkid = 'pchk' + ix;
			// This is a publication on its own line, with a named checkbox, and an indication whether it is checked
			retvar = ' <INPUT TYPE="checkbox" VALUE="1" ID="' + chkid + '"' + chkstr + ' onClick="chgPubChk(\''+chkid+'\',' + ix + ', \'\')"' + disabledstr + '> Include ' + publdesc;
		}
	}

	dalrt ('leaving getChecksandPubl, retvar ' + retvar + ' publdollarstr ' + publdollarstr);
	return retvar;
}

function chkAPAMembershipRequired () {
	var retvar;

	dalrt('chkAPAMembershipRequired isduespaid ' + isduespaid + ' rateidx ' + rateidx + ' qrates.getField(rateidx,"apamembershiprequired") ' + qrates.getField(rateidx,"apamembershiprequired") );

	if (isduespaid == 1 ) {
		retvar = 'Y';
	} else if (qrates.getField(rateidx,"apamembershiprequired") === 'Y') {
		alert ('You must be an APA member, with current dues paid, to join division ' + divlinecodearray[ddidx] + '. Division has not been added to the "Renew or Add These Divisions" list');
		retvar = 'N';
	} else {
		retvar = 'Y';
	}
	return retvar;
}

function clearArrays (locidx) {
	divlinecodearray[locidx] 			= '';
	divlineidxarray[locidx] 			= '';
	linetotalarray[locidx] 				= '';
	divlinepublistarray[locidx] 		= '';
	publdollarstrarray[locidx] 			= '';
	divlinepubcheckedarray[locidx] 		= '';
	divlinedescarray[locidx] 			= '';
	divyearsindivarray[locidx] 			= '';
	divlinembtypearray[locidx] 			= '';
	divselectedpubarray[locidx] 		= '';
	divlineotherpubarray[locidx] 			= '';
}

function calcSelectedPub(ddind) {
	var lchk, retvar;
dalrt('calcSelectedPub divlinecodearray ' + divlinecodearray[ddind]);
	if (divlinecodearray[ddind] == '05') {
		// can be 0, 1, or 2 publications checked
		lchk = divlinepubcheckedarray[ddind];
		// defensive to correct for when someone WAS a student and had two publications selected, then switched to, say, member
		if (lchk === '1,1') {
		//	if(divmembtype == 'STUDENTAFFILIATE') {
				retvar = 'PAS,MET';
		//	} else {
		//		lchk = '1,0';
		//		divlinepubcheckedarray[ddind] = lchk;
		//		retvar = 'MET';
		//	}
		} else if (lchk === '1,0') {
			retvar = 'MET';
		} else if (lchk === '0,1') {
			retvar = 'PAS';
		} else if (lchk === '0,0') {
			retvar = ' ';
		}

	} else {
		if (divlinepubcheckedarray[ddind] == '1') {
			// checked. Pick up the publication code
			retvar = divlinepublistarray[ddind].substr(0,3);
		} else {
			retvar = ' ';
		}
	}
	return retvar;
}

function adjustHTML(){
	// rebuilds the HTML from the beginning
	// recalculates ...array [ddidx]  (problem)
	var j=0.0, dispdollarstr, parentOK, APAOK, publstr;

	// this shows we are always recalculating alldivstring
	alldivstring = '';
	glDivTotDollars = 0;
	dispdollarstr = '';
	linetotal = 0;
	isdebug = 0;

	dalrt('adjustHTML ddcount ' + ddcount);

	for (ddidx = 0; ddidx < ddcount ; ddidx++) {

		sectionidx 		= divlineidxarray[ddidx];
		newsectioncode 	= divlinecodearray[ddidx];
		//dalrt ('adjustHTML sectionidx ' + sectionidx + ' adjustHTML newsectioncode ' + newsectioncode);
		// first year, unless apadivlist shows he is already a member of the division
		isfirstyear = 1;
		// convert to regular expression
		pattern = newsectioncode;

		dalrt('looking in ' + apadivlist + ' for ' + newsectioncode);
		dalrt('apadivlist.search(pattern) ' + apadivlist.search(pattern));

		// removed test about isduespaid   if (ListFindNoCase(apadivlist, newsectioncode, '|') >= 1 && isduespaid === 1) {
		if (ListFindNoCase(apadivlist, newsectioncode, '|') >= 1 ) {
			isfirstyear = 0;
		}
		dalrt ('isfirstyear ' + isfirstyear);
		// get the matching description
		// searches the section list

		// this gets the description
		// newsectiondesc 		= sectionlist[sectionidx][1];
		// this gets the link, with description

		newsectiondesc 		= sectionlist[sectionidx][2];
		// searches the rate table. Sets divmembtype for this division
		// SETS rateidx

		dalrt('calling getFeeFromSession ddidx ' + ddidx);

		thissectionfeestr 	= getFeeFromSession(ddidx);

		dalrt('after getFeeFromSession, thisectionfeestr ' + thissectionfeestr);

		if (thissectionfeestr === null) {
			// do not display this section
			continue;
		}

		// pick up items now that rateidx and divmembtype are set
		divlinedescarray[ddidx]		= qrates.getField(rateidx,"sectionname");
		divyearsindivarray[ddidx]		= qrates.getField(rateidx,"yearsindiv");
		// this changes because sometimes an international affiliate joins as a professional affiliate
		divlinembtypearray[ddidx]	= divmembtype;
		divlineotherpubarray[ddidx]	= qrates.getField(rateidx,"otherpubs");
		dalrt('AdjustHTML: divlineotherpubarray[ddidx] ' + ddidx + ' ' + divlineotherpubarray[ddidx]);

		// pick up the publication list, if it has not been set

		if (qrates.getField(rateidx,"publcodexml") !== '' && qrates.getField(rateidx,"publcodexml") !== null && divlinepublistarray[ddidx] === '') {
			// this ONLY happens if this is a NEW item in divlinpublistarray
			divlinepublistarray[ddidx]	= qrates.getField(rateidx,"publcodexml");

			// this is hard-coded INITIAL value is that the publications are selected
			divlinepubcheckedarray[ddidx] = '1';
			if (newsectioncode == '05') {
				if (divmembtype == 'STUDENTAFFILIATE') {
					// student can pick 0, 1, 2 journals
					divlinepubcheckedarray[ddidx] = '1,1';
				} else {
					// others pick exactly one journal
					divlinepubcheckedarray[ddidx] = '1,0';
				}
			}
		}

		linetotal = 1 * thissectionfeestr;

		dalrt('adjustHTML newsectioncode, rateidx, thissectionfeestr in adjustHTML ' + newsectioncode + ' ' + rateidx + ' ' + thissectionfeestr);
		if (linetotal == -1) {
			alert('No rate is available for section ' + newsectioncode + ' for your membership/affiliate category. Nothing done');
			// DELETE this division. This must be the last division
			clearArrays(ddcount - 1);
			ddcount = ddcount - 1;
			continue;
		}

		// see if person is in a parent division, if required

		parentOK = chkParentDiv();
		if (parentOK == 'N') {
			// DELETE this division. This must be the last division
			clearArrays(ddcount - 1);
			ddcount = ddcount - 1;
			continue;
		}

		if (processingupperdivlist === 0) {
			APAOK = chkAPAMembershipRequired();
			if (APAOK == 'N') {
				// DELETE this division. This must be the last division
				clearArrays(ddcount - 1);
				ddcount = ddcount - 1;
				continue;
			}
		}

		// set publication string with the checkboxes, see about publication fee

		publstr = getChecksandPubl(ddidx);

		dalrt('AFTER getChecksandPubl, publstr ' + publstr + ', publdollarstr ' + publdollarstr);

		// store the line details in arrays for hidden variables for the action form
		linetotal = Number(thissectionfeestr) + Number(publdollarstr);

		linetotalarray[ddidx] 			= linetotal;
		publdollarstrarray[ddidx] 		= publdollarstr;
		dalrt('calling calcSelectedPub ddidx = ' + ddidx);

		divselectedpubarray[ddidx]		= calcSelectedPub(ddidx);

		// add the fee to the total
		// skip divisions already paid
		if (processingupperdivlist === 0) {
			glDivTotDollars = glDivTotDollars + linetotal;
		}
		dispdollarstr='$';
		for (j = 0; j < 8 - thissectionfeestr.length; j++) {
			dispdollarstr = dispdollarstr + '&nbsp;';
		}
		dispdollarstr = dispdollarstr + makeDollarJS(linetotal);
		dalrt ('go to addToInner dispdollarstr (line total) ' + dispdollarstr + ' publstr ' + publstr);

		// update the HTML for this row
		addToInner(ddidx + 1, newsectioncode, newsectiondesc, divmembtype, publstr, dispdollarstr);

	} // end of loop on all divisions
	// add the amount from the current divisions
	glDivTotDollars = glDivTotDollars + 1 * grandbase;

	makeDollarFromVar('GrandTotal', glDivTotDollars);

}

function redisplayDivStatus() {
	// executed when user clicks or unclicks a checkbox in the original division area
	scanDivsForResign();
	adjustHTML();
	viewDivs();
}

function addSection(vsectioncode, disperrors, listname) {

	// be sure the person has not already added this same division
	// ddcount must be valid.  sectionidx must be set.
	// All the other arrays are set from ddcount

	var kk, kmin, locidx;
	isdebug = 0;
	 // dalrt('addSection checking that ' + vsectioncode + ' has been selected already, ddcount ' + ddcount. );
     dalrt('disperrors ' + disperrors + '     listname ' + listname);
	if (divmembtype == ''){
		alert ('Please indicate your member type, first');
		return;
	}

	// set the value of the select in the HTML.  This is a section CODE
	document.getElementById('section').value = vsectioncode;

	dalrt('SEARCHING prevpddivlist ' +  prevpddivlist + ' sectioncode ' + vsectioncode + ' result ' + prevpddivlist.search(vsectioncode));

	// first item is item 1
	kk = ListFindNoCase(curdivlist, vsectioncode, '|');

	// adjust to 0 basis
	kk = kk - 1;

	if (kk >= 0) {
		// person has already paid for this division
		if (disperrors == 1 && listname !== 'curdivlist') {
			alert ('You have already selected division ' + vsectioncode + '. Nothing done');
			return;
		}
	}

	// check the divisions the person might have added in THIS use of the form
	for (locidx = 0; locidx < ddcount; locidx++) {
		if (divlinecodearray[locidx] == vsectioncode) {
			if (disperrors == 1) {
				alert ('You have already selected division ' + vsectioncode + '. Nothing done');
			}
			return;
		}
	}

	// always adding at the end of the list
	ddcount = ddcount + 1;

	// save this code in the "selected division" array
	ddidx = ddcount - 1;
	// this says line 0 in the display of lines of division points to the record in the vsectioncode division (section)
	divlineidxarray[ddidx] 			= sectionidx;
	divlinecodearray[ddidx] 		= vsectioncode;
	// these values get filled in later, after rateidx is set
	divlinepublistarray[ddidx] 		= '';
	divlinepubcheckedarray[ddidx] 	= '';
	linetotalarray[ddidx] 			= '';
	divlinedescarray[ddidx] 		= '';
	divyearsindivarray[ddidx] 		= '';
	divlinembtypearray[ddidx] 		= '';

dalrt('addSection added ' + vsectioncode + '. Calling adjustHTML');

	// adjust the division HTML. This may delete a section if there is an error
	adjustHTML();

	if (listname !== 'upperdivlist') {
		// convert to the hidden variables, so the "act" form can see them
		chgToHidden();

		// show the divisions
		viewDivs();
	}
}

function addSectionFromDropDown() {
	// add another section to be displayed in the upper part of the form
	var htmlsectionidx = 0;

	htmlsectionidx 		= document.getElementById('section').selectedIndex;
	newsectioncode 		= document.getElementById('section').options[htmlsectionidx].value;

	// Account for "please select" in the first row of the selector
	sectionidx = htmlsectionidx - 1;

	addSection(newsectioncode, 1, '');
}

function setOrigDivMembTypeFromDropDown() {
	// set the origdivmembtype from the dropdown
	var htmlorigdivmembtypeidx = 0, locidx;

	htmlorigdivmembtypeidx 		= document.getElementById('origdivmembtypedrop').selectedIndex;
	origdivmembtype 			= document.getElementById('origdivmembtypedrop').options[htmlorigdivmembtypeidx].value;
	document.getElementById('origdivmembtype').value 	= origdivmembtype;
	document.getElementById('divmembtype').value 		= origdivmembtype;
	divmembtype = origdivmembtype;


	// clear the misc hidden stuff, since initializeDivForm will reinitailize
	alldivstring = '';
	// this must be set before clearArrays
	document.getElementById('firstdivlist').value = document.getElementById('formdivlist').value;
	for (locidx = 0; locidx < ddcount; locidx++) {
		clearArrays(locidx);
	}
	document.getElementById('ddcount').value 		= 0;
	dalrt('setOrigDivMembTypeFromDropDown firstdivlist ' + firstdivlist);
	// document.getElementById('origdivmembtypedropdiv').style.display = 'none';
	dalrt ('Calling initializeDivForm, origdivmembtype = ' + document.getElementById('origdivmembtype').value);
	initializeDivForm();
	// this is in case the person changed origdivmembtype when he had some divisions displayed
	// this should adjust checkboxes
	adjustHTML();
	viewDivs();
}

function buildHTMLFromDivList(listname) {
	// builds the html, one line at a time, from the firstdivlist

	// listname is the name of a list of section codes
	var thisdiv;
	if (listname === 'firstdivlist') {
		for (var lptr = 0; lptr < firstdivlist.split('|').length; lptr++){

			// this uses split AND array without a temporary variable
			thisdiv = firstdivlist.split('|')[lptr];
			dalrt('buildHTMLFromDivList thisdiv ' + thisdiv);
			// calculate sectionidx from the thisdiv code from the list
			for (var kk = 0;  kk < sectionlist.length; kk++) {
				if (sectionlist[kk][0] == thisdiv) {
					sectionidx = kk;
					break;
				}
			}
			dalrt('buildHTMLFromDivList listname ' + listname + ' sectionidx ' + sectionidx + ' thisdiv ' + thisdiv);
			addSection(thisdiv, 0, listname);
		}
	}
	else if (listname === 'upperdivlist') {
		for (var lptr = 0; lptr < upperdivlist.split('|').length; lptr++){
			thisdiv = upperdivlist.split('|')[lptr];
			dalrt('buildHTMLFromDivList thisdiv ' + thisdiv);
			// calculate sectionidx from the thisdiv code from the list
			for (var kk = 0;  kk < sectionlist.length; kk++) {
				if (sectionlist[kk][0] == thisdiv) {
					sectionidx = kk;
					break;
				}
			}
			dalrt('buildHTMLFromDivList  listname ' + listname + ' sectionidx ' + sectionidx + ' thisdiv ' + thisdiv);
			addSection(thisdiv, 0, listname);
		}
	}
	else {
		alert('error, unrecognized listname in buildHTMLFromDivList = ' + listname);
	}
}

function delSection(ddrow) {
	// delete the selected division, and compress the list
	var thissection, locidx;

	// ddrow is 1 for the first row. There are ddcount rows before anything is deleted
	// first, must see if there are any children of this parent, where this parent is required
	// old way thissection = qrates.getField(divlineidxarray[ddrow - 1] + 1, "sectioncode");
	// new way
	thissection = divlinecodearray[ddrow - 1];
	dalrt('into delSection, ddrow ' + ddrow + ' deleting divlineidxarray[ddrow - 1] ' + divlineidxarray[ddrow - 1] + 'thissection=' + thissection + ' ddrow ' + ddrow + ' ddcount ' + ddcount);
	// locidx goes from one above the selection
	for (locidx = ddrow ; locidx < ddcount; locidx++) {
		// set rateidx
 		dalrt ('setting rateidx for code ' + divlinecodearray[locidx]);

		thissectionfeestr = getFeeFromSession(locidx);

 		dalrt('testing section ' + divlinecodearray[locidx] + ' ' + rateidx + ' qrates.getField(rateidx, "divcode") ' + qrates.getField(rateidx, "divcode"));
		if (qrates.getField(rateidx, "divcode") == thissection &&
		qrates.getField(rateidx,"parentmembershiprequired") == 'Y') {
			alert('Please delete your membership in section ' + qrates.getField(rateidx,"sectioncode")+ ', first. Nothing done');
			// do not delete anything
			return;
		}
	}

	// shorten the list
	ddcount = ddcount - 1;
	// if deleting row 3 of 5 on the form, this goes from 2
	for (locidx = ddrow - 1; locidx < ddcount; locidx++) {
		if (locidx >= 0) {
			divlineidxarray[locidx] 		= divlineidxarray[locidx + 1];
			divlinecodearray[locidx] 		= divlinecodearray[locidx + 1];
			divlinepublistarray[locidx] 	= divlinepublistarray[locidx + 1];
			divlinepubcheckedarray[locidx] 	= divlinepubcheckedarray[locidx + 1];
			divlinedescarray[locidx] 		= divlinedescarray[locidx + 1];
			divyearsindivarray[locidx] 		= divyearsindivarray[locidx + 1];
			linetotalarray[locidx] 			= linetotalarray[locidx + 1];
			publdollarstrarray[locidx] 		= publdollarstrarray[locidx + 1];
			divlinembtypearray[locidx] 		= divlinembtypearray[locidx + 1];
			divlinembtypearray[locidx] 		= divlinembtypearray[locidx + 1];

		}
	}
	adjustHTML();
	// convert to the hidden variables, so the "act" form can see them
	chgToHidden();
	viewDivs();
}

function chgPubChk(n, ix, picktype) {
	var thischeck, ddind, thissectioncode, thischeckitem, ddval;

	// this routine can execute on ANY line in the division display. So, local ddind. Executes when person checks or unchecks a publication selection in a division
	if (document.getElementById(n) !== undefined){
		thischeck 	= document.getElementById(n).checked;
	} else {
		thischeck 	= false;
	}
	// Number(thischeck) == 0 when the box is just unchecked
	dalrt('chgPubChk ' + n + ' check is ' + Number(thischeck));
	ddind = ix - 1;
	thissectioncode = divlinecodearray[ddind];
	thischeckitem   = divlinepubcheckedarray[ddind];
	// for section 05, we are handling '1,1' where n has 'PAS,MET' appended in the name
	if (thissectioncode == '05') {
		dalrt ('n ' + n + ' thischecked ' + thischeck + ' picktype ' + picktype + ' thischeckitem ' + thischeckitem + ' n.search("PAS") ' + n.search('PAS'));

		// if picktype == 'pickone', then checking one box clears the other, AND clearing one box sets the other
		if (picktype == 'pickone' ) {
			if (n.search('PAS') >= 0) {
				// this is PAS, the second check mark
				if(thischeck) {
					ddval = '0,1';
				} else {
					ddval = '1,0';
				}
			} else {
				// this is MET, the first check mark
				if(thischeck) {
					ddval = '1,0';
				} else {
					ddval = '0,1';
				}
			}
		} else {
			// MET is the first check mark, PAS is the second (alphabetic)
			if (n.search('PAS') >= 0) {
				// this is PAS, the second check mark
				if (thischeckitem.substr(0,1) == '1') {
					// the OTHER one is checked
					if(thischeck) {
						ddval = '1,1';
					} else {
						ddval = '1,0';
					}
				} else {
					// the OTHER one is NOT checked
					if(thischeck) {
						ddval = '0,1';
					} else {
						ddval = '0,0';
					}
				}
			} else {
				// this is MET, the first check mark
				if (thischeckitem.substr(2,1) == '1') {
					// the OTHER one is checked
					if(thischeck) {
						ddval = '1,1';
					} else {
						ddval = '0,1';
					}
				} else {
					// the OTHER one is NOT checked
					if(thischeck) {
						ddval = '1,0';
					} else {
						ddval = '0,0';
					}
				}
			}
		}
	}
	else {
		// section is not 5
		if (thischeck) {
			ddval = '1';
			// divlinepublistarray is like 'GPR,17,STUDENTAFFIL....'
		} else {
			ddval = '0';
		}
	}

	dalrt('using ddval ' + ddval);
	divlinepubcheckedarray[ddind] = ddval;
	divselectedpubarray[ddind] = calcSelectedPub(ddind);
	// record the change in the JS arrays, and the hidden variables, and adjust the screen
	adjustHTML();
	// must update the hidden fields, in case we leave the JS now
	chgToHidden();
	viewDivs();
}

// END of divapp.js - works with divappForm.cfm




