package gov.va.med.esr.ui.util;

import gov.va.med.esr.ui.common.util.DateUtils;
import gov.va.med.esr.ui.common.util.JspUtils;
import gov.va.med.esr.ui.militaryservice.action.MilitaryServiceActionHelper;
import gov.va.med.esr.common.infra.ImpreciseDate;
import gov.va.med.esr.common.infra.ImpreciseDateUtils;
import gov.va.med.esr.voa.webservice.AddressInfo;
import gov.va.med.esr.voa.webservice.DependentFinancialsInfo;
import gov.va.med.esr.voa.webservice.DependentInfo;
import gov.va.med.esr.voa.webservice.EmailCollection;
import gov.va.med.esr.voa.webservice.EmploymentInfo;
import gov.va.med.esr.voa.webservice.ExpenseInfo;
import gov.va.med.esr.voa.webservice.FinancialsInfo;
import gov.va.med.esr.voa.webservice.Form;
import gov.va.med.esr.voa.webservice.IncomeInfo;
import gov.va.med.esr.voa.webservice.InsuranceInfo;
import gov.va.med.esr.voa.webservice.MilitaryServiceInfo;
import gov.va.med.esr.voa.webservice.PhoneInfo;
import gov.va.med.esr.voa.webservice.RaceCollection;
import gov.va.med.esr.voa.webservice.SpouseFinancialsInfo;
import gov.va.med.esr.voa.webservice.SpouseInfo;
import gov.va.med.esr.common.model.SiteYear;
import gov.va.med.esr.common.model.financials.DependentFinancials;
import gov.va.med.esr.common.model.financials.FinancialStatement;
import gov.va.med.esr.common.model.financials.IncomeTest;
import gov.va.med.esr.common.model.financials.SpouseFinancials;
import gov.va.med.esr.common.model.financials.PatientVisitSummary;
import gov.va.med.esr.common.model.insurance.Medicare;
import gov.va.med.esr.common.model.lookup.Country;
import gov.va.med.esr.common.model.lookup.Indicator;
import gov.va.med.esr.common.model.lookup.NameType;
import gov.va.med.esr.common.model.lookup.PhoneType;
import gov.va.med.esr.common.model.lookup.AssociationType;
import gov.va.med.esr.common.model.lookup.VAFacility;
import gov.va.med.esr.common.model.lookup.MaritalStatus;
import gov.va.med.esr.common.model.lookup.DecorationStatus;
import gov.va.med.esr.common.model.lookup.Relationship;
import gov.va.med.esr.common.model.lookup.RaceType;
import gov.va.med.esr.common.model.lookup.EthnicityType;
import gov.va.med.esr.common.model.lookup.Religion;
import gov.va.med.esr.common.model.lookup.EmploymentStatus;
import gov.va.med.esr.common.model.lookup.BenefitType;
import gov.va.med.esr.common.model.lookup.Gender;
import gov.va.med.esr.common.model.lookup.AgentOrangeExposureLocation;
import gov.va.med.esr.common.model.insurance.InsurancePolicy;
import gov.va.med.esr.common.model.insurance.PrivateInsurance;
import gov.va.med.esr.common.model.ee.AgentOrangeExposure;
import gov.va.med.esr.common.model.ee.EnvironmentalContaminationExposure;
import gov.va.med.esr.common.model.ee.MedicaidFactor;
import gov.va.med.esr.common.model.ee.MilitaryService;
import gov.va.med.esr.common.model.ee.CombatEpisode;
import gov.va.med.esr.common.model.ee.MilitaryServiceEpisode;
import gov.va.med.esr.common.model.ee.MilitaryServiceSiteRecord;
import gov.va.med.esr.common.model.ee.NoseThroatRadium;
import gov.va.med.esr.common.model.ee.PurpleHeart;
import gov.va.med.esr.common.model.ee.RadiationExposure;
import gov.va.med.esr.common.model.ee.ServiceConnectionAward;
import gov.va.med.esr.common.model.ee.PrisonerOfWar;
import gov.va.med.esr.common.model.ee.Application;

import gov.va.med.esr.common.model.party.Address;
import gov.va.med.esr.common.model.party.Email;
import gov.va.med.esr.common.model.party.Phone;
import gov.va.med.esr.common.model.person.Association;
import gov.va.med.esr.common.model.person.Name;
import gov.va.med.esr.common.model.person.Person;
import gov.va.med.esr.common.model.person.SSN;
import gov.va.med.esr.common.model.person.Spouse;
import gov.va.med.esr.common.model.person.Dependent;
import gov.va.med.esr.common.model.person.Race;
import gov.va.med.esr.common.model.person.Ethnicity;
import gov.va.med.esr.common.model.person.Employment;
import gov.va.med.esr.common.model.person.BirthRecord;
import gov.va.med.esr.common.model.person.VOAApplication;
import gov.va.med.esr.common.model.person.id.VPIDEntityKey;
import gov.va.med.esr.service.PersonIdentityTraits;
import gov.va.med.fw.util.StringUtils;
import gov.va.med.person.idmgmt.VPID;
import gov.va.med.esr.common.infra.TriState;

import gov.va.med.esr.ui.financials.action.FinancialsConstants;

/* iText-2.1.4.jar */
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.Phrase;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.DocumentException;
import java.text.SimpleDateFormat;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;

import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import java.awt.Color;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXB;

/**
* @author Wen Lin - Financials1010EZApplication is used by financial overview page to
*         generate the 1010EZ form in PDF format for printing. This class fills
*         in the values in a fillable 1010EZ PDF form. If the application
*         contains additional information (as indicated on the form by
*         specifying that the applicant use a separate sheet for additional
*         information), an additional PDF document is also created and appended
*         to the 1010EZ form.
*
*/

public class Financials1010EZApplication {
    private static final Logger log = Logger.getLogger(Financials1010EZApplication.class);

    private HashMap fieldMap = new HashMap();
    private HashMap fieldMap2015 = new HashMap();
    private Person person = null;
    private VOAApplication app = null;
    private Form voaForm = null;
    private MilitaryService militaryService = null;
    private MilitaryServiceInfo militaryServiceInfo= null;
    private Set insurances;
    private Set privateinsurances;
    private List<InsuranceInfo> insuranceInfo;
    private Set medicares;
    private Set dependentFinancials;
    private SpouseFinancials sf = null;
    private FinancialStatement ftmt = null;
    private FinancialsInfo financialsInfo = null;
    private Integer incomeYear;
    private boolean FinDisclosureFlag = false;
    private  Spouse spouse = null;

    private List patientVisitSummaries = null;
    private AcroFields fields;
    private PdfReader reader;
    private PdfStamper stamper;
    private Document additionalInsDocument;
    private Document additionalChildDocument;
    //private Document additionalChildFinDocument;  //
    private boolean isAdditionalDocumentInsNeeded = false;
    private boolean isAdditionalDocumentChildNeeded = false;
    private Font font_helve ;
    private Font font_courier ;
    private Font font_times ;
    private String formFileName;
    private String additionalInsFileName;
    private String additionalChildFileName;
    //private String additionalChildFinFileName;
    private String finalFileName;
    private String filePath;
    private String templateLocation;
    private InputStream fillablePDF;
    private FileOutputStream outStaticForm;
    private FileOutputStream outAdditionalInsForm;
    private FileOutputStream outAdditionalChildForm;
    //private FileOutputStream outAdditionalChildFinForm;
    private FileOutputStream outCombinedForm;
    //private HttpServletResponse response;
    private String veteranName = "";
    private String veteranSSN = "";
    /**
     * Constructor
     *
    * @param person
     *            Person object
     * @parm incomeYear
     *                       Integer of the income year selected
     * @param templatepath
     *            The location where the template file was saved
     */
   public Financials1010EZApplication(Person person, Integer incomeYear, InputStream is, String outputPath) {
        this.person = person;
        this.incomeYear = incomeYear;
        // this.templateLocation = templatePath;
        this.filePath = outputPath;
        this.fillablePDF = is;


        initializeFieldMap();
        String personId = person.getEntityKey().getKeyValueAsString();
        setOutputFiles(personId);

        this.militaryService = person.getMilitaryService();
        this.privateinsurances = person.getPrivateInsurances();
        this.ftmt = person.getFinancialStatement(incomeYear);
        if (this.ftmt == null) {
            this.ftmt = new FinancialStatement();
        }
        this.sf = ftmt.getRecentSpouseFinancials();
        this.dependentFinancials = ftmt.getDependentFinancials();

        if ( privateinsurances != null && privateinsurances.size() > 1 )
            this.initializeAdditionalInsPDF();

        if ( dependentFinancials != null && dependentFinancials.size() > 1 )
             this.initializeAdditionalChildPDF();

        initializePDF();

        this.font_helve  = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);
        this.font_courier = FontFactory.getFont(FontFactory.COURIER, 8);
        this.font_times = FontFactory.getFont(FontFactory.TIMES_ROMAN, 8);
    }

   //constructor for OMB approved Year 2015 version
   public Financials1010EZApplication(Person person, VOAApplication app, InputStream is, String outputPath) {
        this.person = person;
        this.app = app;
        this.filePath = outputPath;
        this.fillablePDF = is;

        //intialize the 2015 form fields with default values
        //note that for future customizations of the pdf form field names, you may need to use Acrobat Pro
        initializeOMB2015FieldMap();


       String personId = person.getEntityKey().getKeyValueAsString();
       setOutputFiles(personId);

       //deserialize a HCA appXML into a VOA Form
       Form result = JAXB.unmarshal(new StringReader(app.getVOAApplicationData().getApplicationData()), Form.class);
       this.voaForm = result;

       this.militaryServiceInfo = result.getSummary().getMilitaryServiceInfo();

       if (result.getSummary() != null && result.getSummary().getInsuranceList() != null){
    	   this.insuranceInfo = result.getSummary().getInsuranceList().getInsurance();
       }
       this.financialsInfo = result.getSummary().getFinancialsInfo();

       if ( insuranceInfo != null && insuranceInfo.size() > 1 ) {
           this.initializeAdditionalInsPDF();
       }

       if ( financialsInfo != null && financialsInfo.getFinancialStatement() != null &&
                financialsInfo.getFinancialStatement().getDependentFinancialsList() != null &&
                financialsInfo.getFinancialStatement().getDependentFinancialsList().getDependentFinancials() != null &&
                              financialsInfo.getFinancialStatement().getDependentFinancialsList().getDependentFinancials().size() > 1) {
          this.initializeAdditionalChildPDF();
       }


       initializePDF();

       this.font_helve  = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);
       this.font_courier = FontFactory.getFont(FontFactory.COURIER, 8);
       this.font_times = FontFactory.getFont(FontFactory.TIMES_ROMAN, 8);
   }


    private String getFormFileName(){
       return this.formFileName;
    }
    private String getAdditionalInsuranceFileName(){
       return this.additionalInsFileName;
    }
    private String getAdditionalDependentFileName(){
       return this.additionalChildFileName;
    }
    private String getFinalFileName(){
       return this.finalFileName;
    }
    private String getOutputFilePath(){
       return this.filePath;
    }


    private void setOutputFiles(String vetId){
        String currDate = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
        currDate = currDate==null?"":currDate.trim();
        String fSeparater = FinancialsConstants.PDF_FILE_SEPARATER;
        String fForm = FinancialsConstants.PDF_FILL_FORM;
        String fInsurance = FinancialsConstants.PDF_ADDITIONAL_INSURANCE;
        String fChild = FinancialsConstants.PDF_ADDITIONAL_DEPENDENT;
        String fFinal = FinancialsConstants.PDF_FINAL_OUTPUT;
        String fExt = FinancialsConstants.PDF_EXTENSION;

        // this.filePath = FinancialsConstants.PDF_OUTPUT_FILE_PATH;
        this.formFileName = vetId+fSeparater+fForm+fSeparater+currDate+fExt;

        this.additionalInsFileName = vetId+fSeparater+fInsurance+fSeparater+currDate+fExt;

        this.additionalChildFileName = vetId+fSeparater+fChild+fSeparater+currDate+fExt;

        this.finalFileName = vetId+fSeparater+fFinal+fSeparater+currDate+fExt;
     }


    /**
     * Initialize the PDF
     *
     */
    private void initializePDF() {
        try {
            reader = new PdfReader(this.fillablePDF);
            if (isAdditionalDocumentInsNeeded || isAdditionalDocumentChildNeeded) {
                outStaticForm = new FileOutputStream(this.getOutputFilePath() + this.getFormFileName());
                stamper = new PdfStamper(reader, outStaticForm, '\0');
            } else {
                outCombinedForm = new FileOutputStream(this.getOutputFilePath() + this.getFinalFileName());
                stamper = new PdfStamper(reader, outCombinedForm, '\0');
            }
            fields = stamper.getAcroFields();
        } catch (Exception e) {

        	log.error("error occurred while initializing the pdf: " + e);
        }
    }

    private void initializeAdditionalInsPDF() {
        isAdditionalDocumentInsNeeded = true;
        try {
            additionalInsDocument = new Document(PageSize.A4, 25, 25, 50, 50);
            outAdditionalInsForm = new FileOutputStream(this.getOutputFilePath()+ this.getAdditionalInsuranceFileName());
            PdfWriter.getInstance(additionalInsDocument, outAdditionalInsForm);
            additionalInsDocument.open();
        } catch (Exception e) {

        	log.error("error occurred while initializing additional pdf: " + e);
        }
    }

    private void initializeAdditionalChildPDF() {
        isAdditionalDocumentChildNeeded = true;
        try {
            additionalChildDocument = new Document(PageSize.A4, 25, 25, 50, 50);
            outAdditionalChildForm = new FileOutputStream(this.getOutputFilePath()+ this.getAdditionalDependentFileName());
            PdfWriter.getInstance(additionalChildDocument, outAdditionalChildForm);
            additionalChildDocument.open();
        } catch (Exception e) {
        	log.error("error occurred while initializing additional child pdf: " + e);
        }
    }


    /**
     * Concatenate fillable PDF document and additional PDF document
     *
     * @param streamOfPDFFiles
     *            List of PDF documents as InputStream objects
     * @param outputStream
     *            The resulting OutputStream object
     * @param paginate
     *            Boolean indicating whether to paginate the resulting document
     */
    private void concatPDFs(List streamOfPDFFiles, OutputStream outputStream,
            boolean paginate) {
        Document document = new Document();
        try {
            List pdfs = streamOfPDFFiles;
            List readers = new ArrayList();
            int totalPages = 0;
            Iterator iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs.
            while (iteratorPDFs.hasNext()) {
                InputStream pdf = (InputStream) iteratorPDFs.next();
                PdfReader pdfReader = new PdfReader(pdf);
                readers.add(pdfReader);
                totalPages += pdfReader.getNumberOfPages();
            }
            // Create a writer for the outputstream
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            // BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            BaseFont bf = BaseFont.createFont(BaseFont.COURIER,BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            PdfContentByte cb = writer.getDirectContent();
            // Holds the PDF // data
            PdfImportedPage page;
            int currentPageNumber = 0;
            int pageOfCurrentReaderPDF = 0;
            Iterator iteratorPDFReader = readers.iterator();
            // Loop through the PDF files and add to the output.
            while (iteratorPDFReader.hasNext()) {
                PdfReader pdfReader = (PdfReader) iteratorPDFReader.next();
                // Create a new page in the target for each source page.
                while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                    document.newPage();
                    pageOfCurrentReaderPDF++;
                    currentPageNumber++;
                    page = writer.getImportedPage(pdfReader,pageOfCurrentReaderPDF);
                    cb.addTemplate(page, 0, 0);
                    // Code for pagination.
                    if (paginate) {
                        cb.beginText();
                        cb.setFontAndSize(bf, 10);
                        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, ""+ currentPageNumber + " of " + totalPages, 520,5, 0);
                        cb.endText();
                    }
                }
                pageOfCurrentReaderPDF = 0;
            }
            outputStream.flush();
            document.close();
            outputStream.close();
        } catch (Exception e) {

        	log.error("error occurred while concatenating pdf: " + e);
        } finally {
            if (document.isOpen())
                document.close();
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException ioe) {
            	log.error("error occurred while concatenating pdf: " + ioe);
            }
        }
    }


    //populate the fields for OMB approved year 2015 Health Care Application Form
    public void getOnline1010EZ() throws Exception {
        try {

            // Set section 1 - General Information
             fillHCAGeneralSection1();

             // Section 2 - Military Service Information
             fillHCAMilitarySection2();

             //section 3 - Insurance Information
             fillHCAInsuranceSection3();

             // Section 4 -Spouse/Dependent Information
             fillHCADependentInfotmationSection4();

             // Section 5 - Previous Calendar Year Gross Annual Income of Veteran, Spouse, and Dependent Children
             // Section 6 - Previous Calendar Year Deductible Expenses
             fillHCAIncomeSection5AndExpenseSection6();

            // Section 7- Assignment of Benefits
            fillHCASignatureSection7();

            stamper.setFormFlattening(true);
            reader.close();
            stamper.close();

            if (isAdditionalDocumentInsNeeded) {
                additionalInsDocument.close();
                outAdditionalInsForm.close();
            }
            if (isAdditionalDocumentChildNeeded){
            additionalChildDocument.close();
                outAdditionalChildForm.close();
            }
            if (isAdditionalDocumentInsNeeded || isAdditionalDocumentChildNeeded)
            outStaticForm.close();
            else
            outCombinedForm.close();

        } catch (Exception e) {
        	log.error("error occurred while processing the pdf: " + e);
            reader.close();
            try {
            if (isAdditionalDocumentInsNeeded) {
                    additionalInsDocument.close();
                    outAdditionalInsForm.close();
                }
                if (isAdditionalDocumentChildNeeded){
                    additionalChildDocument.close();
                    outAdditionalChildForm.close();
               }
                if (isAdditionalDocumentInsNeeded || isAdditionalDocumentChildNeeded)
                    outStaticForm.close();
                else
                    outCombinedForm.close();
                stamper.close();
            } catch (Exception e2) {
            	log.error("error occurred while processing the pdf: " + e2);
            }
        } finally {
            reader.close();
            try {
            if (isAdditionalDocumentInsNeeded) {
                    additionalInsDocument.close();
                    outAdditionalInsForm.close();
                }
                if (isAdditionalDocumentChildNeeded){
                    additionalChildDocument.close();
                    outAdditionalChildForm.close();
                }
                if (isAdditionalDocumentInsNeeded || isAdditionalDocumentChildNeeded)
                    outStaticForm.close();
                else
                    outCombinedForm.close();
                stamper.close();

            } catch (Exception e) {

            	log.error("error occurred while processing the pdf: " + e);
            }
        }
        // Concatenate pdfs
        try {
              if (isAdditionalDocumentInsNeeded || isAdditionalDocumentChildNeeded) {
                List pdfs;
                OutputStream output;
                FileInputStream inStaticForm = null;
                FileInputStream inAdditionalInsForm = null;
                FileInputStream inAdditionalChildForm = null;
                pdfs = new ArrayList();
                File file1 = new File(this.getOutputFilePath() + this.getFormFileName());
                inStaticForm = new FileInputStream(file1);
                pdfs.add(inStaticForm);

                File file2 =null;
                File file3 = null;
                if (isAdditionalDocumentInsNeeded){
                    file2 = new File(this.getOutputFilePath()+ this.getAdditionalInsuranceFileName());
                    inAdditionalInsForm = new FileInputStream(file2);
                    pdfs.add(inAdditionalInsForm);
                }
                if (isAdditionalDocumentChildNeeded){
                    file3 = new File(this.getOutputFilePath()+ this.getAdditionalDependentFileName());
                    inAdditionalChildForm = new FileInputStream(file3);
                    pdfs.add(inAdditionalChildForm);
                }
                output = new FileOutputStream(this.getOutputFilePath() + this.getFinalFileName());
                concatPDFs(pdfs, output, true);
                output.close();
                inStaticForm.close();

                if (inAdditionalInsForm != null)
                    inAdditionalInsForm.close();
                if (inAdditionalChildForm!=null)
                    inAdditionalChildForm.close();

                if (file1.exists()) file1.delete();
                if (isAdditionalDocumentInsNeeded){
                    if (file2.exists()) file2.delete();
                }
                if (isAdditionalDocumentChildNeeded){
                    if (file3.exists()) file3.delete();
                }
            }
        } catch (Exception e) {
        	log.error("error occurred while processing the pdf: " + e);
        }
    }


    /**
     * Initialize the field in the fillable pdf 2015 form
     * Note that for further customizations of field names, you may need a copy of
     * Adobe Acrobat pro.
     *
     */

    private void initializeOMB2015FieldMap() {

        //Section 1 - General Information
        //names
        fieldMap2015.put("Section1:Question1", "Text1");
        fieldMap2015.put("Section1:Question2-MaidenName", "Text2");
        fieldMap2015.put("Section1:Question3:Male", "Check Box1");
        fieldMap2015.put("Section1:Question3:Female", "Check Box2");

        //hispanic, spanish or latino?
        fieldMap2015.put("Section1:Question4:HispanicYes", "Check Box3");
        fieldMap2015.put("Section1:Question4:HispanicNo", "Check Box4");

        //race
        fieldMap2015.put("Section1:Question5:AlaskaNative", "Check Box5");
        fieldMap2015.put("Section1:Question5:Asian", "Check Box6");
        fieldMap2015.put("Section1:Question5:White", "Check Box7");
        fieldMap2015.put("Section1:Question5:Black", "Check Box8");
        fieldMap2015.put("Section1:Question5:NativeHawaiian", "Check Box9");

        //ssn
        fieldMap2015.put("Section1:Question6-SSN", "Text3");

        //dob
        fieldMap2015.put("Section1:Question7-dob", "Text4");
        fieldMap2015.put("Section1:Question7a-pob", "Text5");

        //address
        fieldMap2015.put("Section1:Question8-address", "Text6");
        fieldMap2015.put("Section1:Question8a-city", "Text7");
        fieldMap2015.put("Section1:Question8b-state", "Text8");
        fieldMap2015.put("Section1:Question8c-zip", "Text9");
        fieldMap2015.put("Section1:Question8d-county", "Text10");
        fieldMap2015.put("Section1:Question8e-hmTel", "Text11");
        fieldMap2015.put("Section1:Question8f-mobileTel", "Text12");
        fieldMap2015.put("Section1:Question8g-email", "Text13");

        //Marital Status
        fieldMap2015.put("Section1:Question9:Married", "Check Box10");
        fieldMap2015.put("Section1:Question9:NeverMarried", "Check Box11");
        fieldMap2015.put("Section1:Question9:Separated", "Check Box12");
        fieldMap2015.put("Section1:Question9:Widowed", "Check Box13");
        fieldMap2015.put("Section1:Question9:Divorced", "Check Box14");

        //Min ACA Coverage
        fieldMap2015.put("Section1:Question10:acaYes", "Check Box15");
        fieldMap2015.put("Section1:Question10:acaNo", "Check Box16");

        //medical/OPC
        fieldMap2015.put("Section1:Question11-prefFacility", "Text14");

        //schedule appt?
        fieldMap2015.put("Section1:Question12:ApptYes", "Check Box17");
        fieldMap2015.put("Section1:Question12:ApptNo", "Check Box18");



        // Section 2 - Military Service
        fieldMap2015.put("Section2:Question1-LastSvcBranch", "Text15");
        fieldMap2015.put("Section2:Question1A-LastEntryDate", "Text151");
        fieldMap2015.put("Section2:Question1B-LastDischargeDate", "Text152");
        fieldMap2015.put("Section2:Question1C-LastDischargeType", "Text153");

        //Section 2 - Military History
        fieldMap2015.put("Section2:Question2a-PH:Yes", "Check Box19");
        fieldMap2015.put("Section2:Question2a-PH:No", "Check Box20");
        fieldMap2015.put("Section2:Question2b-POW:Yes", "Check Box21");
        fieldMap2015.put("Section2:Question2b-POW:No", "Check Box22");

        fieldMap2015.put("Section2:Question2c-Combat:Yes", "Check Box23");
        fieldMap2015.put("Section2:Question2c-Combat:No", "Check Box24");

        fieldMap2015.put("Section2:Question2d-disability:Yes", "Check Box25");
        fieldMap2015.put("Section2:Question2d-disability:No", "Check Box26");

        fieldMap2015.put("Section2:Question2e-gulfwar:Yes", "Check Box27");
        fieldMap2015.put("Section2:Question2e-gulfwar:No", "Check Box28");

        fieldMap2015.put("Section2:Question2f-vietnam:Yes", "Check Box29");
        fieldMap2015.put("Section2:Question2f-vietnam:No", "Check Box30");

        fieldMap2015.put("Section2:Question2g-radiation:Yes", "Check Box31");
        fieldMap2015.put("Section2:Question2g-radiation:No", "Check Box32");

        fieldMap2015.put("Section2:Question2h-radium:Yes", "Check Box33");
        fieldMap2015.put("Section2:Question2h-radium:No", "Check Box34");

        fieldMap2015.put("Section2:Question2i-clv:Yes", "Check Box35");
        fieldMap2015.put("Section2:Question2i-clv:No", "Check Box36");


        // Section 3 - Insurance
        fieldMap2015.put("Section3:Question1-Insurance Company-address-tel", "Text16");
        fieldMap2015.put("Section3:Question2-InsPolicyHolder", "Text17");
        fieldMap2015.put("Section3:Question3-InsPolicyNumber", "Text18");
        fieldMap2015.put("Section3:Question4-InsGroupNum", "Text19");
        fieldMap2015.put("Section3:Question5:MedicaidYes", "Check Box37");
        fieldMap2015.put("Section3:Question5:MedicaidNo", "Check Box38");
        fieldMap2015.put("Section3:Question6:HospitalInsPartAYes", "Check Box39");
        fieldMap2015.put("Section3:Question6:HospitalInsPartANo", "Check Box40");

        fieldMap2015.put("Section3:Question6a-InsEffectiveDate", "Text20");
        fieldMap2015.put("Section3:Question6b-veteranName", "Text21");
        fieldMap2015.put("Section3:Question6c-vetSSN", "Text22");


        // Section 4 - Dependent Information
        fieldMap2015.put("Section4:Question1-SpouseName", "Text23");
        fieldMap2015.put("Section4:Question1A-SSN", "Text24");
        fieldMap2015.put("Section4:Question1B-DOB", "Text25");
        fieldMap2015.put("Section4:Question1C-DOM", "Text26");
        fieldMap2015.put("Section4:Question1D-addressTel", "Text27");
        fieldMap2015.put("Section4:Question2-ChildName", "Text28");
        fieldMap2015.put("Section4:Question2A-ChildDOB", "Text29");
        fieldMap2015.put("Section4:Question2B-ChildSSN", "Text30");
        fieldMap2015.put("Section4:Question2C-DateChildBecameDependent", "Text31");

        fieldMap2015.put("Section4:Question2D:Son", "Check Box41");
        fieldMap2015.put("Section4:Question2D:Daughter", "Check Box42");
        fieldMap2015.put("Section4:Question2D:Stepson", "Check Box43");
        fieldMap2015.put("Section4:Question2D:Stepdaughter", "Check Box44");


        fieldMap2015.put("Section4:Question2E-DisableBefore18:Yes", "Check Box45");
        fieldMap2015.put("Section4:Question2E-DisableBefore18:No", "Check Box46");

        fieldMap2015.put("Section4:Question2F-AttendedSchool:Yes", "Check Box47");
        fieldMap2015.put("Section4:Question2F-AttendedSchool:No", "Check Box48");

        fieldMap2015.put("Section4:Question2G-expensesByDepChild", "Text32");

        fieldMap2015.put("Section4:Question3-finSupport:Yes", "Check Box49");
        fieldMap2015.put("Section4:Question3-finSupport:No", "Check Box50");



         // Section 5 - prev cal year Income Information
        fieldMap2015.put("Section5:Question1:VeteranGrossIncome", "Text33");
        fieldMap2015.put("Section5:Question1:SpouseGrossIncome", "Text34");
        fieldMap2015.put("Section5:Question1:ChildGrossIncome", "Text35");
        fieldMap2015.put("Section5:Question2:VeteranNetIncome", "Text36");
        fieldMap2015.put("Section5:Question2:SpouseNetIncome", "Text37");
        fieldMap2015.put("Section5:Question2:ChildNetIncome", "Text38");
        fieldMap2015.put("Section5:Question3:VeteranOtherIncome", "Text40");
        fieldMap2015.put("Section5:Question3:SpouseOtherIncome", "Text41");
        fieldMap2015.put("Section5:Question3:ChildOtherIncome", "Text42");

        // Section 6- prev cal year deductible expenses
        fieldMap2015.put("Section6:Question1:Non_reimb-Medical-exp", "Text43");
        fieldMap2015.put("Section6:Question2:Funeral-Burial-exp", "Text44");
        fieldMap2015.put("Section6:Question3:College-voc-exp", "Text45");

        // Section 7-assignment of benefits/signature-date
        fieldMap2015.put("Section7:signDate", "Text46");
    }

    //OMB approved 2015 HCA form -  Section 1
    private void fillHCAGeneralSection1() throws DocumentException, IOException {

        Name legalName = null;
        Name aliasName = null;

        String p_legalname = voaForm.getSummary().getPersonInfo().getLastName() +", " + voaForm.getSummary().getPersonInfo().getFirstName();
        String middleName = voaForm.getSummary().getPersonInfo().getMiddleName() != null ? voaForm.getSummary().getPersonInfo().getMiddleName() : "";

        if (middleName != null){
        	p_legalname += (" " + middleName);
        }

        this.veteranName = p_legalname;

        fields.setField((String)fieldMap2015.get("Section1:Question1"),p_legalname);

        fields.setField((String)fieldMap2015.get("Section1:Question2-MaidenName"), voaForm.getSummary().getPersonInfo().getMothersMaidenName());

        if ( voaForm.getSummary().getPersonInfo().getGender() != null) {
             if ("M".equalsIgnoreCase(voaForm.getSummary().getPersonInfo().getGender())){
                fields.setField((String)fieldMap2015.get("Section1:Question3:Male"), "1");}
            else if ("F".equalsIgnoreCase(voaForm.getSummary().getPersonInfo().getGender())){
                fields.setField((String)fieldMap2015.get("Section1:Question3:Female"), "2");
            }
        }

        //Hispanic/spanish/latino?
        String ethnicity =  voaForm.getSummary().getDemographics().getEthnicity();

        if (ethnicity != null ){

             if (ethnicity.equalsIgnoreCase("2135-2")){

                   fields.setField((String)fieldMap2015.get("Section1:Question4:HispanicYes"),"1");

             } else {

                   fields.setField((String)fieldMap2015.get("Section1:Question4:HispanicNo"),"1");
             }
        } else {

            fields.setField((String)fieldMap2015.get("Section1:Question4:HispanicNo"),"1");
      }

        if (voaForm.getSummary().getDemographics().getRaces() != null) {
	        List raceset = voaForm.getSummary().getDemographics().getRaces().getRace();

	        if (raceset!=null){
	             for (Iterator iterator = raceset.iterator(); iterator.hasNext();) {
	                    String race = (String) iterator.next();
	                    //RaceType raceType= race.getRaceType();
	                    if (race != null){
	                           if (RaceType.CODE_AMERICAN_INDIAN_ALASKA.getCode().equals(race))
	                                  fields.setField((String)fieldMap2015.get("Section1:Question5:AlaskaNative"),"1");
	                           else if (RaceType.CODE_ASIAN.getCode().equals(race))
	                                  fields.setField((String)fieldMap2015.get("Section1:Question5:Asian"),"1");
	                           else if (RaceType.CODE_BLACK_AFRICAN.getCode().equals(race))
	                                  fields.setField((String)fieldMap2015.get("Section1:Question5:Black"),"1");
	                           else if (RaceType.CODE_WHITE.getCode().equals(race))
	                                  fields.setField((String)fieldMap2015.get("Section1:Question5:White"),"1");
	                           else if (RaceType.CODE_HAWAIIAN_PACIFIC.getCode().equals(race))
	                                  fields.setField((String)fieldMap2015.get("Section1:Question5:NativeHawaiian"),"1");
	                    }
	             }
	        }
        }


       this.veteranSSN = voaForm.getSummary().getPersonInfo().getSsnText();

       fields.setField((String)fieldMap2015.get("Section1:Question6-SSN"),veteranSSN);

       fields.setField((String)fieldMap2015.get("Section1:Question7-dob"), voaForm.getSummary().getPersonInfo().getDob());
       if (voaForm.getSummary().getPersonInfo().getPlaceOfBirthCity() != null && voaForm.getSummary().getPersonInfo().getPlaceOfBirthState() != null){
    	   fields.setField((String)fieldMap2015.get("Section1:Question7a-pob"),voaForm.getSummary().getPersonInfo().getPlaceOfBirthCity() + ", " + voaForm.getSummary().getPersonInfo().getPlaceOfBirthState());
       }

        // Get the permanent address
       if (voaForm.getSummary().getDemographics().getContactInfo() != null && voaForm.getSummary().getDemographics().getContactInfo().getAddresses() != null &&
    		   voaForm.getSummary().getDemographics().getContactInfo().getAddresses().getAddress() != null) {
	        AddressInfo permAddress = voaForm.getSummary().getDemographics().getContactInfo().getAddresses().getAddress().get(0);

	        if (permAddress != null) {
	            String stateProvince = null;
	            String zipPostalCode = null;
	            if ("USA".equalsIgnoreCase(permAddress.getCountry())) {
	                stateProvince = permAddress.getState();
	                zipPostalCode = permAddress.getZipCode();
	                if ((StringUtils.isNotEmpty(zipPostalCode))
	                        && (StringUtils.isNotEmpty(permAddress.getZipPlus4()))) {
	                    zipPostalCode = zipPostalCode + "-"
	                            + permAddress.getZipPlus4();
	                }
	            } else {
	                stateProvince = permAddress.getProvinceCode();
	                zipPostalCode = permAddress.getPostalCode();
	            }

	            StringBuffer resultBuffer = new StringBuffer();

	            // Append the first 3 lines
	            this.appendAddressPieceOnNewLine(resultBuffer, permAddress.getLine1());
	            this.appendAddressPieceOnNewLine(resultBuffer, permAddress.getLine2());
	            this.appendAddressPieceOnNewLine(resultBuffer, permAddress.getLine3());

	            fields.setField((String)fieldMap2015.get("Section1:Question8-address"),resultBuffer.toString());
	            fields.setField((String)fieldMap2015.get("Section1:Question8a-city"),permAddress.getCity());
	            fields.setField((String)fieldMap2015.get("Section1:Question8b-state"),stateProvince);
	            fields.setField((String)fieldMap2015.get("Section1:Question8c-zip"),zipPostalCode);
	            fields.setField((String)fieldMap2015.get("Section1:Question8d-county"),permAddress.getCounty());
	        }
       }

       if (voaForm.getSummary().getDemographics().getContactInfo() != null && voaForm.getSummary().getDemographics().getContactInfo().getPhones() != null) {
	        List<PhoneInfo> phones = voaForm.getSummary().getDemographics().getContactInfo().getPhones().getPhone();
	        if (phones != null) {
		        String homePhone = null;
		        String cellPhone = null;

		        Iterator<PhoneInfo> phoneIter = phones.iterator();

		             //only one of each allowed
		             boolean homeSet = false;
		             boolean cellSet = false;
		             while (phoneIter.hasNext()) {
		                    PhoneInfo pi = phoneIter.next();

		                    if (!homeSet && pi.getType() != null && pi.getType().equalsIgnoreCase("1")) {

		                           String num = String.format("(%s) %s-%s", pi.getPhoneNumber().substring(0, 3), pi.getPhoneNumber().substring(3, 6),
		                                     pi.getPhoneNumber().substring(6, 10));
		                           homePhone=num;
		                           homeSet = true;
		                    }

		                    if (!cellSet && pi.getType() != null && pi.getType().equalsIgnoreCase("4")) {

		                           String num = String.format("(%s) %s-%s", pi.getPhoneNumber().substring(0, 3), pi.getPhoneNumber().substring(3, 6),
		                                     pi.getPhoneNumber().substring(6, 10));
		                           cellPhone=num;
		                           cellSet = true;
		                    }
		             }


		        if (homePhone != null)
		            fields.setField((String)fieldMap2015.get("Section1:Question8e-hmTel"),homePhone);
		        if (cellPhone != null)
		        	fields.setField((String)fieldMap2015.get("Section1:Question8f-mobileTel"),cellPhone);
		 }
       }

        // Get the contact methods
        EmailCollection emails = voaForm.getSummary().getDemographics().getContactInfo().getEmails();
        String email = null;
        if (emails !=null && emails.getEmail() != null && emails.getEmail().size() > 0) {
             email = emails.getEmail().get(0).getAddress();
        }


        fields.setField((String)fieldMap2015.get("Section1:Question8g-email"),email);

        fields.setField((String)fieldMap2015.get("Section1:Question11-prefFacility"), voaForm.getSummary().getDemographics().getPreferredFacility() != null ? voaForm.getSummary().getDemographics().getPreferredFacility() : "");

        String mstatus = voaForm.getSummary().getDemographics().getMaritalStatus();
        if (mstatus != null) {
            if (mstatus.equalsIgnoreCase("M")) {
                fields.setField((String)fieldMap2015.get("Section1:Question9:Married"), "1");
            } else if (mstatus.equalsIgnoreCase("S")) {
                fields.setField((String)fieldMap2015.get("Section1:Question9:NeverMarried"), "2");
            } else if (mstatus.equalsIgnoreCase("A")) {
                fields.setField((String)fieldMap2015.get("Section1:Question9:Separated"), "3");
            } else if (mstatus.equalsIgnoreCase("W")) {
                fields.setField((String)fieldMap2015.get("Section1:Question9:Widowed"), "4");
            }
            else if (mstatus.equalsIgnoreCase("D")) {
                fields.setField((String)fieldMap2015.get("Section1:Question9:Divorced"), "5");
            }
        }

        //Question 10 - ACA
        if (voaForm.getSummary().getDemographics().isAcaIndicator() != null) {
                Boolean isAca = voaForm.getSummary().getDemographics().isAcaIndicator();

                if (isAca) {
                       fields.setField((String)fieldMap2015.get("Section1:Question10:acaYes"),"1");
                } else {
                       fields.setField((String)fieldMap2015.get("Section1:Question10:acaNo"),"2");
                }
         }


        if (voaForm.getSummary().getDemographics().isAppointmentRequestResponse() != null) {
            Boolean isAppt = voaForm.getSummary().getDemographics().isAppointmentRequestResponse();

            if (isAppt) {
                   fields.setField((String)fieldMap2015.get("Section1:Question12:ApptYes"),"1");
            } else {
                   fields.setField((String)fieldMap2015.get("Section1:Question12:ApptNo"),"2");
            }
         }

    }


    //OMB HCA 2015 Section 2 - Military Service
    private void fillHCAMilitarySection2() throws DocumentException, IOException, Exception {

    	String serviceBranch = voaForm.getSummary().getMilitaryServiceInfo().getMilitaryServiceSiteRecords().
                getMilitaryServiceSiteRecord().get(0).getMilitaryServiceEpisodes().getMilitaryServiceEpisode().get(0).getServiceBranch();
    	String branchName = getBranchName(serviceBranch);

        fields.setField((String)fieldMap2015.get("Section2:Question1-LastSvcBranch"), branchName);

        fields.setField((String)fieldMap2015.get("Section2:Question1A-LastEntryDate"), voaForm.getSummary().getMilitaryServiceInfo().getMilitaryServiceSiteRecords().
                           getMilitaryServiceSiteRecord().get(0).getMilitaryServiceEpisodes().getMilitaryServiceEpisode().get(0).getStartDate());

        fields.setField((String)fieldMap2015.get("Section2:Question1B-LastDischargeDate"), voaForm.getSummary().getMilitaryServiceInfo().getMilitaryServiceSiteRecords().
                           getMilitaryServiceSiteRecord().get(0).getMilitaryServiceEpisodes().getMilitaryServiceEpisode().get(0).getEndDate());


           String disCode = voaForm.getSummary().getMilitaryServiceInfo().getMilitaryServiceSiteRecords().
                   getMilitaryServiceSiteRecord().get(0).getMilitaryServiceEpisodes().getMilitaryServiceEpisode().get(0).getDischargeType();
           String disName = getDischargeType(disCode);


           fields.setField((String)fieldMap2015.get("Section2:Question1C-LastDischargeType"), disName);

          if (voaForm.getSummary().getPurpleHeart() != null && voaForm.getSummary().getPurpleHeart().isIndicator() != null) {
                    Boolean isPh = voaForm.getSummary().getPurpleHeart().isIndicator();
                    if (isPh) {
                           fields.setField((String)fieldMap2015.get("Section2:Question2a-PH:Yes"),"1");
                    } else {
                           fields.setField((String)fieldMap2015.get("Section2:Question2a-PH:No"),"1");
                    }
             }


           if (voaForm.getSummary().getPrisonerOfWarInfo() != null && voaForm.getSummary().getPrisonerOfWarInfo().getPowIndicator() != null) {

                    if (voaForm.getSummary().getPrisonerOfWarInfo().getPowIndicator().equalsIgnoreCase("True")) {
                           fields.setField((String)fieldMap2015.get("Section2:Question2b-POW:Yes"),"1");
                    } else {
                           fields.setField((String)fieldMap2015.get("Section2:Question2b-POW:No"), "1");
                    }
             }

           /*if (voaForm.getSummary().getEnrollmentDeterminationInfo() != null && voaForm.getSummary().getEnrollmentDeterminationInfo().getServiceConnectionAward() != null &&
                           voaForm.getSummary().getEnrollmentDeterminationInfo().getServiceConnectionAward().isServiceConnectedIndicator() != null) {
                    Boolean isSc = voaForm.getSummary().getEnrollmentDeterminationInfo().getServiceConnectionAward().isServiceConnectedIndicator();
                    if (isSc) {
                           fields.setField((String)fieldMap2015.get("Section2:Question2c-Combat:Yes"), "1");
                    } else {
                           fields.setField((String)fieldMap2015.get("Section2:Question2c-Combat:No"), "1");
                    }
           }*/

          if (voaForm.getSummary().getMilitaryServiceInfo() != null && voaForm.getSummary().getMilitaryServiceInfo().isDischargeDueToDisability() != null) {
            Boolean dis = voaForm.getSummary().getMilitaryServiceInfo().isDischargeDueToDisability();
            if (dis) {
                   fields.setField((String)fieldMap2015.get("Section2:Question2d-disability:Yes"), "1");

            } else {
                   fields.setField((String)fieldMap2015.get("Section2:Question2d-disability:No"), "1");

            }
          }


          if( voaForm.getSummary().getEnrollmentDeterminationInfo() != null){

             if (voaForm.getSummary().getEnrollmentDeterminationInfo().getSpecialFactors().isAgentOrangeInd()) {
                    fields.setField((String)fieldMap2015.get("Section2:Question2f-vietnam:Yes"),"1");
             } else {
                    fields.setField((String)fieldMap2015.get("Section2:Question2f-vietnam:No"),"1");
             }


             if (voaForm.getSummary().getEnrollmentDeterminationInfo().getSpecialFactors().isRadiationExposureInd()) {
                    fields.setField((String)fieldMap2015.get("Section2:Question2g-radiation:Yes"),"1");
             } else {
                    fields.setField((String)fieldMap2015.get("Section2:Question2g-radiation:No"),"1");
             }

             if (voaForm.getSummary().getEnrollmentDeterminationInfo().getSpecialFactors().isEnvContaminantsInd()) {

                    fields.setField((String)fieldMap2015.get("Section2:Question2e-gulfwar:Yes"), "1");
             } else {

                    fields.setField((String)fieldMap2015.get("Section2:Question2e-gulfwar:No"), "1");
             }


             if (voaForm.getSummary().getEnrollmentDeterminationInfo().getNoseThroatRadiumInfo() != null) {
                    if (voaForm.getSummary().getEnrollmentDeterminationInfo().getNoseThroatRadiumInfo().getReceivingTreatment().equalsIgnoreCase("True")) {
                           fields.setField((String)fieldMap2015.get("Section2:Question2h-radium:Yes"),"1");

                    } else {
                           fields.setField((String)fieldMap2015.get("Section2:Question2h-radium:No"),"1");

                    }
             }

             //CLV
             if (voaForm.getSummary().getEnrollmentDeterminationInfo().getSpecialFactors().isCampLejeuneInd()) {
                    fields.setField((String)fieldMap2015.get("Section2:Question2i-clv:Yes"),"1");
             } else {
                    fields.setField((String)fieldMap2015.get("Section2:Question2i-clv:No"),"1");
             }

    	}

    }

    // //OMB HCA 2015 Section 3 - Insurance
    private void fillHCAInsuranceSection3() throws DocumentException, IOException {

       if (voaForm.getSummary().getInsuranceList() != null) {
             insuranceInfo = voaForm.getSummary().getInsuranceList().getInsurance();
       }

        if (voaForm.getSummary().getEnrollmentDeterminationInfo() != null && voaForm.getSummary().getEnrollmentDeterminationInfo().isEligibleForMedicaid() != null ) {
            if ( Boolean.TRUE.equals(voaForm.getSummary().getEnrollmentDeterminationInfo().isEligibleForMedicaid())){
                fields.setField((String)fieldMap2015.get("Section3:Question5:MedicaidYes"),"1");
            }
            else if ( Boolean.FALSE.equals(voaForm.getSummary().getEnrollmentDeterminationInfo().isEligibleForMedicaid())){
                   fields.setField((String)fieldMap2015.get("Section3:Question5:MedicaidNo"),"1");
            }
        }

        boolean isMedicare = false;


        int ins_cnt = 0;
        if (insuranceInfo != null && insuranceInfo.size() != 0) {
            boolean isFirst = true;
            boolean addFirst = true;
            for (Iterator iterator = insuranceInfo.iterator(); iterator.hasNext();) {
                InsuranceInfo insurance = (InsuranceInfo) iterator.next();
                if (insurance.getInsuranceMappingTypeName().equalsIgnoreCase("MDCR")) {
                    isMedicare = true;
                    //RTC defect 393424- part a effective date
                    fields.setField((String)fieldMap2015.get("Section3:Question6a-InsEffectiveDate"), insurance.getPartAEffectiveDate());  //RTC fix..
                }
                ins_cnt ++;
                if (isFirst) {
                    fields.setField((String)fieldMap2015.get("Section3:Question1-Insurance Company-address-tel"),insurance.getCompanyName());
                    fields.setField((String)fieldMap2015.get("Section3:Question2-InsPolicyHolder"),insurance.getPolicyHolderName());
                    fields.setField((String)fieldMap2015.get("Section3:Question3-InsPolicyNumber"),insurance.getPolicyNumber());
                    fields.setField((String)fieldMap2015.get("Section3:Question4-InsGroupNum"),insurance.getGroupNumber());

                    isFirst = false;
                } else {
                    PdfPTable table = new PdfPTable(3);
                    table.setKeepTogether(true);
                    table.setWidthPercentage(100f);
                    float[] widths = {45f,30f,25f};
                    table.setWidths(widths);
                    if (addFirst){
                            PdfPCell cell = new PdfPCell(new Paragraph("APPLICATION FOR HEALTH BENEFITS, Continued",FontFactory.getFont(FontFactory.HELVETICA, 11,Font.BOLD, Color.BLACK)));
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            table.addCell(cell);
                            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                            table.addCell(new Phrase("VETERAN'S NAME  (Last, First, Middle)\n\n"+veteranName, font_times));
                            table.addCell( new Phrase("SOCIAL SECURITY NUMBER\n\n"+veteranSSN, font_times));
                            addFirst = false;
                    }
                    PdfPCell cell = new PdfPCell(new Paragraph("SECTION III - INSURANCE INFORMATION (Continuation #"+ins_cnt+")",FontFactory.getFont(FontFactory.HELVETICA, 8,Font.BOLD, Color.BLACK)));
                    cell.setColspan(3);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell.setBackgroundColor(Color.lightGray);
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph("1.HEALTH INSURANCE COMPANY NAME,ADDRESS AND TELEPHONE NUMBER\n"+insurance.getCompanyName(), font_courier));
                    cell.setColspan(3);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);

                    //RTC Defect - 393424: prevent null values from displaying
                    String polHolder = insurance.getPolicyHolderName() != null ? insurance.getPolicyHolderName() : "";
                    table.addCell(new Phrase("2.NAME OF POLICY HOLDER\n"+polHolder, font_courier));

                    String polNum = insurance.getPolicyNumber() != null ? insurance.getPolicyNumber() : "";
                    table.addCell(new Phrase("3.POLICY NUMBER\n"+polNum, font_courier));

                    String polGrp = insurance.getGroupNumber() != null ? insurance.getGroupNumber() : "";
                    table.addCell(new Phrase("4.GROUP CODE\n"+ polGrp, font_courier));
                    additionalInsDocument.add(table);
                }
            }
        }

        if (isMedicare) {
               fields.setField((String)fieldMap2015.get("Section3:Question6:HospitalInsPartAYes"), "1");

        } else {
               fields.setField((String)fieldMap2015.get("Section3:Question6:HospitalInsPartANo"), "1");
        }

    }

   //OMB 2015 - Section 4- Spouse and Dependent
    private void fillHCADependentInfotmationSection4() throws DocumentException, IOException {

          if (voaForm.getSummary().getFinancialsInfo() != null && voaForm.getSummary().getFinancialsInfo().getFinancialStatement() != null &&
                       voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getSpouseFinancialsList() != null &&
                       voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getSpouseFinancialsList().getSpouseFinancials() != null &&
                                    voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getSpouseFinancialsList().getSpouseFinancials().get(0) != null) {

                       SpouseInfo spouseInfo = voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getSpouseFinancialsList().getSpouseFinancials().get(0).getSpouse();
                       SpouseFinancialsInfo spouseFins = voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getSpouseFinancialsList().getSpouseFinancials().get(0);

                        fields.setField((String)fieldMap2015.get("Section3:Question6b-veteranName"),veteranName);
                        fields.setField((String)fieldMap2015.get("Section3:Question6c-vetSSN"),voaForm.getSummary().getPersonInfo().getSsnText());

      			        if (spouseInfo.getMiddleName() != null){
                          fields.setField((String)fieldMap2015.get("Section4:Question1-SpouseName"),spouseInfo.getFamilyName() + ", " + spouseInfo.getGivenName() + " " + spouseInfo.getMiddleName());
      			        }
                        else {
                          fields.setField((String)fieldMap2015.get("Section4:Question1-SpouseName"),spouseInfo.getFamilyName() + ", " + spouseInfo.getGivenName());
                        }
   			         fields.setField((String)fieldMap2015.get("Section4:Question1A-SSN"),spouseInfo.getSsns().getSsn().get(0).getSsnText());
   			         fields.setField((String)fieldMap2015.get("Section4:Question1B-DOB"),spouseInfo.getDob());
   			         fields.setField((String)fieldMap2015.get("Section4:Question1C-DOM"),spouseInfo.getStartDate());

   			         String spAddr = spouseInfo.getAddress().getLine1() + ", " + spouseInfo.getAddress().getCity() + ", " + spouseInfo.getAddress().getState() + " " + spouseInfo.getAddress().getZipCode();
   			         String spPhone = spouseInfo.getAddress().getPhoneNumber() != null ? spouseInfo.getAddress().getPhoneNumber() : "";

   			         fields.setField((String)fieldMap2015.get("Section4:Question1D-addressTel"),spAddr+"\n"+spPhone);

   			         if (spouseFins.isContributedToSpousalSupport() != null) {

                           Boolean isContrib = spouseFins.isContributedToSpousalSupport();
                           if (isContrib) {
                                  fields.setField((String)fieldMap2015.get("Section4:Question3-finSupport:Yes"),"1");
                           }
   			         }
          }


        int dep_cnt = 0;
        int add_cnt = 0;
        DependentFinancialsInfo dependent = null;

        if (voaForm.getSummary().getFinancialsInfo() !=  null && voaForm.getSummary().getFinancialsInfo().getFinancialStatement() != null &&
                 voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getDependentFinancialsList() != null &&
                 voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getDependentFinancialsList().getDependentFinancials() != null) {


           List<DependentFinancialsInfo> dependents = voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getDependentFinancialsList().getDependentFinancials();

           boolean isFirst = true;
           boolean addFirst = true;
           for (Iterator itr = dependents.iterator(); itr.hasNext();) {
                dependent = (DependentFinancialsInfo) itr.next();


               if ( dependent != null) {
               dep_cnt++;
                   if (isFirst){
                       fields.setField((String)fieldMap2015.get("Section4:Question2-ChildName"), dependent.getDependentInfo().getFamilyName() + ", " +
                                    dependent.getDependentInfo().getGivenName() + " " + dependent.getDependentInfo().getMiddleName());

                       if (dependent.getDependentInfo().getRelationship() != null){
                              String rship = dependent.getDependentInfo().getRelationship();
                              if( Relationship.CODE_SON.getCode().equals(rship) )
                                  fields.setField((String)fieldMap2015.get("Section4:Question2D:Son"),"1");
                              else if ( Relationship.CODE_DAUGHTER.getCode().equals(rship) )
                                   fields.setField((String)fieldMap2015.get("Section4:Question2D:Daughter"),"1");
                              else if ( Relationship.CODE_STEPSON.getCode().equals(rship))
                                     fields.setField((String)fieldMap2015.get("Section4:Question2D:Stepson"),"1");
                              else if ( Relationship.CODE_STEPDAUGHTER.getCode().equals(rship) )
                                   fields.setField((String)fieldMap2015.get("Section4:Question2D:Stepdaughter"),"1");
                       }

                       fields.setField((String)fieldMap2015.get("Section4:Question2B-ChildSSN"),dependent.getDependentInfo().getSsns().getSsn().get(0).getSsnText());
                       fields.setField((String)fieldMap2015.get("Section4:Question2C-DateChildBecameDependent"), dependent.getDependentInfo().getStartDate());
                       fields.setField((String)fieldMap2015.get("Section4:Question2A-ChildDOB"),dependent.getDependentInfo().getDob());

                       if (dependent.isIncapableOfSelfSupport() !=null && dependent.isIncapableOfSelfSupport().booleanValue())
                           fields.setField((String)fieldMap2015.get("Section4:Question2E-DisableBefore18:Yes"),"1");
                       else
                           fields.setField((String)fieldMap2015.get("Section4:Question2E-DisableBefore18:No"),"1");

                       if (dependent.isAttendedSchool()!=null && dependent.isAttendedSchool().booleanValue())
                           fields.setField((String)fieldMap2015.get("Section4:Question2F-AttendedSchool:Yes"),"1");
                       else
                           fields.setField((String)fieldMap2015.get("Section4:Question2F-AttendedSchool:No"),"1");


                       if (dependent.isLivedWithPatient()!= null && !dependent.isLivedWithPatient().booleanValue()) {
                              fields.setField((String)fieldMap2015.get("Section4:Question3-finSupport:Yes"),"1");  //Did you provide support Yes
                       }

                       fields.setField((String)fieldMap2015.get("Section4:Question2G-expensesByDepChild"),dependent.getExpenses() !=null && dependent.getExpenses().
                                    getExpense()!=null? dependent.getExpenses().getExpense().get(0).getAmount().toString():"");

                       isFirst = false;
                   }
                   else{
                        add_cnt ++;
                        PdfPTable table=new PdfPTable(5);
                        table.setKeepTogether(true);
                        table.setWidthPercentage(100f);
                        table.setSpacingAfter(0f);
                        float[] widths = {23f,22f,5f,25f,25f};
                               table.setWidths(widths);
                        if ( add_cnt % 4 == 1 || addFirst ){
                                      PdfPCell cell = new PdfPCell(new Paragraph("APPLICATION FOR HEALTH BENEFITS, Continued",FontFactory.getFont(FontFactory.HELVETICA, 11,Font.BOLD, Color.BLACK)));
                                      cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                      cell.setColspan(2);
                                      table.addCell(cell);
                                      cell = new PdfPCell(new Paragraph("VETERAN'S NAME  (Last, First, Middle)\n\n"+veteranName, font_times));
                                      cell.setColspan(2);
                                      cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                                      table.addCell(cell);
                                      table.addCell( new Phrase("SOCIAL SECURITY NUMBER\n\n"+veteranSSN, font_times));
                                      addFirst = false;
                              }
                       PdfPCell cell = new PdfPCell (new Paragraph ("Section IV - DEPENDENT INFORMATION (Child #"+dep_cnt+")",FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD,Color.BLACK )));
                       cell.setColspan (5);
                       cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                       cell.setBackgroundColor (Color.LIGHT_GRAY);
                       table.addCell (cell);

                       String depname = dependent.getDependentInfo().getFamilyName() + ", " +
                                    dependent.getDependentInfo().getGivenName() + " " + dependent.getDependentInfo().getMiddleName();
                       cell = new PdfPCell(new Phrase("2.CHILD'S NAME(Last, First , Middle Name)\n\n"+depname, font_courier));
                       cell.setColspan(3);
                       table.addCell(cell);

                       String deprelation="";

                       String rship = dependent.getDependentInfo().getRelationship();
                       if( Relationship.CODE_SON.getCode().equals(rship) )
                              deprelation = "SON";
                       else if ( Relationship.CODE_DAUGHTER.getCode().equals(rship) )
                              deprelation = "DAUGHTER";
                       else if ( Relationship.CODE_STEPSON.getCode().equals(rship))
                              deprelation = "STEPSON";
                       else if ( Relationship.CODE_STEPDAUGHTER.getCode().equals(rship) )
                              deprelation = "STEPDAUGHTER";

                       cell = new PdfPCell(new Phrase("2A.CHILD'S DATE OF BIRTH(mm/dd/yyyy)\n\n"+dependent.getDependentInfo().getDob(), font_courier));
                       cell.setColspan(2);
                       table.addCell(cell);

                       String depssn = dependent.getDependentInfo().getSsns().getSsn().get(0).getSsnText();
                       table.addCell(new Phrase("2B.CHILD SOCIAL SECURITY NUMBER\n\n"+depssn, font_courier));

                       cell = new PdfPCell(new Phrase("2C.DATE CHILD BECAME YOUR DEPENDENT (mm/dd/yyyy)\n\n"+dependent.getDependentInfo().getStartDate(), font_courier));
                       cell.setColspan(2);
                       table.addCell(cell);

                       cell = new PdfPCell(new Phrase("2D.CHILD'S RELATIONSHIP TO YOU\n\n"+deprelation, font_courier));
                       cell.setColspan(2);
                       table.addCell(cell);


                       String disable = dependent.isIncapableOfSelfSupport()!=null && dependent.isIncapableOfSelfSupport().booleanValue()? "YES":"NO";
                       cell = new PdfPCell(new Phrase("2E.WAS CHILD PERMANENTLY AND TOTALY DISABLED BEFORE THE AGE OF 18?\n\n"+disable, font_courier));
                       cell.setColspan(3);
                       table.addCell(cell);

                       String attendschool = dependent.isAttendedSchool()!=null && dependent.isAttendedSchool().booleanValue()? "YES":"NO";
                       cell = new PdfPCell(new Phrase("2F.IF CHILD IS BETWEEN 18 and 23 YEARS OF AGE,DID CHILD ATTEND SCHOOL LAST CALENDAR YEAR?\n\n"+attendschool, font_courier));
                       cell.setColspan(2);
                       table.addCell(cell);

                       //RTC defect 393424- fix improper display of data
                       String childschool = "";
                       childschool= dependent.getExpenses() !=null && dependent.getExpenses().getExpense()!=null? dependent.getExpenses().getExpense().get(0).getAmount().toString() : "";

                       //RTC defect 393424- fix question description
                       String providedSupport = dependent.isLivedWithPatient()!= null && !dependent.isLivedWithPatient().booleanValue() ? "YES" : "NO";

                       cell = new PdfPCell(new Phrase("3.IF YOUR SPOUSE OR DEPENDENT CHILD DID NOT LIVE WITH YOU LAST YEAR, DID YOU PROVIDE SUPPORT?\n\n"+ providedSupport, font_courier));
                       cell.setColspan(3);
                       table.addCell(cell);


                       cell = new PdfPCell(new Phrase("2G.EXPENSES PAID BY YOUR DEPENDENT CHILD FOR COLLEGE,VOCATIONAL REHABILITATION ORTRAINING(e.g.,tuition,books,materials)\n\n"+"$     "+childschool, font_courier));
                       cell.setColspan(2);
                       table.addCell(cell);
                       additionalChildDocument.add(table);
                   }
               }
           }
       }
   }

   //OMB 2015 Form - Incomes and ExpensesSection (Sections 5 and 6)
   private void fillHCAIncomeSection5AndExpenseSection6() throws DocumentException, IOException
        {
           DependentFinancials df = null;
           Dependent dependent = null;

           if (voaForm.getSummary().getFinancialsInfo() != null &&
                        voaForm.getSummary().getFinancialsInfo().getIncomeTest() != null) {

                  if (voaForm.getSummary().getFinancialsInfo().getFinancialStatement() != null &&
                               voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getIncomes() != null){

                        List<IncomeInfo> incomes = voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getIncomes().getIncome();

                                    Iterator<IncomeInfo> incomeIter = incomes.iterator();
                                    while (incomeIter.hasNext()) {
                                           IncomeInfo income = incomeIter.next();

                                           //gross income
                                           if (income != null && income.getType().equalsIgnoreCase("7")) {

                                                  fields.setField((String)fieldMap2015.get("Section5:Question1:VeteranGrossIncome"),income.getAmount().toString());
                                           }
                                           //property
                                           if (income != null && income.getType().equalsIgnoreCase("13")) {
                                                  fields.setField((String)fieldMap2015.get("Section5:Question2:VeteranNetIncome"),income.getAmount().toString());
                                           }
                                           //other
                                           if (income != null && income.getType().equalsIgnoreCase("10")) {
                                                  fields.setField((String)fieldMap2015.get("Section5:Question3:VeteranOtherIncome"),income.getAmount().toString());
                                           }
                                    }
                   }

                  //Expenses
                  if (voaForm.getSummary().getFinancialsInfo() != null && voaForm.getSummary().getFinancialsInfo().getFinancialStatement() != null && voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getExpenses() != null &&
                               voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getExpenses().getExpense() != null) {


                        List<ExpenseInfo> expenses = voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getExpenses().getExpense();

                        Iterator<ExpenseInfo> expenseIter = expenses.iterator();

                        while (expenseIter.hasNext()) {

                               ExpenseInfo expense = expenseIter.next();
                               //medical
                               if (expense != null && expense.getExpenseType() != null &&
                                             expense.getExpenseType().equalsIgnoreCase("18")) {

                                      fields.setField((String)fieldMap2015.get("Section6:Question1:Non_reimb-Medical-exp"),expense.getAmount().toString());
                               }
                               //education
                               if (expense != null && expense.getExpenseType() != null &&
                                             expense.getExpenseType().equalsIgnoreCase("19")) {  //RTC item - 393424 - fix expense type
                                      fields.setField((String)fieldMap2015.get("Section6:Question2:Funeral-Burial-exp"),expense.getAmount().toString());

                               }

                               if (expense != null && expense.getExpenseType() != null &&
                                             expense.getExpenseType().equalsIgnoreCase("3")) { //RTC item - 393424 - fix expense type
                                      fields.setField((String)fieldMap2015.get("Section6:Question3:College-voc-exp"),expense.getAmount().toString());
                               }
                        }
                  }


                  if (voaForm.getSummary().getFinancialsInfo().getFinancialStatement() != null && voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getSpouseFinancialsList() != null &&
                               voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getSpouseFinancialsList().getSpouseFinancials() != null) {


                        SpouseFinancialsInfo spouseFins = voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getSpouseFinancialsList().getSpouseFinancials().get(0);

                        if (spouseFins.getIncomes() != null && spouseFins.getIncomes().getIncome() != null) {
                               List<IncomeInfo> spouseIncomes = spouseFins.getIncomes().getIncome();
                               Iterator<IncomeInfo> finsIter = spouseIncomes.iterator();

                               while (finsIter.hasNext()) {
                                      IncomeInfo income = finsIter.next();

                                      //gross
                                      if (income.getType().equalsIgnoreCase("7")) {
                                             fields.setField((String)fieldMap2015.get("Section5:Question1:SpouseGrossIncome"),income.getAmount().toString());
                                      }
                                      //property
                                      if (income.getType().equalsIgnoreCase("13")) {
                                             fields.setField((String)fieldMap2015.get("Section5:Question2:SpouseNetIncome"),income.getAmount().toString());
                                      }
                                      //all other
                                      if (income.getType().equalsIgnoreCase("10")) {
                                             fields.setField((String)fieldMap2015.get("Section5:Question3:SpouseOtherIncome"),income.getAmount().toString());
                                      }

                               }
                        }
                  }



                  if (voaForm.getSummary().getFinancialsInfo().getFinancialStatement() != null && voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getDependentFinancialsList() != null &&
                               voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getDependentFinancialsList().getDependentFinancials() != null) {

                        List<DependentFinancialsInfo> dependents = voaForm.getSummary().getFinancialsInfo().getFinancialStatement().getDependentFinancialsList().getDependentFinancials();
                        Iterator<DependentFinancialsInfo> dependIter = dependents.iterator();
                        boolean isFirst_8 = true;
                    boolean isFirst_10 = true;
                    boolean addFirst = true;
                    int childCnt = 0;
                    int add_child_cnt = 0;

                        while(dependIter.hasNext()) {

                               DependentFinancialsInfo depFin = dependIter.next();



                  if ( depFin != null && depFin.getIncomes() != null && depFin.getIncomes().getIncome() != null) {
                           childCnt ++;
                              if (isFirst_8) {



                              List<IncomeInfo> incomes = depFin.getIncomes().getIncome();

                              Iterator<IncomeInfo> incomeIter = incomes.iterator();
                                            while (incomeIter.hasNext()) {
                                                   IncomeInfo income = incomeIter.next();

                                                   if (income != null && income.getType().equalsIgnoreCase("7")) {
                                                          fields.setField((String)fieldMap2015.get("Section5:Question1:ChildGrossIncome"),income.getAmount().toString());
                                                   }

                                                   if (income != null && income.getType().equalsIgnoreCase("13")) {
                                                          fields.setField((String)fieldMap2015.get("Section5:Question2:ChildNetIncome"),income.getAmount().toString());
                                                   }

                                                   if (income != null && income.getType().equalsIgnoreCase("10")) {
                                                          fields.setField((String)fieldMap2015.get("Section5:Question3:ChildOtherIncome"),income.getAmount().toString());
                                                   }

                                            }
                                            isFirst_8 = false;
                                     }
                                     else {



                                            add_child_cnt ++;
                                            if (add_child_cnt % 9 == 1  || addFirst ){
                                                   additionalChildDocument.newPage();
                                                   PdfPTable table=new PdfPTable(3);
                                             table.setWidthPercentage(100f);
                                             table.setSpacingAfter(0f);
                                             table.setKeepTogether(true);
                                              float[] widths = {45f,30f,25f};
                                              table.setWidths(widths);
                                              PdfPCell cell = new PdfPCell(new Paragraph("APPLICATION FOR HEALTH BENEFITS, Continued",FontFactory.getFont(FontFactory.HELVETICA, 11,Font.BOLD, Color.BLACK)));
                                              cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                              table.addCell(cell);
                                              cell = new PdfPCell(new Paragraph("VETERAN'S NAME  (Last, First, Middle)\n\n"+veteranName, font_times));
                                              cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                                              table.addCell(cell);
                                              table.addCell( new Phrase("SOCIAL SECURITY NUMBER\n\n"+veteranSSN, font_times));
                                              cell = new PdfPCell (new Paragraph ("Section V - PREVIOUS CALENDAR YEAR GROSS ANNUAL INCOME OF VETERAN, SPOUSE AND DEPENDENT CHILDREN (Continued)",FontFactory.getFont(FontFactory.HELVETICA, 8,Font.BOLD, Color.BLACK )));
                                              cell.setColspan (3);
                                              cell.setHorizontalAlignment (Element.ALIGN_CENTER);
                                              cell.setBackgroundColor (Color.LIGHT_GRAY); //cell.setPadding (10.0f);
                                              table.addCell (cell);
                                              addFirst = false;
                                              additionalChildDocument.add(table);
                                      }

                                    List<IncomeInfo> incomes = depFin.getIncomes().getIncome();

                                    Iterator<IncomeInfo> incomeIter = incomes.iterator();
                                          while (incomeIter.hasNext()) {

                                             IncomeInfo income = incomeIter.next();

                                             PdfPTable table=new PdfPTable(3);
                                             table.setWidthPercentage(100f);
                                             table.setKeepTogether(true);
                                           float[] widths = {34f,33f,33f};
                                            table.setWidths(widths);
                                            table.setSpacingAfter(0f);
                                           PdfPCell cell = new PdfPCell (new Paragraph ("Child #"+childCnt,FontFactory.getFont(FontFactory.HELVETICA, 8,Font.BOLD, Color.BLACK )));
                                           cell.setColspan (3);
                                            cell.setHorizontalAlignment (Element.ALIGN_CENTER);
                                           table.addCell (cell);

                                           //RTC defect 393424- form elements not displayed

                                    	   String grossincome = (income != null) && (income.getType().equalsIgnoreCase("7")) ? income.getAmount().toString() : "";
                                           table.addCell(new Phrase("1.GROSS ANNUAL INCOME FROM EMPLOYMENT  * (wages,bonuses,tips,etc.) EXCLUDING INCOME FROM YOUR FARM,RANCH,PROPERTYOR BUSINESS\n\n"+ grossincome, font_courier));

                                    	   String farmRanchIncome = income != null && income.getType().equalsIgnoreCase("13") ? income.getAmount().toString() : "";
                                           table.addCell(new Phrase("2.NET INCOME FROM YOUR FARM,RANCH,PROPERTY,OR BUSINESS\n\n"+farmRanchIncome, font_courier));

                                           String otherIncome = (income != null) && (income.getType().equalsIgnoreCase("10")) ? income.getAmount().toString() : "";
                                           table.addCell(new Phrase("3.LIST OTHER INCOME AMOUNTS (eg.Social Security, compensation, pension interest,dividends),EXCLUDING WELFARE.\n\n"+ otherIncome, font_courier));

                                            additionalChildDocument.add(table);
                                     }
                              } // not first child
                } // end dep financials
       } // end dependent iterator

      } // end dependents
     } // end disclose not null
   }


    //Section 7-signature date -2015
    private void fillHCASignatureSection7() throws DocumentException, IOException {
        fields.setField((String) fieldMap2015.get("Section7:signDate"), DateUtils.format(app.getResponseTimeStamp(), null));
    }


   private String getBranchName(String serviceBranch){

 		String branchName ="";

 		if (serviceBranch.equals("1")) {
 			branchName = "ARMY";
 		}
 		else if (serviceBranch.equals("2")){
 			branchName = "AIR FORCE";
 		}
 		else if (serviceBranch.equals("3")){
 			branchName = "NAVY";
 		}
 		else if (serviceBranch.equals("4")){
 			branchName = "MARINE CORPS";
 		}
 		else if (serviceBranch.equals("5")){
 			branchName = "COAST GUARD";
 		}
 		else if (serviceBranch.equals("6")){
 			branchName = "OTHER";
 		}
 		else if (serviceBranch.equals("7")){
 			branchName = "MERCHANT SEAMAN";
 		}
 		else if (serviceBranch.equals("8")){
 			branchName = "B.E.C.";
 		}
 		else if (serviceBranch.equals("9")){
 			branchName = "USPHS";
 		}
 		else if (serviceBranch.equals("10")){
 			branchName = "NOAA";
 		}
		else if (serviceBranch.equals("11")){
 			branchName = "F.COMMONWEALTH";
 		}
		else if (serviceBranch.equals("12")){
 			branchName = "F.GUERILLA";
 		}
		else if (serviceBranch.equals("13")){
 			branchName = "F.SCOUTS NEW";
 		}
		else if (serviceBranch.equals("14")){
 			branchName = "F.SCOUTS OLD";
 		}

 		return branchName;
    }

    private String getDischargeType(String disCode){
 	   String disName="";
 	   if (disCode.equals("1")){
 		   disName = "HONORABLE";
 	   }
 	   else if (disCode.equals("2")){
 		   disName = "DISHONORABLE";
 	   }
 	   else if (disCode.equals("3")){
 		   disName = "GENERAL";
 	   }
 	   else if (disCode.equals("4")){
 		   disName = "OTHER THAN HONORABLE";
 	   }
 	   else if (disCode.equals("5")){
 		   disName = "UNDESIRABLE";
 	   }
 	   else if (disCode.equals("6")){
 		   disName = "BAD CONDUCT";
 	   }
 	   else if (disCode.equals("8")){
 		   disName = "DISHONORABLE-VA";
 	   }
 	   else if (disCode.equals("9")){
 		   disName = "HONORABLE-VA";
 	   }

 	   return disName;

    }


    /**
     * Fill each section of the fillable PDF (year 2011 or earlier versions), and create additional files if
     * necessary. If additional files are necessary, the two PDFs are
     * concatenated.
     *
     */
    public void get1010EZ() throws Exception {
        try {

            // Set section 1 - General Information
            fillSection1();

            // Set section 2 - Insurance Information
            fillSection2();

            // Section 3 - Employment Information
            fillSection3();

             // Section 4 - Military Service Information
            fillSection4();

            // Section 5 - Financial Disclosure
            fillSection5();

             // Section 7 - Spouse/Dependent Financial Information
             fillSection7();

             // Section 8 - Previous Calendar Year Gross Annual Income of Veteran, Spouse, and Dependent Children
             // Section 9 - Previous Calendar Year Deductible Expenses
             // Section 10 - Previous Calendar Year Net Worth
             // fill section 8, 9 and 10
             fillSection8_9_10();

            // Section 12 - Assignment of Benefits
            fillSection12();

            stamper.setFormFlattening(true);
            reader.close();
            stamper.close();

            if (isAdditionalDocumentInsNeeded) {
                additionalInsDocument.close();
                outAdditionalInsForm.close();
            }
            if (isAdditionalDocumentChildNeeded){
            additionalChildDocument.close();
                outAdditionalChildForm.close();
            }
            if (isAdditionalDocumentInsNeeded || isAdditionalDocumentChildNeeded)
            outStaticForm.close();
            else
            outCombinedForm.close();

        } catch (Exception e) {
            e.printStackTrace();
            reader.close();
            try {
            if (isAdditionalDocumentInsNeeded) {
                    additionalInsDocument.close();
                    outAdditionalInsForm.close();
                }
                if (isAdditionalDocumentChildNeeded){
                    additionalChildDocument.close();
                    outAdditionalChildForm.close();
                }
                if (isAdditionalDocumentInsNeeded || isAdditionalDocumentChildNeeded)
                    outStaticForm.close();
                else
                    outCombinedForm.close();
                stamper.close();
            } catch (Exception e2) {
                e.printStackTrace();
            }
        } finally {
            reader.close();
            try {
            if (isAdditionalDocumentInsNeeded) {
                    additionalInsDocument.close();
                    outAdditionalInsForm.close();
                }
                if (isAdditionalDocumentChildNeeded){
                    additionalChildDocument.close();
                    outAdditionalChildForm.close();
                }
                if (isAdditionalDocumentInsNeeded || isAdditionalDocumentChildNeeded)
                    outStaticForm.close();
                else
                    outCombinedForm.close();
                stamper.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // Concatenate pdfs
        try {
              if (isAdditionalDocumentInsNeeded || isAdditionalDocumentChildNeeded) {
                log.debug("Concatenating the pdf documents in 1010EZ");
                List pdfs;
                OutputStream output;
                FileInputStream inStaticForm = null;
                FileInputStream inAdditionalInsForm = null;
                FileInputStream inAdditionalChildForm = null;
                pdfs = new ArrayList();
                File file1 = new File(this.getOutputFilePath() + this.getFormFileName());
                inStaticForm = new FileInputStream(file1);
                pdfs.add(inStaticForm);

                File file2 =null;
                File file3 = null;
                if (isAdditionalDocumentInsNeeded){
                    file2 = new File(this.getOutputFilePath()+ this.getAdditionalInsuranceFileName());
                    inAdditionalInsForm = new FileInputStream(file2);
                    pdfs.add(inAdditionalInsForm);
                }
                if (isAdditionalDocumentChildNeeded){
                    file3 = new File(this.getOutputFilePath()+ this.getAdditionalDependentFileName());
                    inAdditionalChildForm = new FileInputStream(file3);
                    pdfs.add(inAdditionalChildForm);
                }
                output = new FileOutputStream(this.getOutputFilePath() + this.getFinalFileName());
                concatPDFs(pdfs, output, true);
                output.close();
                inStaticForm.close();

                if (inAdditionalInsForm != null)
                    inAdditionalInsForm.close();
                if (inAdditionalChildForm!=null)
                    inAdditionalChildForm.close();

                if (file1.exists()) file1.delete();
                if (isAdditionalDocumentInsNeeded){
                    if (file2.exists()) file2.delete();
                }
                if (isAdditionalDocumentChildNeeded){
                    if (file3.exists()) file3.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * Initialize map containing all field names in the fillable PDF for older form such as 2011 version
     *
     */
    private void initializeFieldMap() {

       //Section 1
        fieldMap.put("Section1:Question1", "Text1");
        fieldMap.put("Section1:Question2", "Text2");
        //fieldMap.put("Section1:Question3", "Text3");
        fieldMap.put("Section1:Question4:Male", "Check Box20");
        fieldMap.put("Section1:Question4:Female", "Check Box21");
        fieldMap.put("Section1:Question5:Yes", "Check Box22");
        fieldMap.put("Section1:Question5:No", "Check Box23");
        fieldMap.put("Section1:Question6:AlaskaNative", "Check Box24");
        fieldMap.put("Section1:Question6:Asian", "Check Box25");
        fieldMap.put("Section1:Question6:White", "Check Box26");
        fieldMap.put("Section1:Question6:Black", "Check Box27");
        fieldMap.put("Section1:Question6:NativeHawaiian", "Check Box28");
        fieldMap.put("Section1:Question7", "Text4");
        fieldMap.put("Section1:Question8", "Text7");
        fieldMap.put("Section1:Question9", "Text5");
        fieldMap.put("Section1:Question9A", "Text8");
        fieldMap.put("Section1:Question10", "Text6");
        fieldMap.put("Section1:Question11", "Text10");
        fieldMap.put("Section1:Question11A", "Text11");
        fieldMap.put("Section1:Question11B", "Text12");
        fieldMap.put("Section1:Question11C", "Text13");
        fieldMap.put("Section1:Question11D", "Text14");
        fieldMap.put("Section1:Question11E", "Text15");
        fieldMap.put("Section1:Question11F", "Text16");
        fieldMap.put("Section1:Question11G", "Text17");
        fieldMap.put("Section1:Question11H", "Text18");
        fieldMap.put("Section1:Question12:HealthServices", "Check Box29");
        fieldMap.put("Section1:Question12:NursingHome", "Check Box30");
        fieldMap.put("Section1:Question12:Domiciliary", "Check Box31");
        fieldMap.put("Section1:Question12:Dental", "Check Box32");
        fieldMap.put("Section1:Question13", "Text19");
        fieldMap.put("Section1:Question14:Yes", "Check Box33");
        fieldMap.put("Section1:Question14:No", "Check Box34");
        fieldMap.put("Section1:Question15:Yes", "Check Box35");
        fieldMap.put("Section1:Question15:No", "Check Box36");
        fieldMap.put("Section1:Question15:Location","Text22");
        fieldMap.put("Section1:Question16:Married", "Check Box37");
        fieldMap.put("Section1:Question16:NeverMarried", "Check Box38");
        fieldMap.put("Section1:Question16:Separated", "Check Box39");
        fieldMap.put("Section1:Question16:Widowed", "Check Box40");
        fieldMap.put("Section1:Question16:Divorced", "Check Box41");
        fieldMap.put("Section1:Question16:Unknown", "Check Box42");
        fieldMap.put("Section1:Question17", "Text45");
        fieldMap.put("Section1:Question17A", "Text46");
        fieldMap.put("Section1:Question17B", "Text47");
        fieldMap.put("Section1:Question18", "Text50");
        fieldMap.put("Section1:Question18A", "Text48");
        fieldMap.put("Section1:Question18B", "Text49");
        fieldMap.put("Section1:Question19:EmergencyContact", "Check Box43");
        fieldMap.put("Section1:Question19:NextOfKin", "Check Box44");

        // Section 2
        fieldMap.put("Section2:Question1:Yes", "Check Box61");
        fieldMap.put("Section2:Question1:No", "Check Box62");
        fieldMap.put("Section2:Question2", "Text53");
        fieldMap.put("Section2:Question3", "Text54");
        fieldMap.put("Section2:Question4", "Text55");
        fieldMap.put("Section2:Question5", "Text56");
        fieldMap.put("Section2:Question6:Yes", "Check Box63");
        fieldMap.put("Section2:Question6:No", "Check Box64");
        fieldMap.put("Section2:Question7:Yes", "Check Box65");
        fieldMap.put("Section2:Question7:No", "Check Box66");
       // fieldMap.put("Section2:Question7A", "Text57");  //TODO fix
        fieldMap.put("Section2:Question8:Yes", "Check Box68");
        fieldMap.put("Section2:Question8:No", "Check Box67");
        fieldMap.put("Section2:Question8A", "Text58");
        fieldMap.put("Section2:Question9", "Text60");
        fieldMap.put("Section2:Question10", "Text59");
        fieldMap.put("Section2:Question11:Yes", "Check Box69");
        fieldMap.put("Section2:Question11:No", "Check Box70");
        fieldMap.put("Section2:Question12:Yes", "Check Box71");
        fieldMap.put("Section2:Question12:No", "Check Box72");

        // Section 3
        fieldMap.put("Section3:Question1:FullTime", "Check Box73");
        fieldMap.put("Section3:Question1:NotEmployed", "Check Box74");
        fieldMap.put("Section3:Question1:Retired", "Check Box75");
        fieldMap.put("Section3:Question1:PartTime", "Check Box76");
        fieldMap.put("Section3:Question1:RetirementDate", "Text9");
        fieldMap.put("Section3:Question1A", "Text81");
        fieldMap.put("Section3:Question2:FullTime", "Check Box77");
        fieldMap.put("Section3:Question2:NotEmployed", "Check Box78");
        fieldMap.put("Section3:Question2:Retired", "Check Box80");
        fieldMap.put("Section3:Question2:PartTime", "Check Box79");
        fieldMap.put("Section3:Question2:RetirementDate", "Text20");
        fieldMap.put("Section3:Question2A", "Text82");

        // Section 4
        fieldMap.put("Section4:Question1", "Text83");
        fieldMap.put("Section4:Question1A", "Text84");
        fieldMap.put("Section4:Question1B", "Text85");
        fieldMap.put("Section4:Question1C", "Text86");
        fieldMap.put("Section4:Question1D", "Text87");
        fieldMap.put("Section4:Question2A:Yes", "Check Box88");
        fieldMap.put("Section4:Question2A:No", "Check Box97");
        fieldMap.put("Section4:Question2B:Yes", "Check Box89");
        fieldMap.put("Section4:Question2B:No", "Check Box96");
        fieldMap.put("Section4:Question2C:Yes", "Check Box90");
        fieldMap.put("Section4:Question2C:No", "Check Box110");
        fieldMap.put("Section4:Question2C1", "Text21");
        fieldMap.put("Section4:Question2D:Yes", "Check Box91");
        fieldMap.put("Section4:Question2D:No", "Check Box94");
        fieldMap.put("Section4:Question2E:Yes", "Check Box92");
        fieldMap.put("Section4:Question2E:No", "Check Box93");
        fieldMap.put("Section4:Question2E1:Yes", "Check Box98");
        fieldMap.put("Section4:Question2E1:No", "Check Box99");
        fieldMap.put("Section4:Question2F:Yes", "Check Box100");
        fieldMap.put("Section4:Question2F:No", "Check Box101");
        fieldMap.put("Section4:Question2G:Yes", "Check Box102");
        fieldMap.put("Section4:Question2G:No", "Check Box103");
        fieldMap.put("Section4:Question2H:Yes", "Check Box109");
        fieldMap.put("Section4:Question2H:No", "Check Box104");
        fieldMap.put("Section4:Question2I:Yes", "Check Box108");
        fieldMap.put("Section4:Question2I:No", "Check Box105");
        fieldMap.put("Section4:Question2J:Yes", "Check Box107");
        fieldMap.put("Section4:Question2J:No", "Check Box106");

        // Section 5
        fieldMap.put("Section5:No", "Check Box113");
        fieldMap.put("Section5:Yes", "Check Box114");

        // Section 7
        fieldMap.put("Section7:Question1", "Text115");
        fieldMap.put("Section7:Question1A", "Text117");
        fieldMap.put("Section7:Question1B", "Text118");
        fieldMap.put("Section7:Question1C", "Text123");
        fieldMap.put("Section7:Question1D", "Text122");
        fieldMap.put("Section7:Question1E", "Text124");
        fieldMap.put("Section7:Question2", "Text116");
        fieldMap.put("Section7:Question2A:Son", "Check Box45");
        fieldMap.put("Section7:Question2A:Daughter", "Check Box46");
        fieldMap.put("Section7:Question2A:Stepson", "Check Box47");
        fieldMap.put("Section7:Question2A:Stepdaughter", "Check Box48");
        fieldMap.put("Section7:Question2B", "Text119");
        fieldMap.put("Section7:Question2C", "Text120");
        fieldMap.put("Section7:Question2D", "Text121");
        fieldMap.put("Section7:Question2E:Yes", "Check Box49");
        fieldMap.put("Section7:Question2E:No", "Check Box50");
        fieldMap.put("Section7:Question2F:Yes", "Check Box51");
        fieldMap.put("Section7:Question2F:No", "Check Box52");
        fieldMap.put("Section7:Question2G", "Text61");
        fieldMap.put("Section7:Question3:Spouse", "Text125");
        fieldMap.put("Section7:Question3:Child", "Text126");
        fieldMap.put("Section7:Question3:Yes", "Check Box53");  //Did you provide support Yes


        // Section 8
        fieldMap.put("Section8:Question1:Veteran", "Text127");
        fieldMap.put("Section8:Question1:Spouse", "Text128");
        fieldMap.put("Section8:Question1:Child", "Text129");
        fieldMap.put("Section8:Question2:Veteran", "Text132");
        fieldMap.put("Section8:Question2:Spouse", "Text131");
        fieldMap.put("Section8:Question2:Child", "Text130");
        fieldMap.put("Section8:Question3:Veteran", "Text133");
        fieldMap.put("Section8:Question3:Spouse", "Text134");
        fieldMap.put("Section8:Question3:Child", "Text135");

        // Section 9

        fieldMap.put("Section9:Question1", "Text136");
        fieldMap.put("Section9:Question2", "Text137");
        fieldMap.put("Section9:Question3", "Text138");

        // Section 10
        fieldMap.put("Section10:Question1:Veteran", "Text139");
        fieldMap.put("Section10:Question1:Spouse", "Text140");
        fieldMap.put("Section10:Question1:Child", "Text141");
        fieldMap.put("Section10:Question2:Veteran", "Text144");
        fieldMap.put("Section10:Question2:Spouse", "Text143");
       fieldMap.put("Section10:Question2:Child", "Text142");
        fieldMap.put("Section10:Question3:Veteran", "Text145");
        fieldMap.put("Section10:Question3:Spouse", "Text146");
        fieldMap.put("Section10:Question3:Child", "Text147");

        // Section 12
        fieldMap.put("Section12:Date", "Text148");
    }



    /**
     * Fill SECTION I - GENERAL INFORMATION of the fillable PDF document
     * @throws DocumentException
     * @throws IOException
     */
    private void fillSection1() throws DocumentException, IOException {


        Name legalName = null;
        Name aliasName = null;

        // get name from person
        Set names = person.getNames();
        aliasName = Name.getNameOfType(names, NameType.ALIAS_NAME.getName());
        legalName = Name.getNameOfType(names, NameType.LEGAL_NAME.getName());

        String p_legalname = this.getLastFirstMiddleByComma(legalName);
        String p_aliasname = aliasName != null ? aliasName.getFormattedName(): "";
        this.veteranName = p_legalname;

        fields.setField((String)fieldMap.get("Section1:Question1"),p_legalname);
        fields.setField((String)fieldMap.get("Section1:Question2"),p_aliasname);
        fields.setField((String)fieldMap.get("Section1:Question3"), person.getMothersMaidenName());

        fields.setField((String)fieldMap.get("Section1:Question1"),p_legalname);
        fields.setField("test", p_legalname);

        String nm = (String)fieldMap.get("Section1:Question2");

        if (person.getGender() != null) {
             if (Gender.MALE.getCode().equalsIgnoreCase(person.getGender().getCode()))
                fields.setField((String)fieldMap.get("Section1:Question4:Male"), "Yes");
            else if (Gender.FEMALE.getCode().equalsIgnoreCase(person.getGender().getCode()))
                fields.setField((String)fieldMap.get("Section1:Question4:Female"), "Yes");
        }

        Ethnicity ethnicity = person.getEthnicity();
        if (ethnicity!=null && ethnicity.getEthnicityType()!=null ){
             EthnicityType ethnicitytype = ethnicity.getEthnicityType();
             if (ethnicitytype!=null){
                    if (EthnicityType.CODE_HISPANIC.getCode().equals(ethnicitytype.getCode()))
                           fields.setField((String)fieldMap.get("Section1:Question5:Yes"),"Yes");
                    else
                           if ( EthnicityType.CODE_NOT_HISPANIC.getCode().equals(ethnicitytype.getCode()))
                                  fields.setField((String)fieldMap.get("Section1:Question5:No"),"Yes");
             }
        }

        Set raceset = person.getRaces();
        if (raceset!=null){
             for (Iterator iterator = raceset.iterator(); iterator.hasNext();) {
                    Race race = (Race) iterator.next();
                    RaceType raceType= race.getRaceType();
                    if (raceType!=null){
                           if (RaceType.CODE_AMERICAN_INDIAN_ALASKA.getCode().equals(raceType.getCode()))
                                  fields.setField((String)fieldMap.get("Section1:Question6:AlaskaNative"),"Yes");
                           else if (RaceType.CODE_ASIAN.getCode().equals(raceType.getCode()))
                                  fields.setField((String)fieldMap.get("Section1:Question6:Asian"),"Yes");
                           else if (RaceType.CODE_BLACK_AFRICAN.getCode().equals(raceType.getCode()))
                                  fields.setField((String)fieldMap.get("Section1:Question6:Black"),"Yes");
                           else if (RaceType.CODE_WHITE.getCode().equals(raceType.getCode()))
                                  fields.setField((String)fieldMap.get("Section1:Question6:White"),"Yes");
                           else if (RaceType.CODE_HAWAIIAN_PACIFIC.getCode().equals(raceType.getCode()))
                                  fields.setField((String)fieldMap.get("Section1:Question6:NativeHawaiian"),"Yes");
                    }
             }
        }

       SSN officialSSN = person.getOfficialSsn();
       this.veteranSSN = officialSSN!=null? JspUtils.displaySSN(officialSSN.getSsnText()):"";

       fields.setField((String)fieldMap.get("Section1:Question7"),officialSSN!=null? JspUtils.displaySSN(officialSSN.getSsnText()):"");
       ImpreciseDate birthdate = null;
       if (person.getBirthRecord() != null)
            birthdate = person.getBirthRecord().getBirthDate();
       fields.setField((String)fieldMap.get("Section1:Question8"), person.getClaimFolderNumber());
       fields.setField((String)fieldMap.get("Section1:Question9"), DateUtils.format(birthdate, null));
       fields.setField((String)fieldMap.get("Section1:Question9A"),person.getBirthRecord()!=null ? this.getBirthPlace(person.getBirthRecord().getCity(),person.getBirthRecord().getState()):"");
       fields.setField((String)fieldMap.get("Section1:Question10"),person.getReligion()!=null ? person.getReligion().getName():"");

        // Get the permanent address
        Address permAddress = person.getPermanentAddress();
        if (permAddress != null) {
            String stateProvince = null;
            String zipPostalCode = null;
            if (Country.isUSAddress(permAddress.getCountry())) {
                stateProvince = permAddress.getState();
                zipPostalCode = permAddress.getZipCode();
                if ((StringUtils.isNotEmpty(zipPostalCode))
                        && (StringUtils.isNotEmpty(permAddress.getZipPlus4()))) {
                    zipPostalCode = zipPostalCode + "-"
                            + permAddress.getZipPlus4();
                }
            } else {
                stateProvince = permAddress.getProvince();
                zipPostalCode = permAddress.getPostalCode();
            }

            StringBuffer resultBuffer = new StringBuffer();
            // Append the first 3 lines
            permAddress.appendAddressPieceOnNewLine(resultBuffer, permAddress.getLine1());
            permAddress.appendAddressPieceOnNewLine(resultBuffer, permAddress.getLine2());
            permAddress.appendAddressPieceOnNewLine(resultBuffer, permAddress.getLine3());

            fields.setField((String)fieldMap.get("Section1:Question11"),resultBuffer.toString());
            fields.setField((String)fieldMap.get("Section1:Question11A"),permAddress.getCity());
            fields.setField((String)fieldMap.get("Section1:Question11B"),stateProvince);
            fields.setField((String)fieldMap.get("Section1:Question11C"),zipPostalCode);
            fields.setField((String)fieldMap.get("Section1:Question11D"),permAddress.getCounty());
        }

        Phone homephone = person.getHomePhone();
        if (homephone != null)
            fields.setField((String)fieldMap.get("Section1:Question11E"),homephone.getFormattedPhone());

        // Get the contact methods
        ArrayList emails = new ArrayList(person.getEmails());
        String cellphonenumber = "";
        String pagephonenumber = "";

        Phone cellphone = Phone.getPhoneOfType(person.getPhones(),PhoneType.CODE_MOBILE.getCode());
        if (cellphone != null)
            cellphonenumber = cellphone.getFormattedPhone();

        Phone pagephone = Phone.getPhoneOfType(person.getPhones(),PhoneType.CODE_PAGER.getCode());
        if (pagephone != null)
            pagephonenumber = pagephone.getFormattedPhone();

        String emailaddress = "";
        for (Iterator iterator = emails.iterator(); iterator.hasNext();) {
            Email vemail = (Email) iterator.next();
            emailaddress = vemail.getAddress();
            if (emailaddress != null && StringUtils.isNotEmpty(emailaddress))
                break;
        }

        fields.setField((String)fieldMap.get("Section1:Question11G"),cellphonenumber);
        fields.setField((String)fieldMap.get("Section1:Question11H"),pagephonenumber);
        fields.setField((String)fieldMap.get("Section1:Question11F"),emailaddress);
        fields.setField((String)fieldMap.get("Section1:Question13"), person.getMostRecentPreferredFacility() != null ? person.getMostRecentPreferredFacility().getFacilityName() : "");

        // question 12 - new VOA
        Application application = person.getApplication();
        if (application!=null){
             BenefitType benefitType = application.getBenefitType();
             if (benefitType!=null){
                    if (BenefitType.CODE_HEATH_SERVICES.getCode().equals(benefitType.getCode())
                                  || BenefitType.CODE_ENROLLMENT.getCode().equals(benefitType.getCode()) )
                           fields.setField((String)fieldMap.get("Section1:Question12:HealthServices"),"Yes");
                    else if (BenefitType.CODE_DENTAL.getCode().equals(benefitType.getCode()) )
                           fields.setField((String)fieldMap.get("Section1:Question12:Dental"),"Yes");
                    else if (BenefitType.CODE_DOMICILIARY.getCode().equals(benefitType.getCode()) )
                           fields.setField((String)fieldMap.get("Section1:Question12:Domiciliary"),"Yes");
                    else if (BenefitType.CODE_NURSING_HOME.getCode().equals(benefitType.getCode()) )
                           fields.setField((String)fieldMap.get("Section1:Question12:NursingHome"),"Yes");
             }
        }

        // VOA Only check Question15:NO, otherwise Question15:Yes.
        patientVisitSummaries = this.getPatientVisitSummaries();
        if (patientVisitSummaries != null && patientVisitSummaries.size() > 0) {
                    //get the first record and return the date if used sort in getPatientVisitSummaries()
                    // PatientVisitSummary patientVisitSummary = (PatientVisitSummary)patientVisitSummaries.get(0);
             PatientVisitSummary patientVisitSummary = PatientVisitSummary.getLastestVisitedSummary(patientVisitSummaries);
               fields.setField((String)fieldMap.get("Section1:Question15:Yes"),"Yes");
                    fields.setField((String)fieldMap.get("Section1:Question15:Location"),patientVisitSummary!=null && patientVisitSummary.getFacilityVisited()!=null ? patientVisitSummary.getFacilityVisited().getName():""); ;
        }
        else
               fields.setField((String)fieldMap.get("Section1:Question15:No"),"Yes");

        MaritalStatus mstatus = person.getMaritalStatus();
        if (mstatus != null) {
            if (mstatus.getName().equalsIgnoreCase("MARRIED")) {
                fields.setField((String)fieldMap.get("Section1:Question16:Married"), "Yes");
            } else if (mstatus.getName().equalsIgnoreCase("NEVER MARRIED")) {
                fields.setField((String)fieldMap.get("Section1:Question16:NeverMarried"), "Yes");
            } else if (mstatus.getName().equalsIgnoreCase("SEPARATED")) {
                fields.setField((String)fieldMap.get("Section1:Question16:Separated"), "Yes");
            } else if (mstatus.getName().toUpperCase().indexOf("WIDOW") >= 0) {
                fields.setField((String)fieldMap.get("Section1:Question16:Widowed"), "Yes");
            } else if (mstatus.getName().equalsIgnoreCase("UNKNOWN")) {
                fields.setField((String)fieldMap.get("Section1:Question16:Unknown"), "Yes");
            } else if (mstatus.getName().equalsIgnoreCase("DIVORCED")) {
                fields.setField((String)fieldMap.get("Section1:Question16:Divorced"), "Yes");
            }
        }
        List associations = new ArrayList(person.getAssociations());
        Collections.sort(associations);
        Association primary_next_of_kin = Association.getAssociationOfType(person.getAssociations(),AssociationType.CODE_PRIMARY_NEXT_OF_KIN.getCode());
        Association emergency_contact = Association.getAssociationOfType(person.getAssociations(), AssociationType.CODE_EMERGENCY_CONTACT.getCode());

        if (primary_next_of_kin != null) {
            Address p_address = primary_next_of_kin.getAddress();
            String a_addr = p_address!=null ? p_address.getFormattedAddress():"";
            String a_role = primary_next_of_kin.getRelationship();
            String a_name = primary_next_of_kin.getRepresentativeName() != null ? primary_next_of_kin.getRepresentativeName().getFormattedName(): "";
            String a_h_phone = Phone.getFormattedPhone(primary_next_of_kin.getPrimaryPhone()); // primary=home, alternate=work
            String a_w_phone = Phone.getFormattedPhone(primary_next_of_kin.getAlternatePhone());
            fields.setField((String)fieldMap.get("Section1:Question17"),a_name + "\n" + a_addr + "\n" + a_role);
            fields.setField((String)fieldMap.get("Section1:Question17A"),a_h_phone);
            fields.setField((String)fieldMap.get("Section1:Question17B"), a_w_phone);
        }

        if (emergency_contact != null) {
            Address e_address = emergency_contact.getAddress();
            String e_addr = e_address!=null ? e_address.getFormattedAddress():"";
            String e_role = emergency_contact.getRelationship();
            String e_name = emergency_contact.getRepresentativeName() != null ? emergency_contact.getRepresentativeName().getFormattedName(): "";
            String e_h_phone = Phone.getFormattedPhone(emergency_contact.getPrimaryPhone());
            String e_w_phone = Phone.getFormattedPhone(emergency_contact.getAlternatePhone());
            fields.setField((String) fieldMap.get("Section1:Question18"),e_name + "\n" + e_addr + "\n" + e_role);
            fields.setField((String) fieldMap.get("Section1:Question18A"),e_h_phone);
            fields.setField((String) fieldMap.get("Section1:Question18B"),e_w_phone);
         }

        /* VOA Question14 Appoinment left unchecked base on UC  */
        //CCR12088 -  VOA - Appointment Request Indicator not printing on 1010EZ
        if (person.getAppointmentRequestResponse() != null)
        {
             if (person.getAppointmentRequestResponse())
                    fields.setField((String)fieldMap.get("Section1:Question14:Yes"),"Yes");
             else
                    fields.setField((String)fieldMap.get("Section1:Question14:No"),"Yes");
        }

        /* Question19 to left unchecked based on UC Specification */
    }


    public void appendAddressPieceOnNewLine(StringBuffer buffer, String piece)
    {
        // If there is nothing to append, just return
        if (StringUtils.isEmpty(piece))
        {
            return;
        }

        // If something was already added to the buffer, add a new line
        if ((buffer != null) && (buffer.length() > 0))
        {
            buffer.append("\n");
        }

        // Add this piece of the address
        buffer.append(piece);
    }

    /**
     * Fill SECTION II - INSURANCE INFORMATION of the fillable PDF document
     *
     * @throws DocumentException
     * @throws IOException
     */

    private void fillSection2() throws DocumentException, IOException {

        insurances = person.getInsurances(); // set of insurancePolicy
        medicares = person.getMedicareInsurances();
        MedicaidFactor medicaidfactor = person.getMedicaidFactor();

        if (medicaidfactor != null )
            if ( Boolean.TRUE.equals(medicaidfactor.getEligibleForMedicaid()))
                fields.setField((String)fieldMap.get("Section2:Question6:Yes"),"Yes");
        else if ( Boolean.FALSE.equals(medicaidfactor.getEligibleForMedicaid()))
            fields.setField((String)fieldMap.get("Section2:Question6:No"),"Yes");

        if (insurances != null && insurances.size() != 0)
            fields.setField((String)fieldMap.get("Section2:Question1:Yes"),"Yes");
        else
            fields.setField((String)fieldMap.get("Section2:Question1:No"),"Yes");

        List sortpinsr = sortPrivateInsurance (privateinsurances);
        int ins_cnt = 0;
        if (sortpinsr != null && sortpinsr.size() != 0) {
            boolean isFirst = true;
            boolean addFirst = true;
            for (Iterator iterator = sortpinsr.iterator(); iterator.hasNext();) {
                PrivateInsurance insurance = (PrivateInsurance) iterator.next();
                ins_cnt ++;
                if (isFirst) {
                    fields.setField((String)fieldMap.get("Section2:Question2"),getInsuranceCompanyAddrPhone(insurance));
                    fields.setField((String)fieldMap.get("Section2:Question3"),insurance.getSubscriber() != null ? insurance.getSubscriber().getName() : "");
                    fields.setField((String)fieldMap.get("Section2:Question4"),insurance.getPolicyNumber());
                    fields.setField((String)fieldMap.get("Section2:Question5"),insurance.getGroupNumber());
                    isFirst = false;
                } else {
                    PdfPTable table = new PdfPTable(3);
                    table.setKeepTogether(true);
                    table.setWidthPercentage(100f);
                    float[] widths = {45f,30f,25f};
                    table.setWidths(widths);
                    if (addFirst){
                            PdfPCell cell = new PdfPCell(new Paragraph("APPLICATION FOR HEALTH BENEFITS, Continued",FontFactory.getFont(FontFactory.HELVETICA, 11,Font.BOLD, Color.BLACK)));
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            table.addCell(cell);
                            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                            table.addCell(new Phrase("VETERAN'S NAME  (Last, First, Middle)\n\n"+veteranName, font_times));
                            table.addCell( new Phrase("SOCIAL SECURITY NUMBER\n\n"+veteranSSN, font_times));
                            addFirst = false;
                    }
                    PdfPCell cell = new PdfPCell(new Paragraph("SECTION II - INSURANCE INFORMATION (Continuation #"+ins_cnt+")",FontFactory.getFont(FontFactory.HELVETICA, 8,Font.BOLD, Color.BLACK)));
                    cell.setColspan(3);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell.setBackgroundColor(Color.lightGray);
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph("2.HEALTH INSURANCE COMPANY NAME,ADDRESS AND TELEPHONE NUMBER\n"+getInsuranceCompanyAddrPhone(insurance), font_courier));
                    cell.setColspan(3);
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                    table.addCell(cell);

                    String policyholder = insurance.getSubscriber() != null ? insurance.getSubscriber().getName() : "";
                    table.addCell(new Phrase("3.NAME OF POLICY HOLDER\n"+policyholder, font_courier));
                    table.addCell(new Phrase("4.POLICY NUMBER\n"+insurance.getPolicyNumber(), font_courier));
                    table.addCell(new Phrase("5.GROUP CODE\n"+insurance.getGroupNumber(), font_courier));
                    additionalInsDocument.add(table);
                }
            }
        }

        if (medicares != null && medicares.size() != 0) {
            // only Part A or Part A and B in current ESR if Part A and B there
            // are two medicare
            // records - one part A (Part A indicator ture, part B false) and
            // another part B (with both part A and part B indicator True)
            Medicare medicare = null;
            Medicare LatestMedicareA = null;
            Medicare LatestMedicareB = null;

            for (Iterator iterator = medicares.iterator(); iterator.hasNext();) {
            medicare = (Medicare) iterator.next();
            // Medicare B
                if (Boolean.TRUE.equals(medicare.isEnrolledInPartB())){
                           if(LatestMedicareB == null) {
                                 LatestMedicareB = medicare;
                           } else {
                                 // if(LatestMedicareB.getCreatedOn().before(medicare.getCreatedOn()))
                                  if(LatestMedicareB.getModifiedOn().before(medicare.getModifiedOn()))
                                        LatestMedicareB = medicare;
                           }
                    }else
                           // medicare A
                           if (Boolean.TRUE.equals(medicare.isEnrolledInPartA())){
                                 if(LatestMedicareA == null) {
                                        LatestMedicareA = medicare;
                                 } else {
                                        if(LatestMedicareA.getModifiedOn().before(medicare.getModifiedOn()))
                                               LatestMedicareA = medicare;
                                 }
                           }
            }
            if (LatestMedicareB != null) {
                fields.setField((String)fieldMap.get("Section2:Question8:Yes"), "Yes");
                fields.setField((String)fieldMap.get("Section2:Question8A"), DateUtils.format(LatestMedicareB.getPartBEffectiveDate(), null));
            }
            else fields.setField((String)fieldMap.get("Section2:Question8:No"),"Yes");

            if (LatestMedicareA != null) {
                fields.setField((String)fieldMap.get("Section2:Question7:Yes"), "Yes");
                //fields.setField((String)fieldMap.get("Section2:Question7A"), DateUtils.format(LatestMedicareA.getPartAEffectiveDate(),null));
                fields.setField((String)fieldMap.get("Section2:Question9"), LatestMedicareA.getNameOnMedicareCard());
                fields.setField((String)fieldMap.get("Section2:Question10"), LatestMedicareA.getMedicareClaimNumber());
            }
            else  fields.setField((String)fieldMap.get("Section2:Question7:No"), "Yes");
        }
        // section 2 question 11 and 12 left unchecked
    }


    /**
     * Fill SECTION III - EMPLOYMENT INFORMATION of the fillable PDF document
     *
     * @throws DocumentException
     * @throws IOException
     */

    private void fillSection3() throws DocumentException, IOException {
       Employment vetEmp = person.getEmployment();
       if (vetEmp!=null){
             // CCR 10673
             ImpreciseDate retiredate = vetEmp.getRetirementDate();
             EmploymentStatus employmentstatus = vetEmp.getEmploymentStatus();
             if (employmentstatus!=null){
                    if (EmploymentStatus.CODE_FULL_TIME.getCode().equals(employmentstatus.getCode())) {
                           fields.setField((String)fieldMap.get("Section3:Question1:FullTime"), "Yes");
                           fields.setField((String)fieldMap.get("Section3:Question1A"),getEmployerCompanyAddrPhone(vetEmp));
                    }
                    else if (EmploymentStatus.CODE_ACTIVE_MILITARYSERVICE.getCode().equals(employmentstatus.getCode()) ||
                     EmploymentStatus.CODE_SELF_EMPLOYED.getCode().equals(employmentstatus.getCode()) )
                    {
                           fields.setField((String)fieldMap.get("Section3:Question1:FullTime"), "Yes");
                            fields.setField((String)fieldMap.get("Section3:Question1A"),getEmployerCompanyAddrPhone(vetEmp));
                    }
                    else if (EmploymentStatus.CODE_PART_TIME.getCode().equals(employmentstatus.getCode()) )
                    {
                           fields.setField((String)fieldMap.get("Section3:Question1:PartTime"), "Yes");
                           fields.setField((String)fieldMap.get("Section3:Question1A"),getEmployerCompanyAddrPhone(vetEmp));
                    }
                    else if (EmploymentStatus.CODE_NOT_EMPLOYED.getCode().equals(employmentstatus.getCode()))
                             fields.setField((String)fieldMap.get("Section3:Question1:NotEmployed"), "Yes");
                    else if (EmploymentStatus.CODE_RETIRED.getCode().equals(employmentstatus.getCode()))
                    {
                            fields.setField((String)fieldMap.get("Section3:Question1:Retired"), "Yes");
                            fields.setField((String)fieldMap.get("Section3:Question1:RetirementDate"),DateUtils.format(retiredate, null));
                            fields.setField((String)fieldMap.get("Section3:Question1A"),getEmployerCompanyAddrPhone(vetEmp));
                    }
             }
       }
       // spouse employment information
        if (sf != null) {
            spouse = sf.getReportedOn();
        }
        if (spouse != null && spouse.getEmployment()!= null) {
             Employment spEmp = spouse.getEmployment();
             // CCR 10673
             ImpreciseDate retiredate = spEmp.getRetirementDate();
             EmploymentStatus employmentstatus = spEmp.getEmploymentStatus();
             if (employmentstatus!=null){
                    if (EmploymentStatus.CODE_FULL_TIME.getCode().equals(employmentstatus.getCode())) {
                           fields.setField((String)fieldMap.get("Section3:Question2:FullTime"), "Yes");
                           fields.setField((String)fieldMap.get("Section3:Question2A"),getEmployerCompanyAddrPhone(spEmp));
                    }
                    else if (EmploymentStatus.CODE_ACTIVE_MILITARYSERVICE.getCode().equals(employmentstatus.getCode()) ||
                     EmploymentStatus.CODE_SELF_EMPLOYED.getCode().equals(employmentstatus.getCode()) )
                    {
                           fields.setField((String)fieldMap.get("Section3:Question2:FullTime"), "Yes");
                           fields.setField((String)fieldMap.get("Section3:Question2A"),getEmployerCompanyAddrPhone(spEmp));
                    }
                    else if (EmploymentStatus.CODE_PART_TIME.getCode().equals(employmentstatus.getCode()) )
                    {
                           fields.setField((String)fieldMap.get("Section3:Question2:PartTime"), "Yes");
                           fields.setField((String)fieldMap.get("Section3:Question2A"),getEmployerCompanyAddrPhone(spEmp));
                    }
                    else if (EmploymentStatus.CODE_NOT_EMPLOYED.getCode().equals(employmentstatus.getCode()))
                             fields.setField((String)fieldMap.get("Section3:Question2:NotEmployed"), "Yes");
                    else if (EmploymentStatus.CODE_RETIRED.getCode().equals(employmentstatus.getCode()))
                    {
                            fields.setField((String)fieldMap.get("Section3:Question2:Retired"), "Yes");
                            fields.setField((String)fieldMap.get("Section3:Question2:RetirementDate"),DateUtils.format(retiredate, null));
                            fields.setField((String)fieldMap.get("Section3:Question2A"),getEmployerCompanyAddrPhone(spEmp));
                    }
             }
        }
    }


    /**
     * Fill SECTION IV - MILITARY SERVICE INFORMATION of the fillable PDF
     * document
     *
     * @throws DocumentException
     * @throws IOException
     */

    private void fillSection4() throws DocumentException, IOException, Exception {
        PurpleHeart ph = person.getPurpleHeart();
        if (ph != null && ph.getPhIndicator() != null )
        {
             if ( Boolean.TRUE.equals(ph.getPhIndicator()) && ph.getStatus() != null
                &&  DecorationStatus.CODE_CONFIRMED.getCode().equals(ph.getStatus().getCode()) ) {
                    fields.setField((String)fieldMap.get("Section4:Question2A:Yes"),"Yes");
             } else if (isFalse(ph.getPhIndicator()))
                    fields.setField((String)fieldMap.get("Section4:Question2A:No"),"Yes");
        }

        PrisonerOfWar pow = person.getPrisonerOfWar();
        if (pow != null && pow.getPowIndicator() != null ){
            if ( Boolean.TRUE.equals(pow.getPowIndicator().toBoolean())) {
            fields.setField((String)fieldMap.get("Section4:Question2B:Yes"),"Yes");
            } else if (  Boolean.FALSE.equals(pow.getPowIndicator().toBoolean())) {
            fields.setField((String)fieldMap.get("Section4:Question2B:No"), "Yes");
            }
        }

        ServiceConnectionAward scAward = person.getServiceConnectionAward();
        if (scAward != null && scAward.getServiceConnectedPercentage() != null ) {
            if ( scAward.getServiceConnectedPercentage().intValue() > 0
                    && Boolean.TRUE.equals(scAward.getServiceConnectedIndicator())) {
                fields.setField((String)fieldMap.get("Section4:Question2C:Yes"), "Yes");
                fields.setField((String)fieldMap.get("Section4:Question2C1"),scAward.getServiceConnectedPercentage().toString());
            } else {
                fields.setField((String)fieldMap.get("Section4:Question2C:No"), "Yes");
            }
        } else
            fields.setField((String)fieldMap.get("Section4:Question2C:No"),"Yes");

        AgentOrangeExposure aoe = person.getAgentOrangeExposure();
        if (aoe != null && aoe.getAgentOrangeExposureIndicator() != null ){
             if ( Indicator.YES.getCode().equals(aoe.getAgentOrangeExposureIndicator().getCode())
                &&  aoe.getLocation() != null && AgentOrangeExposureLocation.CODE_VIETNAM.getCode().equalsIgnoreCase(aoe.getLocation().getCode()) )
             {
                    fields.setField((String)fieldMap.get("Section4:Question2G:Yes"),"Yes");
             }
             else fields.setField((String)fieldMap.get("Section4:Question2G:No"),"Yes");
        }

        // Radiation exposure
        RadiationExposure rexp = person.getRadiationExposure();
        if (rexp != null && rexp.getRadiationExposureIndicator() != null )
        {
             if( Indicator.YES.getCode().equals(rexp.getRadiationExposureIndicator().getCode())
                && rexp.getExposureMethod()!= null )
             {
               fields.setField((String)fieldMap.get("Section4:Question2H:Yes"),"Yes");
             } else fields.setField((String)fieldMap.get("Section4:Question2H:No"),"Yes");
        }

        // SW Asia conditions (Environmental Contamination Exposure)
        EnvironmentalContaminationExposure eexp = person.getEnvironmentalContaminationExposure();
        if (eexp != null && eexp.getEnvironmentalContaminationExposureIndicator() != null
                && Indicator.YES.getCode().equals(eexp.getEnvironmentalContaminationExposureIndicator().getCode())) {
            fields.setField((String)fieldMap.get("Section4:Question2F:Yes"),"Yes");
        } else
            fields.setField((String)fieldMap.get("Section4:Question2F:No"),"Yes");

        // EnvironmentalContaminationExposure contExp = (EnvironmentalContaminationExposure)person.getSpecialFactorByType(EnvironmentalContaminationExposure.class);
        // Indicator envInd = (contExp != null) ? contExp.getEnvironmentalContaminationExposureIndicator() : null;
        // form.setExposedToContaminants((envInd != null) ? envInd.getCode() : Indicator.UNKNOWN.getCode());

        // person.getClinicalDeterminations();

        NoseThroatRadium ntr = (NoseThroatRadium)person.getClinicalDeterminationByType(NoseThroatRadium.class);
        if (ntr != null && ntr.getReceivingTreatment()!=null ){
             // StringUtils.isNotEmpty(ntr.getVerificationDate().toString())
             if ( ntr.getVerificationDate() != null  && TriState.TRUE.equals(ntr.getReceivingTreatment()) ){
                    fields.setField((String)fieldMap.get("Section4:Question2I:Yes"),"Yes");
             }
             else if (ntr.getVerificationDate() == null && TriState.FALSE.equals(ntr.getReceivingTreatment()) ){
                    fields.setField((String)fieldMap.get("Section4:Question2I:No"),"Yes");
             }
        }
        // No is a definitive answer that we do not have and suggest the box be left unchecked
        // else fields.setField((String)fieldMap.get("Section4:Question2I:No"),"Yes");

        if (militaryService != null) {
          if ( militaryService.getDisabilityRetirementIndicator() != null
          && Indicator.YES.getCode().equals(this.getIndicatorCode(militaryService.getDisabilityRetirementIndicator())))
           {
                fields.setField((String)fieldMap.get("Section4:Question2E1:Yes"), "Yes");
            } else if ( militaryService.getDisabilityRetirementIndicator() != null
                    && Indicator.NO.getCode().equals(this.getIndicatorCode(militaryService.getDisabilityRetirementIndicator()))){
                fields.setField((String)fieldMap.get("Section4:Question2E1:No"), "Yes");
            }

          if (militaryService.getDischargeDueToDisability() != null &&
            Indicator.YES.getCode().equals(this.getIndicatorCode(militaryService.getDischargeDueToDisability())) )
            // if (militaryService.getDischargeDueToDisability() != null && militaryService.getDischargeDueToDisability().booleanValue() )
            {
                fields.setField((String)fieldMap.get("Section4:Question2E:Yes"), "Yes");
            } else if (militaryService.getDischargeDueToDisability() != null &&
                    Indicator.NO.getCode().equals(this.getIndicatorCode(militaryService.getDischargeDueToDisability())) ){
                fields.setField((String)fieldMap.get("Section4:Question2E:No"), "Yes");
            }
        }
        /*
        else {
            fields.setField((String) fieldMap.get("Section4:Question2E1:No"),"No");
            fields.setField((String) fieldMap.get("Section4:Question2E:No"),"No");
        }
        */
        String militaryServiceNumber,branchOfService,entryDate,separationDate,dischargeType;
        MilitaryServiceSiteRecord latestmilitaryServiceSiteRecord = this.getLatestMilitaryServiceSiteRecord();
        MilitaryServiceEpisode latestEpisode = getLatestMilitaryServiceEpisode(latestmilitaryServiceSiteRecord);
        if (latestEpisode!=null){
             militaryServiceNumber = latestEpisode.getServiceNumber();
                    branchOfService = latestEpisode.getServiceBranch() == null ? "" : latestEpisode.getServiceBranch().getDescription();
            entryDate = JspUtils.displayValue(latestEpisode.getStartDate(),JspUtils.STANDARD_DATE_FORMAT);
            separationDate = JspUtils.displayValue(latestEpisode.getEndDate(),JspUtils.STANDARD_DATE_FORMAT);
            dischargeType = latestEpisode.getDischargeType() == null ? "" : latestEpisode.getDischargeType().getDescription();
                    fields.setField((String)fieldMap.get("Section4:Question1"), branchOfService);
                    fields.setField((String)fieldMap.get("Section4:Question1A"), entryDate);
                  fields.setField((String)fieldMap.get("Section4:Question1B"), separationDate);
                  fields.setField((String)fieldMap.get("Section4:Question1C"), dischargeType);
                  fields.setField((String)fieldMap.get("Section4:Question1D"),  militaryServiceNumber);
        }

        ImpreciseDate afterDate = ImpreciseDateUtils.createImpreciseDate(1998, 11, 11);
        boolean isServeCombat = false;
        Set combatepisodes = militaryService.getCombatEpisodes();
        MilitaryServiceActionHelper.sortCombatEpisodes(combatepisodes);
        if (combatepisodes != null && ! combatepisodes.isEmpty()){
            List combats = MilitaryServiceActionHelper.sortCombatEpisodes(combatepisodes);
            for (Iterator comb =combats.iterator(); comb.hasNext();) {
                CombatEpisode cbats = (CombatEpisode)comb.next();
                ImpreciseDate combatStartDate = cbats.getStartDate();
                if (combatStartDate != null && combatStartDate.compareTo(afterDate) == 1 ){
                    fields.setField((String) fieldMap.get("Section4:Question2D:Yes"),"Yes");
                    isServeCombat = true;
                    break;
                }
            }
        }
        if (!isServeCombat)
            fields.setField((String) fieldMap.get("Section4:Question2D:No"),"Yes");
    }



     private void fillSection5() throws DocumentException, IOException {

        IncomeTest test = person.getIncomeTest(this.incomeYear);
         if ( test == null || test.getDiscloseFinancialInformation() == null)
              FinDisclosureFlag = false;

         else {
                if(isTrue(test.getDiscloseFinancialInformation()))  {
                    fields.setField((String) fieldMap.get("Section5:Yes"),"Yes");
                    FinDisclosureFlag = true;
                }
                else if(isFalse(test.getDiscloseFinancialInformation()))  {
                    fields.setField((String) fieldMap.get("Section5:No"),"Yes");
                    FinDisclosureFlag = false;
                }
         }
     }



    /**
     * Fill SECTION VII - DEPENDENT INFORMATION of the fillable PDF document
     *
     * @throws DocumentException
     * @throws IOException
     */
   private void fillSection7() throws DocumentException, IOException {

     if (spouse != null) {
         fields.setField((String)fieldMap.get("Section7:Question1"),spouse.getName()!= null ? getLastFirstMiddleByComma(spouse.getName()): "");
         fields.setField((String)fieldMap.get("Section7:Question1A"),spouse.getMaidenName());
         fields.setField((String)fieldMap.get("Section7:Question1B"),spouse.getOfficialSsn()!= null ? JspUtils.displaySSN(spouse.getOfficialSsn().getSsnText()): "");
         fields.setField((String)fieldMap.get("Section7:Question1C"),DateUtils.format(spouse.getDob(), null));
         fields.setField((String)fieldMap.get("Section7:Question1D"),DateUtils.format(spouse.getMarriageDate(), null));
         // new VOA
         String spAddr = spouse.getAddress()!= null? spouse.getAddress().getFormattedAddress():"";
         String spPhone = spouse.getHomePhone()!=null? spouse.getHomePhone().getFormattedPhone():"";
         fields.setField((String)fieldMap.get("Section7:Question1E"),spAddr+"\n"+spPhone);
         if (FinDisclosureFlag && sf.getLivedWithPatient()!= null && !sf.getLivedWithPatient().booleanValue()){
             //fields.setField((String)fieldMap.get("Section7:Question3:Spouse"),ftmt.getContributionToSpouse()!=null? ftmt.getContributionToSpouse().toString(): "");
              fields.setField((String)fieldMap.get("Section7:Question3:Yes"),"Yes");  //Did you provide support Yes
         }
     }

     DependentFinancials df = null;
     Dependent dependent = null;
     int dep_cnt = 0;
     int add_cnt = 0;

     if (dependentFinancials!=null && dependentFinancials.size() != 0) {
        boolean isFirst = true;
        boolean addFirst = true;
        for (Iterator itr =dependentFinancials.iterator(); itr.hasNext();) {
            df = (DependentFinancials) itr.next();
            dependent = df.getReportedOn();
            if ( dependent != null) {
            dep_cnt++;
                if (isFirst){
                    fields.setField((String)fieldMap.get("Section7:Question2"), dependent.getName()!=null ? getLastFirstMiddleByComma(dependent.getName()):"" );
                    if (dependent.getRelationship()!=null){
                           if( Relationship.CODE_SON.getCode().equals(dependent.getRelationship().getCode()) )
                               fields.setField((String)fieldMap.get("Section7:Question2A:Son"),"Yes");
                           else if ( Relationship.CODE_DAUGHTER.getCode().equals(dependent.getRelationship().getCode()) )
                                fields.setField((String)fieldMap.get("Section7:Question2A:Daughter"),"Yes");
                           else if ( Relationship.CODE_STEPSON.getCode().equals(dependent.getRelationship().getCode()) )
                                  fields.setField((String)fieldMap.get("Section7:Question2A:Stepson"),"Yes");
                           else if ( Relationship.CODE_STEPDAUGHTER.getCode().equals(dependent.getRelationship().getCode()) )
                                fields.setField((String)fieldMap.get("Section7:Question2A:Stepdaughter"),"Yes");
                    }
                    fields.setField((String)fieldMap.get("Section7:Question2B"),dependent.getOfficialSsn()!=null? JspUtils.displaySSN(dependent.getOfficialSsn().getSsnText()):"" );
                    fields.setField((String)fieldMap.get("Section7:Question2C"),DateUtils.format(dependent.getStartDate(), null));
                    fields.setField((String)fieldMap.get("Section7:Question2D"),DateUtils.format(dependent.getDob(), null));

                    if (df.getIncapableOfSelfSupport()!=null && df.getIncapableOfSelfSupport().booleanValue())
                        fields.setField((String)fieldMap.get("Section7:Question2E:Yes"),"Yes");
                    else
                        fields.setField((String)fieldMap.get("Section7:Question2E:No"),"Yes");

                    if (df.getAttendedSchool()!=null && df.getAttendedSchool().booleanValue())
                        fields.setField((String)fieldMap.get("Section7:Question2F:Yes"),"Yes");
                    else
                        fields.setField((String)fieldMap.get("Section7:Question2F:No"),"Yes");

                    if (FinDisclosureFlag ){
                        if (df.getLivedWithPatient()!= null && !df.getLivedWithPatient().booleanValue())
                            //fields.setField((String)fieldMap.get("Section7:Question3:Child"),df.getAmountContributedToSupport()!=null? df.getAmountContributedToSupport().toString(): "");
                               fields.setField((String)fieldMap.get("Section7:Question3:Yes"),"Yes");  //Did you provide support Yes
                               fields.setField((String)fieldMap.get("Section7:Question2G"),df.getEducationExpense()!=null && df.getEducationExpense().getAmount()!=null? df.getEducationExpense().getAmount().toString():"");
                    }
                    isFirst = false;
                }
                else{
                     add_cnt ++;
                     PdfPTable table=new PdfPTable(5);
                     table.setKeepTogether(true);
                     table.setWidthPercentage(100f);
                     table.setSpacingAfter(0f);
                     float[] widths = {23f,22f,5f,25f,25f};
                            table.setWidths(widths);
                     if ( add_cnt % 4 == 1 || addFirst ){
                                   PdfPCell cell = new PdfPCell(new Paragraph("APPLICATION FOR HEALTH BENEFITS, Continued",FontFactory.getFont(FontFactory.HELVETICA, 11,Font.BOLD, Color.BLACK)));
                                   cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                   cell.setColspan(2);
                                   table.addCell(cell);
                                   cell = new PdfPCell(new Paragraph("VETERAN'S NAME  (Last, First, Middle)\n\n"+veteranName, font_times));
                                   cell.setColspan(2);
                                   cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                                   table.addCell(cell);
                                   table.addCell( new Phrase("SOCIAL SECURITY NUMBER\n\n"+veteranSSN, font_times));
                                   addFirst = false;
                           }
                    PdfPCell cell = new PdfPCell (new Paragraph ("Section VII - DEPENDENT INFORMATION (Child #"+dep_cnt+")",FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD,Color.BLACK )));
                    cell.setColspan (5);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell.setBackgroundColor (Color.LIGHT_GRAY);
                    table.addCell (cell);

                    String depname = dependent.getName()!=null ? getLastFirstMiddleByComma(dependent.getName()):"";
                    cell = new PdfPCell(new Phrase("2.CHILD'S NAME(Last, First , Middle Name)\n\n"+depname, font_courier));
                    cell.setColspan(3);
                    table.addCell(cell);

                    String deprelation=dependent.getRelationship()!=null ? dependent.getRelationship().getDescription(): "";
                    cell = new PdfPCell(new Phrase("2A.CHILD'S RELATIONSHIP TO YOU\n\n"+deprelation, font_courier));
                    cell.setColspan(2);
                    table.addCell(cell);

                    String depssn = dependent.getOfficialSsn()!=null?JspUtils.displaySSN(dependent.getOfficialSsn().getSsnText()):"";
                    table.addCell(new Phrase("2B.CHILD SOCIAL SECURITY NUMBER\n\n"+depssn, font_courier));

                    cell = new PdfPCell(new Phrase("2C.DATE CHILD BECAME YOUR DEPENDENT (mm/dd/yyyy)\n\n"+DateUtils.format(dependent.getStartDate(), null), font_courier));
                    cell.setColspan(2);
                    table.addCell(cell);

                    cell = new PdfPCell(new Phrase("2D.CHILD'S DATE OF BIRTH(mm/dd/yyyy)\n\n"+DateUtils.format(dependent.getDob(), null), font_courier));
                    cell.setColspan(2);
                    table.addCell(cell);

                    String disable = df.getIncapableOfSelfSupport()!=null && df.getIncapableOfSelfSupport().booleanValue()? "YES":"NO";
                    cell = new PdfPCell(new Phrase("2E.WAS CHILD PERMANENTLY AND TOTALY DISABLED BEFORE THE AGE OF 18?\n\n"+disable, font_courier));
                    cell.setColspan(3);
                    table.addCell(cell);

                    String attendschool = df.getAttendedSchool()!=null && df.getAttendedSchool().booleanValue()? "YES":"NO";
                    cell = new PdfPCell(new Phrase("2F.IF CHILD IS BETWEEN 18 and 23 YEARS OF AGE,DID CHILD ATTEND SCHOOL LAST CALENDAR YEAR?\n\n"+attendschool, font_courier));
                    cell.setColspan(2);
                    table.addCell(cell);

                    String childschool = "";
                    String childsupport = "";
                    if (FinDisclosureFlag){
                           childschool= df.getEducationExpense()!=null && df.getEducationExpense().getAmount()!=null? df.getEducationExpense().getAmount().toString():"";
                           childsupport = df.getAmountContributedToSupport()!=null? df.getAmountContributedToSupport().toString():"";
                    }
                    cell = new PdfPCell(new Phrase("3.IF YOUR DEPENDENT CHILD DID NOT LIVE WITH YOU LAST YEAR ENTER THE AMOUNT YOU CONTRIBUTED TO THEIR SUPPORT.\n\n"+"CHILD     $     "+childsupport, font_courier));
                    cell.setColspan(3);
                    table.addCell(cell);

                    cell = new PdfPCell(new Phrase("2G.EXPENSES PAID BY YOUR DEPENDENT CHILD FOR COLLEGE,VOCATIONAL REHABILITATION ORTRAINING(e.g.,tuition,books,materials)\n\n"+"$     "+childschool, font_courier));
                    cell.setColspan(2);
                    table.addCell(cell);
                    additionalChildDocument.add(table);
                }
            }
        }
    }
 }

/**
 * Fill SECTION VIII - PREVIOUS CALENDAR YEAR GROSS ANNUAL INCOME OF
 * VETERAN, SPOUSE AND DEPENDENT CHILDREN of the fillable PDF document
 *
 * @throws DocumentException
 * @throws IOException
 */

 private void fillSection8_9_10() throws DocumentException, IOException
 {
    DependentFinancials df = null;
    Dependent dependent = null;
    if (FinDisclosureFlag ){
         if ( ftmt !=null ){
                // veteran financial info
                fields.setField((String)fieldMap.get("Section8:Question1:Veteran"),ftmt.getTotalEmploymentIncome()!=null && ftmt.getTotalEmploymentIncome().getAmount()!=null ? ftmt.getTotalEmploymentIncome().getAmount().toString():"");
                fields.setField((String)fieldMap.get("Section8:Question2:Veteran"),ftmt.getFarmRanchBusinessIncome()!=null && ftmt.getFarmRanchBusinessIncome().getAmount()!=null ? ftmt.getFarmRanchBusinessIncome().getAmount().toString():"");
                fields.setField((String)fieldMap.get("Section8:Question3:Veteran"),ftmt.getOtherIncome()!=null && ftmt.getOtherIncome().getAmount()!=null ? ftmt.getOtherIncome().getAmount().toString():"");
                fields.setField((String)fieldMap.get("Section9:Question1"),ftmt.getNonReimbursableExpense()!=null && ftmt.getNonReimbursableExpense().getAmount()!=null? ftmt.getNonReimbursableExpense().getAmount().toString():"");
                fields.setField((String)fieldMap.get("Section9:Question2"),ftmt.getFuneralBurialExpense()!=null && ftmt.getFuneralBurialExpense().getAmount()!=null ? ftmt.getFuneralBurialExpense().getAmount().toString(): "");
                fields.setField((String)fieldMap.get("Section9:Question3"),ftmt.getVeteranEducationExpense()!=null && ftmt.getVeteranEducationExpense().getAmount()!=null ? ftmt.getVeteranEducationExpense().getAmount().toString():"");
                fields.setField((String)fieldMap.get("Section10:Question1:Veteran"),ftmt.getCashAndBankAccountBalances()!=null && ftmt.getCashAndBankAccountBalances().getAmount()!=null ? ftmt.getCashAndBankAccountBalances().getAmount().toString():"");
                fields.setField((String)fieldMap.get("Section10:Question2:Veteran"),ftmt.getRealEstate()!=null && ftmt.getRealEstate().getAmount()!=null? ftmt.getRealEstate().getAmount().toString():"");
                fields.setField((String)fieldMap.get("Section10:Question3:Veteran"),ftmt.getOtherPropertyOrAssets()!=null && ftmt.getOtherPropertyOrAssets().getAmount()!=null? ftmt.getOtherPropertyOrAssets().getAmount().toString():"");
         }
         // spouse financial info
        if(sf != null) {  // :new BigDecimal(0d).toString()
               fields.setField((String)fieldMap.get("Section8:Question1:Spouse"),sf.getTotalEmploymentIncome()!=null && sf.getTotalEmploymentIncome().getAmount()!=null ? sf.getTotalEmploymentIncome().getAmount().toString():"");
               fields.setField((String)fieldMap.get("Section8:Question2:Spouse"),sf.getFarmRanchBusinessIncome()!=null && sf.getFarmRanchBusinessIncome().getAmount()!= null ? sf.getFarmRanchBusinessIncome().getAmount().toString():"");
               fields.setField((String)fieldMap.get("Section8:Question3:Spouse"),sf.getOtherIncome()!=null && sf.getOtherIncome().getAmount()!=null ? sf.getOtherIncome().getAmount().toString():"");
                fields.setField((String)fieldMap.get("Section10:Question1:Spouse"),sf.getCashAndBankAccountBalances()!=null && sf.getCashAndBankAccountBalances().getAmount()!=null ? sf.getCashAndBankAccountBalances().getAmount().toString(): "");
                fields.setField((String)fieldMap.get("Section10:Question2:Spouse"),sf.getRealEstate()!=null && sf.getRealEstate().getAmount()!=null ? sf.getRealEstate().getAmount().toString(): "");
                fields.setField((String)fieldMap.get("Section10:Question3:Spouse"),sf.getOtherPropertyOrAssets()!=null && sf.getOtherPropertyOrAssets().getAmount()!=null? sf.getOtherPropertyOrAssets().getAmount().toString(): "");
        }
        // Children financial info
       if (dependentFinancials!=null && dependentFinancials.size() != 0) {
            boolean isFirst_8 = true;
            boolean isFirst_10 = true;
            boolean addFirst = true;
            int childCnt = 0;
            int add_child_cnt = 0;
            // Section VIII
            for (Iterator itr =dependentFinancials.iterator(); itr.hasNext();) {
                df = (DependentFinancials)itr.next();
                dependent = df.getReportedOn();
                if ( dependent != null) {
                         childCnt ++;
                            if (isFirst_8) {
                                          fields.setField((String)fieldMap.get("Section8:Question1:Child"),df.getTotalEmploymentIncome()!=null && df.getTotalEmploymentIncome().getAmount()!=null? df.getTotalEmploymentIncome().getAmount().toString():"");
                                          fields.setField((String)fieldMap.get("Section8:Question2:Child"),df.getFarmRanchBusinessIncome()!=null && df.getFarmRanchBusinessIncome().getAmount()!=null ? df.getFarmRanchBusinessIncome().getAmount().toString():"");
                                          fields.setField((String)fieldMap.get("Section8:Question3:Child"),df.getOtherIncome()!=null && df.getOtherIncome().getAmount()!=null? df.getOtherIncome().getAmount().toString():"");
                                         isFirst_8 = false;
                                   }
                                   else {
                                          add_child_cnt ++;
                                          if (add_child_cnt % 9 == 1  || addFirst ){
                                                 additionalChildDocument.newPage();
                                                 PdfPTable table=new PdfPTable(3);
                                           table.setWidthPercentage(100f);
                                           table.setSpacingAfter(0f);
                                           table.setKeepTogether(true);
                                            float[] widths = {45f,30f,25f};
                                            table.setWidths(widths);
                                            PdfPCell cell = new PdfPCell(new Paragraph("APPLICATION FOR HEALTH BENEFITS, Continued",FontFactory.getFont(FontFactory.HELVETICA, 11,Font.BOLD, Color.BLACK)));
                                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                            table.addCell(cell);
                                            cell = new PdfPCell(new Paragraph("VETERAN'S NAME  (Last, First, Middle)\n\n"+veteranName, font_times));
                                            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                                            table.addCell(cell);
                                            table.addCell( new Phrase("SOCIAL SECURITY NUMBER\n\n"+veteranSSN, font_times));
                                            cell = new PdfPCell (new Paragraph ("Section VIII - PREVIOUS CALENDAR YEAR GROSS ANNUAL INCOME OF VETERAN, SPOUSE AND DEPENDENT CHILDREN (Continued)",FontFactory.getFont(FontFactory.HELVETICA, 8,Font.BOLD, Color.BLACK )));
                                            cell.setColspan (3);
                                            cell.setHorizontalAlignment (Element.ALIGN_CENTER);
                                            cell.setBackgroundColor (Color.LIGHT_GRAY); //cell.setPadding (10.0f);
                                            table.addCell (cell);
                                            addFirst = false;
                                            additionalChildDocument.add(table);
                                    }
                                         PdfPTable table=new PdfPTable(3);
                                    table.setWidthPercentage(100f);
                                    table.setKeepTogether(true);
                                    float[] widths = {34f,33f,33f};
                                    table.setWidths(widths);
                                    table.setSpacingAfter(0f);
                                    PdfPCell cell = new PdfPCell (new Paragraph ("Child #"+childCnt,FontFactory.getFont(FontFactory.HELVETICA, 8,Font.BOLD, Color.BLACK )));
                                    cell.setColspan (3);
                                    cell.setHorizontalAlignment (Element.ALIGN_CENTER);
                              //    cell.setBackgroundColor (Color.LIGHT_GRAY); //cell.setPadding (10.0f);
                                    table.addCell (cell);
                                    String grossincome = df.getTotalEmploymentIncome()!=null && df.getTotalEmploymentIncome().getAmount()!=null? df.getTotalEmploymentIncome().getAmount().toString():"";
                                    table.addCell(new Phrase("1.GROSS ANNUAL INCOME FROM EMPLOYMENT  * (wages,bonuses,tips,etc.) EXCLUDING INCOME FROM YOUR FARM,RANCH,PROPERTYOR BUSINESS\n\n"+this.addCurrencySymbol(grossincome), font_courier));
                                    String netincome =df.getFarmRanchBusinessIncome()!=null && df.getFarmRanchBusinessIncome().getAmount()!=null? df.getFarmRanchBusinessIncome().getAmount().toString():"";
                                    table.addCell(new Phrase("2.NET INCOME FROM YOUR FARM,RANCH,PROPERTY,OR BUSINESS\n\n"+this.addCurrencySymbol(netincome), font_courier));
                                    String otherincome = df.getOtherIncome()!=null && df.getOtherIncome().getAmount()!= null ? df.getOtherIncome().getAmount().toString():"";
                                    table.addCell(new Phrase("3.LIST OTHER INCOME AMOUNTS (eg.Social Security, compensation, pension interest,dividends),EXCLUDING WELFARE.\n\n"+this.addCurrencySymbol(otherincome), font_courier));
                                    // additionalChildFinDocument.add(table);
                                    additionalChildDocument.add(table);
                                   }
                     }
            }

            // Section X
                childCnt = 0;
                add_child_cnt = 0;
                addFirst = true;
           for (Iterator itr =dependentFinancials.iterator(); itr.hasNext();) {
                df = (DependentFinancials) itr.next();
                dependent = df.getReportedOn();
                if ( dependent != null) {
                         childCnt ++;
                              if (isFirst_10){
                                     fields.setField((String)fieldMap.get("Section10:Question1:Child"),df.getCashAndBankAccountBalances()!=null && df.getCashAndBankAccountBalances().getAmount()!=null ? df.getCashAndBankAccountBalances().getAmount().toString(): "");
                              fields.setField((String)fieldMap.get("Section10:Question2:Child"),df.getRealEstate()!=null && df.getRealEstate().getAmount()!=null ? df.getRealEstate().getAmount().toString():"");
                              fields.setField((String)fieldMap.get("Section10:Question3:Child"),df.getOtherPropertyOrAssets()!=null && df.getOtherPropertyOrAssets().getAmount()!=null? df.getOtherPropertyOrAssets().getAmount().toString(): "");
                              isFirst_10 = false;
                              }
                              else{
                                    // new code
                                     add_child_cnt ++;
                                          if (add_child_cnt % 7 == 1  || addFirst ){
                                                 additionalChildDocument.newPage();
                                                 PdfPTable table=new PdfPTable(3);
                                           table.setWidthPercentage(100f);
                                           table.setSpacingAfter(0f);
                                           table.setKeepTogether(true);
                                            float[] widths = {45f,30f,25f};
                                            table.setWidths(widths);
                                            PdfPCell cell = new PdfPCell(new Paragraph("APPLICATION FOR HEALTH BENEFITS, Continued",FontFactory.getFont(FontFactory.HELVETICA, 11,Font.BOLD, Color.BLACK)));
                                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                                            table.addCell(cell);
                                            cell = new PdfPCell(new Paragraph("VETERAN'S NAME  (Last, First, Middle)\n\n"+veteranName, font_times));
                                            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                                            table.addCell(cell);
                                            table.addCell( new Phrase("SOCIAL SECURITY NUMBER\n\n"+veteranSSN, font_times));
                                            cell = new PdfPCell (new Paragraph ("Section X - PREVIOUS CALENDAR YEAR NET WORTH (Continued)",FontFactory.getFont(FontFactory.HELVETICA, 8,Font.BOLD, Color.BLACK )));
                                            cell.setColspan (3);
                                            cell.setHorizontalAlignment (Element.ALIGN_CENTER);
                                            cell.setBackgroundColor (Color.LIGHT_GRAY); //cell.setPadding (10.0f);
                                            table.addCell (cell);
                                            addFirst = false;
                                            additionalChildDocument.add(table);
                                          }
                                         // end of new code
                                    PdfPTable table=new PdfPTable(3);
                                 table.setWidthPercentage(100f);
                                 float[] widths = {34f,33f,33f};
                                    table.setWidths(widths);
                                    table.setSpacingAfter(0f);
                                    /*
                                    if (addFirst){
                                            PdfPCell cell = new PdfPCell (new Paragraph ("Section X - PREVIOUS CALENDAR YEAR NET WORTH (Continued)",FontFactory.getFont(FontFactory.HELVETICA, 8,Font.BOLD, Color.BLACK )));
                                            cell.setColspan (3);
                                            cell.setHorizontalAlignment (Element.ALIGN_CENTER);
                                            cell.setBackgroundColor (Color.LIGHT_GRAY); //cell.setPadding (10.0f);
                                            table.addCell (cell);
                                            addFirst = false;
                                    }
                                    */
                                    PdfPCell cell = new PdfPCell (new Paragraph ("Child #"+childCnt,FontFactory.getFont(FontFactory.HELVETICA, 8,Font.BOLD, Color.BLACK )));
                                    cell.setColspan (3);
                                    cell.setHorizontalAlignment (Element.ALIGN_CENTER);
                                    table.addCell (cell);
                                    String bankamt  = df.getCashAndBankAccountBalances()!=null && df.getCashAndBankAccountBalances().getAmount()!=null ? df.getCashAndBankAccountBalances().getAmount().toString(): "";
                                    table.addCell(new Phrase("1.CASH,AMOUNT IN BANK ACCOUNTS.\n\n"+this.addCurrencySymbol(bankamt),font_courier));
                                    String marketvalue = df.getRealEstate()!=null && df.getRealEstate().getAmount()!=null ? df.getRealEstate().getAmount().toString(): "";
                                    table.addCell(new Phrase("2.MARKET VALUE OF LAND AND BUILDINGS MINUS MORTGAGES AND LIENS. (e.g. second homes and non-income producing property. Do not countyour primary home.)\n\n"+this.addCurrencySymbol(marketvalue), font_courier));
                                    String othervalue = df.getOtherPropertyOrAssets()!=null && df.getOtherPropertyOrAssets().getAmount()!=null? df.getOtherPropertyOrAssets().getAmount().toString(): "";
                                    table.addCell(new Phrase("3.VALUE OF OTHER PROPERTY OR ASSETS (e.g. art, rare coins,collectables) MINUS THE AMOUNT YOU OWE ON THESE ITEMS. INCLUDE VALUE OFFARM, RANCH OR BUSINESS ASSETS. Exclude household effects and family vehicles.\n\n"+this.addCurrencySymbol(othervalue), font_courier));
                                    additionalChildDocument.add(table);
                              }
                }
           }
       }
    }
  }

    /**
     * Fill SECTION XII - ASSIGNMENT OF BENEFITS of the fillable PDF document
     *
     * @throws DocumentException
     * @throws IOException
     */

    private void fillSection12() throws DocumentException, IOException {
        fields.setField((String) fieldMap.get("Section12:Date"),
                new SimpleDateFormat("MM/dd/yyyy").format(new Date()));
    }



    /**
     * Remove the currency symbol (i.e. $)
     *
     * @param currency
     *            String value containing a currency amount that includes
     *            currency symbol (i.e. $)
     * @return String value containing a currency amount excluding currency
     *         symbol (i.e. $) since it is already provided on the form
     */

     private String removeCurrencySymbol(String currency) {
         if (currency != null && StringUtils.isEmpty(currency))
         { return currency.substring(1); }
         return "";
     }

     private String addCurrencySymbol(String currency) {
         if (currency != null && StringUtils.isNotEmpty(currency))
         { return "$"+" "+currency; }
         return "$";
     }
    private String getInsuranceCompanyAddrPhone(InsurancePolicy insurance) {
        StringBuffer insuranceInfo = new StringBuffer();
        if (insurance.getCompanyName() != null && StringUtils.isNotEmpty(insurance.getCompanyName()))
            insuranceInfo.append(insurance.getCompanyName());

        if (insurance.getAddress() != null && StringUtils.isNotEmpty(insurance.getAddress().getFormattedAddress())) {
            if (insuranceInfo.length() > 0) {
                insuranceInfo.append("\n");
            }
            insuranceInfo.append(insurance.getAddress().getFormattedAddress());
        }
        if (insurance.getBusinessPhone() != null && StringUtils.isNotEmpty(insurance.getBusinessPhone().getFormattedPhone())) {
            if (insuranceInfo.length() > 0) {
                insuranceInfo.append("\n");
            }
            insuranceInfo.append(insurance.getBusinessPhone().getFormattedPhone());
        }
        return insuranceInfo.toString();
    }

       private String getEmployerCompanyAddrPhone(Employment em){
             StringBuffer emInfo = new StringBuffer();
             if (em.getEmployerName() !=null && StringUtils.isNotEmpty(em.getEmployerName()) )
                    emInfo.append(em.getEmployerName());

             if (em.getEmployerAddress() !=null && StringUtils.isNotEmpty(em.getEmployerAddress().getFormattedAddress()) ){
                    if(emInfo.length() > 0) { emInfo.append("\n"); }
                           emInfo.append(em.getEmployerAddress().getFormattedAddress());
             }

             if(em.getEmployerPhone() !=null && StringUtils.isNotEmpty(em.getEmployerPhone())) {
                    if(emInfo.length() > 0) { emInfo.append("\n"); }
                           emInfo.append(em.getEmployerPhone());
             }
             return emInfo.toString();
       }

    private String getIndicatorCode(Boolean flag) {
        if(flag == null) {
            return Indicator.UNKNOWN.getCode();
        } else {
            return (flag.equals(Boolean.TRUE)) ? Indicator.YES.getCode() : Indicator.NO.getCode();
        }
    }

    private boolean isTrue(Boolean bool) {
        return bool != null && bool.booleanValue();
    }

    private boolean isTrue(Indicator ind) {
        return ind != null && ind.getCode().equals(Indicator.YES.getCode());
    }

    private boolean isFalse(Boolean bool) {
        return bool != null && !bool.booleanValue();
    }

    private boolean isFalse(Indicator ind) {
        return ind != null && ind.getCode().equals(Indicator.NO.getCode());
    }

    private boolean isUnknown(Boolean bool) {
        return bool == null;
    }

    private boolean isUnknown(Indicator ind) {
        return ind != null && ind.getCode().equals(Indicator.UNKNOWN.getCode());
    }

    private List getPatientVisitSummaries() {
       //  Map facilities = new HashMap ();
        Map patientVisits = null;
        Set facilityKeys = null;
        if (this.patientVisitSummaries == null)
                    this.patientVisitSummaries = new ArrayList ();
       patientVisits = person.getPatientVisitSummaries();
       if ( patientVisits !=  null)
             facilityKeys = patientVisits.keySet();

       if ( facilityKeys != null){
                    for (Iterator iter=facilityKeys.iterator(); iter.hasNext();) {
                           SiteYear siteYear = (SiteYear) iter.next ();
                     if(siteYear != null) {
                          VAFacility facility = siteYear.getFacility();
                          if ( facility!=null && facility.getType()!=null && facility.getType().getIsMedicalTreating()){
                                 PatientVisitSummary patientVisitSummary = (PatientVisitSummary)patientVisits.get(siteYear);
                                 this.patientVisitSummaries.add(patientVisitSummary);
                          }
                     }
                    }
       }
       return patientVisitSummaries;
       }

       private MilitaryServiceSiteRecord getLatestMilitaryServiceSiteRecord()  throws Exception
       {
           boolean isHECsiteRecordPresent = false;
           boolean isVOAsiteRecordPresent = false;
           boolean isVAMCsiteRecordPresent = false;
           MilitaryServiceSiteRecord latestSiteRec = null;
             MilitaryServiceSiteRecord siteRec = null;

             Iterator itr = null;
             if(this.militaryService != null) {
                    Set siteRecords = militaryService.getMilitaryServiceSiteRecords();
                    itr = siteRecords != null ? siteRecords.iterator() : null;
                    MilitaryServiceSiteRecord latestHECSiteRec = null;
                    MilitaryServiceSiteRecord latestVOASiteRec = null;
                    MilitaryServiceSiteRecord latestVAMCSiteRec = null;

                    // take the "latest" site data ESR has on file
                    while(itr != null && itr.hasNext()) {
                           siteRec = (MilitaryServiceSiteRecord) itr.next();
                           // HEC
                           if ( siteRec.getSite()!=null && VAFacility.CODE_HEC.getName().equalsIgnoreCase(siteRec.getSite().getName())){
                                 isHECsiteRecordPresent = true;
                                 if(latestHECSiteRec == null) {
                                        latestHECSiteRec = siteRec;
                                 } else {
                                        // if(latestHECSiteRec.getCreatedOn().before(siteRec.getCreatedOn()))
                                        if(latestHECSiteRec.getModifiedOn().before(siteRec.getModifiedOn()))
                                               latestHECSiteRec = siteRec;
                                 }
                           }

                           else  // VOA CODE_MHV
                                 if ( siteRec.getSite()!=null && VAFacility.CODE_MHV.getName().equalsIgnoreCase(siteRec.getSite().getName())){
                                               isVOAsiteRecordPresent = true;
                                               if(latestVOASiteRec == null) {
                                                     latestVOASiteRec = siteRec;
                                               }
                                               else {
                                                      if(latestVOASiteRec.getModifiedOn().before(siteRec.getModifiedOn()))
                                                            latestVOASiteRec = siteRec;
                                               }
                                        }
                                 else { // anything else consider VAMC
                                        isVAMCsiteRecordPresent = true;
                                        if(latestVAMCSiteRec == null) {
                                               latestVAMCSiteRec = siteRec;
                                        }
                                        else {
                                               if(latestVAMCSiteRec.getModifiedOn().before(siteRec.getModifiedOn()))
                                                     latestVAMCSiteRec = siteRec;
                                        }
                                 }
                           }

                    if (isHECsiteRecordPresent) latestSiteRec = latestHECSiteRec;
                    else if (isVAMCsiteRecordPresent) latestSiteRec = latestVAMCSiteRec;
                    else if (isVOAsiteRecordPresent) latestSiteRec = latestVOASiteRec;

              }
       return latestSiteRec;
       }

    private MilitaryServiceEpisode getLatestMilitaryServiceEpisode(MilitaryServiceSiteRecord mtsiterecords)  throws Exception
       {
       MilitaryServiceEpisode latestEpisode = null;
        Iterator itr = null;

             if(mtsiterecords != null) {
                    Set episodes = mtsiterecords.getMilitaryServiceEpisodes();
                    itr = episodes != null ? episodes.iterator() : null;

                    MilitaryServiceEpisode episode = null;
                    // take the "latest" episode for this guy
                    while(itr != null && itr.hasNext()) {
                           episode = (MilitaryServiceEpisode) itr.next();
                           if(latestEpisode == null) {
                                 latestEpisode = episode;
                           } else {
                                 if(latestEpisode.getEndDate() != null && latestEpisode.getEndDate().compareTo(episode.getEndDate()) < 0)
                                        latestEpisode = episode;
                           }
                    }
             }
             return latestEpisode;
       }

    private List sortPrivateInsurance(Set pinsr )
    {
       if ( pinsr == null ) return null;
        List privateList = new ArrayList(pinsr);
        if(!privateList.isEmpty())
        {
            Comparator comparator = new Comparator()
            {
                public int compare(Object pObject1, Object pObject2)
                {
                    Date startImDate1 = (pObject1 != null && pObject1 instanceof PrivateInsurance) ? ((PrivateInsurance)pObject1).getModifiedOn() : null;
                    Date startImDate2 = (pObject2 != null && pObject2 instanceof PrivateInsurance) ? ((PrivateInsurance)pObject2).getModifiedOn() : null;
                    if(startImDate1 != null && startImDate2 != null)
                    {
                        // return (startImDate1.compareTo(startImDate2)); ascending oldest -> latest date
                           long thisTime = startImDate1.getTime();
                           long secondTime = startImDate2.getTime();
                           return (thisTime > secondTime ? -1 : (thisTime==secondTime ? 0 : 1));
                    }
                    return 0;
                }
            };
            Collections.sort(privateList,comparator);
        }
        return privateList;
    }

  private String getLastFirstMiddleByComma(Name name){

       StringBuffer buf = new StringBuffer();
           if (name == null )
              return null;

           String flname = name.getFormattedName();
           String middleName = name.getMiddleName();
           if (StringUtils.isNotBlank(flname))
        {
              buf.append(flname);
        }
           if (StringUtils.isNotBlank(middleName))
        {
            if (buf.length() > 0)
            {
                buf.append(", ");
            }
            buf.append(middleName);
        }
        return buf.toString().toUpperCase();
       }

   //display version of OMB approved HCA forms
   public void display1010EZ(HttpServletResponse resp)throws Exception{
       InputStream input= null;
       DataOutputStream dataostream = null;
       String finalFname = this.getOutputFilePath() + this.getFinalFileName();
       log.info("file is: " + finalFname);
       try {

             input= new FileInputStream(finalFname);
             log.info("file input is: " + input.toString());
           resp.setContentType("application/pdf");
           resp.setHeader("Content-Disposition", "inline; filename=1010EZ Display");
           resp.setHeader("Accept-Ranges", "bytes");


           dataostream = new DataOutputStream(resp.getOutputStream());
           byte[] buf = new byte[4096];
           int bytesRead;
           while ((bytesRead = input.read(buf)) > 0) {
              dataostream.write(buf, 0, bytesRead);
           }

       } finally {
             if (input != null) {
                    input.close();
             }
             if (dataostream != null) {
                    log.info("output stream is: " + dataostream.toString());

                     dataostream.close();
             }
             File file_temp = new File(finalFname);
             log.info("final file from file_temp is: " + file_temp );
             if ( file_temp!=null && file_temp.exists()) {
               file_temp.delete();
            }
       }
   }

    private String getBirthPlace(String city, String state) {
             StringBuffer birthPlace = new StringBuffer();
             if (city!= null) {
                    birthPlace.append(city);
             }
             if (birthPlace.length() > 0) {
                           birthPlace.append(", ");
             }
             if (state != null) {
                    birthPlace.append(state);
             }
             return birthPlace.toString();
       }

      private InputStream readTemplate(String fillableFormFileName)throws Exception
      {
            FileInputStream inFillablePDFFile = new FileInputStream(fillableFormFileName);
            InputStream inFillablePDF = (InputStream)inFillablePDFFile;
            return inFillablePDF;
      }

       public VOAApplication getApp() {
             return app;
       }

       public void setApp(VOAApplication app) {
             this.app = app;
       }

       public Form getVoaForm() {
             return voaForm;
       }

       public void setVoaForm(Form voaForm) {
             this.voaForm = voaForm;
       }

       public MilitaryServiceInfo getMilitaryServiceInfo() {
             return militaryServiceInfo;
       }

       public void setMilitaryServiceInfo(MilitaryServiceInfo militaryServiceInfo) {
             this.militaryServiceInfo = militaryServiceInfo;
       }

       public List<InsuranceInfo> getInsuranceInfo() {
             return insuranceInfo;
       }

       public void setInsuranceInfo(List<InsuranceInfo> insuranceInfo) {
             this.insuranceInfo = insuranceInfo;
       }

       public FinancialsInfo getFinancialsInfo() {
             return financialsInfo;
       }

       public void setFinancialsInfo(FinancialsInfo financialsInfo) {
             this.financialsInfo = financialsInfo;
       }

}

