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.financials.action.FinancialsConstants;
import gov.va.med.esr.common.infra.ImpreciseDate;
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.insurance.Medicare;
import gov.va.med.esr.common.model.ee.MedicaidFactor;
import gov.va.med.esr.common.model.lookup.Country;
import gov.va.med.esr.common.model.lookup.EmploymentStatus;
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.MaritalStatus;
import gov.va.med.esr.common.model.lookup.Relationship;
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.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.Employment;
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.id.VPIDEntityKey;
import gov.va.med.esr.service.PersonIdentityTraits;
import gov.va.med.fw.model.lookup.Lookup;
import gov.va.med.fw.util.StringUtils;

/* 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.BufferedWriter;
import java.io.FileWriter;
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.DataOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;

import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
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.log4j.Logger;
import java.awt.Color;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Wen Lin - Financials1010EZRRenewal is used by financial overview page to
 *         generate the 1010EZR form in PDF format for printing. This class fills
 *         in the values in a fillable 1010EZR 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 1010EZR form.
 */

public class Financials1010EZRRenewal {

    private static final Logger log = Logger.getLogger(Financials1010EZRRenewal.class);
   // private static final String fillable1010EZRFileName = "C:\\temp\\Fillable1010EZRHealthcareApplication.pdf";
   // private static final String fillable1010EZRFileName = "Fillable1010EZRHealthcareApplication.pdf";
    private HashMap fieldMap = new HashMap();
    private Person person = null;
    private Set insurances;
    private Set privateinsurances;
    private Set medicares;
    private Set dependentFinancials;
    private SpouseFinancials sf = null;
    private FinancialStatement ftmt = null;
    private Integer incomeYear;
    private boolean FinDisclosureFlag = false;
    private  Spouse spouse = 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 InputStream fillablePDF;
    private FileOutputStream outStaticForm;
    private FileOutputStream outAdditionalInsForm;
    private FileOutputStream outAdditionalChildForm;
 //   private FileOutputStream outAdditionalChildFinForm;
    private FileOutputStream outCombinedForm;
//    private HttpServletResponse response;
    private String templateLocation;
    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 Financials1010EZRRenewal (Person person, Integer incomeYear, String templatePath) {
 //  public Financials1010EZRRenewal (Person person, Integer incomeYear, String templatePath, String outputPath) { 
	 public Financials1010EZRRenewal (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.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);
    }
    
    private void setOutputFiles(String vetId){
    	
    	String currDate = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
    	currDate = currDate==null?"":currDate.trim();
    	// String curDate = new SimpleDateFormat("yyyyMMddHHmmss").format(DateUtils.getCurrentDateTime());
    	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;
    	String fInd = FinancialsConstants.FLAG_1010EZR;
    	
    //	this.filePath = FinancialsConstants.PDF_OUTPUT_FILE_PATH;
    	this.formFileName = vetId+fInd+fSeparater+fForm+fSeparater+currDate+fExt;
    	this.additionalInsFileName = vetId+fInd+fSeparater+fInsurance+fSeparater+currDate+fExt;
    	this.additionalChildFileName = vetId+fInd+fSeparater+fChild+fSeparater+currDate+fExt;
    	this.finalFileName = vetId+fInd+fSeparater+fFinal+fSeparater+currDate+fExt;
    	// this.formFileName = "1010EZR_Form1.pdf";
    	// this.additionalInsFileName = "1010EZR_Additional_InsForm2.pdf";
    	// this.additionalChildFileName = "1010EZR_Additional_ChildForm2.pdf";
    	// this.finalFileName = "1010EZR_Final_Complete_Form.pdf";
    }
    
    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;
    }
 
    /**
     * 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) {
            e.printStackTrace();
        }
    }
    
    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) {
            e.printStackTrace();
        }
    }
    
    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) {
            e.printStackTrace();
        }
    }
    
    /**
     * Fill each section of the fillable PDF, and create additional files if
     * necessary. If additional files are necessary, the two PDFs are
     * concatenated.
     * 
     */
    public void get1010EZR() throws Exception {
        try {

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

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

            // Section 3 - Employment Information
            fillSection3();
     
            // Section  5 - Financial Disclosure 
            fillSection5();
          
             // Section 6 - Spouse/Dependent Financial Information
             fillSection6();
             
             // Section 7 - Previous Calendar Year Gross Annual Income of Veteran, Spouse, and Dependent Children 
             // Section 8 - Previous Calendar Year Deductible Expenses
             // Section 9 - Previous Calendar Year Net Worth
             // fill section 7, 8 and 9
            fillSection7_8_9();

            // Section 11 - Assignment of Benefits
            fillSection11();

            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 1010EZR");
                List pdfs;
                OutputStream output;
                FileInputStream inStaticForm = null;
                FileInputStream inAdditionalInsForm = null;
                FileInputStream inAdditionalChildForm = null;
           //     FileInputStream inAdditionalChildFinForm = null;
                pdfs = new ArrayList();
             //   log.debug("Creating file " + filePath + formFileName);
                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);
                }
               // log.debug("Creating file " + filePath + finalFileName);
                output = new FileOutputStream(this.getOutputFilePath() + this.getFinalFileName());
                concatPDFs(pdfs, output, true);
                output.close();
                inStaticForm.close();
                
                if (inAdditionalChildForm!=null)
                	inAdditionalChildForm.close();
                if (inAdditionalInsForm != null)
                	inAdditionalInsForm.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();
        }
    }
   
    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_CENTER, ""+ currentPageNumber + " of " + totalPages, 520,5, 0);
                        cb.endText();
                    }
                }
                pageOfCurrentReaderPDF = 0;
            }
            outputStream.flush();
            document.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document.isOpen())
                document.close();
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    private void initializeFieldMap() {
    	// header info
    	fieldMap.put("VeteranName", "vha1010ezrprint[0].#subform[1].pg2_veterans_name[0]");
    	fieldMap.put("VeteranSSN", "vha1010ezrprint[0].#subform[1].SSN_pg2[0]");
    	// section I - general information
        fieldMap.put("Section1:Question1", "vha1010ezrprint[0].#subform[0].veterans_name[0]");
        fieldMap.put("Section1:Question2", "vha1010ezrprint[0].#subform[0].other_names[0]");
        //fieldMap.put("Section1:Question3", "vha1010ezrprint[0].#subform[0].Never_Married[0]");
        fieldMap.put("Section1:Question3:Male","Check Box24");   //Male
        fieldMap.put("Section1:Question:Female","Check Box25");   //Female
        fieldMap.put("Section1:Question4", "vha1010ezrprint[0].#subform[0].SSN1[0]");
        fieldMap.put("Section1:Question5", "vha1010ezrprint[0].#subform[0].Date_of_birth[0]");
        fieldMap.put("Section1:Question6", "vha1010ezrprint[0].#subform[0].perm_address[0]");
        fieldMap.put("Section1:Question6A", "vha1010ezrprint[0].#subform[0].city[0]");
        fieldMap.put("Section1:Question6B", "vha1010ezrprint[0].#subform[0].state[0]");
        fieldMap.put("Section1:Question6C", "vha1010ezrprint[0].#subform[0].zip[0]");
        fieldMap.put("Section1:Question6D", "vha1010ezrprint[0].#subform[0].county[0]");
        fieldMap.put("Section1:Question6E", "vha1010ezrprint[0].#subform[0].home_number[0]");
        fieldMap.put("Section1:Question6F", "vha1010ezrprint[0].#subform[0].email_address[0]");
        fieldMap.put("Section1:Question6G", "vha1010ezrprint[0].#subform[0].cell_phone_number[0]");
        //fieldMap.put("Section1:Question6H", "vha1010ezrprint[0].#subform[0].pager_phone_number[0]");
        //fieldMap.put("Section1:Question7", "vha1010ezrprint[0].#subform[0].CurrentnMaritalStatus[0]");
        fieldMap.put("Section1:Question7:Married", "Check Box18");  //Married
        fieldMap.put("Section1:Question7:NeverMarried", "Check Box19");  //Never married
        fieldMap.put("Section1:Question7:Separated", "Check Box20");  //Separated
        fieldMap.put("Section1:Question7:Widowed", "Check Box21");  //Widowed
        fieldMap.put("Section1:Question7:Divorced", "Check Box22");  //Divorced
        fieldMap.put("Section1:Question7:Unknown", "Check Box23");  //Unknown
        fieldMap.put("Section1:Question8", "vha1010ezrprint[0].#subform[0].name_address[0]");
        fieldMap.put("Section1:Question8A", "vha1010ezrprint[0].#subform[0].next_of_kin_phone1[0]");
        fieldMap.put("Section1:Question8B", "vha1010ezrprint[0].#subform[0].next_of_kin_phone2[0]");
        fieldMap.put("Section1:Question9", "vha1010ezrprint[0].#subform[0].name_address_1[0]");
        fieldMap.put("Section1:Question9A", "vha1010ezrprint[0].#subform[0].emergency2[0]");
        fieldMap.put("Section1:Question9B", "vha1010ezrprint[0].#subform[0].emergency2[1]");
        // no Question 10 mapping in current online 1010EZR form, left unchecked
        
        // Section 2 Insurance
        //fieldMap.put("Section2:Question1","vha1010ezrprint[0].#subform[0].YES_No1[0]");
        fieldMap.put("Section2:Question1:Yes", "Check Box16");  // Covered by spouse insurance Yes
        fieldMap.put("Section2:Question1:No", "Check Box17");  // Covered by souse insurance No
        fieldMap.put("Section2:Question2", "vha1010ezrprint[0].#subform[0].health_ins_co[0]");
        fieldMap.put("Section2:Question3", "vha1010ezrprint[0].#subform[0].policy_holder[0]");
        fieldMap.put("Section2:Question4", "vha1010ezrprint[0].#subform[0].policy_number[0]");
        fieldMap.put("Section2:Question5", "vha1010ezrprint[0].#subform[0].group_code[0]");
        //fieldMap.put("Section2:Question6", "vha1010ezrprint[0].#subform[0].Yes_No2[0]");
        fieldMap.put("Section2:Question6:Yes", "Check Box14");  //Medicaid eligibility Yes
        fieldMap.put("Section2:Question6:No", "Check Box15");  // Medicaid eligibility No
        //fieldMap.put("Section2:Question7", "vha1010ezrprint[0].#subform[0].Yes_No3[0]");
        fieldMap.put("Section2:Question7:Yes", "Check Box12");  //Medicare Part A Yes
        fieldMap.put("Section2:Question7:No", "Check Box13");	// Medicare Part A No
        fieldMap.put("Section2:Question7A", "vha1010ezrprint[0].#subform[0].effective_date7[0]");
        //fieldMap.put("Section2:Question8", "vha1010ezrprint[0].#subform[0].Yes_no4[0]");
        fieldMap.put("Section2:Question8:Yes", "Check Box10");  //Medicare Part B Yes
        fieldMap.put("Section2:Question8:No", "Check Box11");	// Medicare Part B No
        fieldMap.put("Section2:Question8A", "vha1010ezrprint[0].#subform[0].effective_date8[0]");
        fieldMap.put("Section2:Question9", "vha1010ezrprint[0].#subform[0].exact_name[0]");
        fieldMap.put("Section2:Question10", "vha1010ezrprint[0].#subform[0].medicare_claim_number[0]");
       
        // Section 3 - Employment
        fieldMap.put("Section3:Question1:FullTime", "Check Box28");
        fieldMap.put("Section3:Question1:NotEmployed", "Check Box30");
        fieldMap.put("Section3:Question1:Retired", "Check Box31");
        fieldMap.put("Section3:Question1:PartTime", "Check Box29");
        //fieldMap.put("Section3:Question1:EmploymentStatus", "vha1010ezrprint[0].#subform[0].Employment1[0]");
        fieldMap.put("Section3:Question1:RetirementDate", "vha1010ezrprint[0].#subform[0].date_of_retirement1[0]");
        fieldMap.put("Section3:Question1A", "vha1010ezrprint[0].#subform[0].company_name_address1[0]");
        fieldMap.put("Section3:Question2:FullTime", "Check Box32");
        fieldMap.put("Section3:Question2:NotEmployed", "Check Box34");
        fieldMap.put("Section3:Question2:Retired", "Check Box35");
        fieldMap.put("Section3:Question2:PartTime", "Check Box33");
        //fieldMap.put("Section3:Question2:EmploymentStatus", "vha1010ezrprint[0].#subform[0].Employment2[0]");
        fieldMap.put("Section3:Question2:RetirementDate", "vha1010ezrprint[0].#subform[0].date_of_retirement2[0]");
        fieldMap.put("Section3:Question2A", "vha1010ezrprint[0].#subform[0].company_name_address2[0]");
       
        // Section 4 Financial Disclosure
        fieldMap.put("Section4:No", "Check Box26");
        fieldMap.put("Section4:Yes", "Check Box27"); 
     
        // Section 6 Dependent Info
        fieldMap.put("Section6:Question1", "vha1010ezrprint[0].#subform[1].spouse_name[0]");
        fieldMap.put("Section6:Question1A", "vha1010ezrprint[0].#subform[1].spouse_maiden_name[0]");
        fieldMap.put("Section6:Question1B", "vha1010ezrprint[0].#subform[1].spouse_SSN[0]");
        fieldMap.put("Section6:Question1C", "vha1010ezrprint[0].#subform[1].spouse_dob[0]");
        fieldMap.put("Section6:Question1D", "vha1010ezrprint[0].#subform[1].date_of_marriage[0]");
        fieldMap.put("Section6:Question1E", "vha1010ezrprint[0].#subform[1].spouse_address[0]");
        fieldMap.put("Section6:Question2", "vha1010ezrprint[0].#subform[1].childs_name[0]");
        //fieldMap.put("Section6:Question2A", "vha1010ezrprint[0].#subform[1].Relationship[0]");
        fieldMap.put("Section6:Question2A:Son","Check Box6");   //Son
        fieldMap.put("Section6:Question2A:Daughter","Check Box7");   //Daughter
        fieldMap.put("Section6:Question2A:Stepson","Check Box8");   //Stepson
        fieldMap.put("Section6:Question2A:Stepdaughter","Check Box9");   //Stepdaughter
        fieldMap.put("Section6:Question2B", "vha1010ezrprint[0].#subform[1].child_SSN[0]");
        fieldMap.put("Section6:Question2C", "vha1010ezrprint[0].#subform[1].dependent_date[0]");
        fieldMap.put("Section6:Question2D", "vha1010ezrprint[0].#subform[1].child_dob[0]");
        //fieldMap.put("Section6:Question2E", "vha1010ezrprint[0].#subform[1].Page2_Yes_No3[0]");
        fieldMap.put("Section6:Question2E:Yes","Check Box2");   //Child disabled Yes
        fieldMap.put("Section6:Question2E:No","Check Box3");   //Child disabled No
        //fieldMap.put("Section6:Question2F", "vha1010ezrprint[0].#subform[1].Page2_Yes_No4[0]");
        fieldMap.put("Section6:Question2F:Yes","Check Box4");   //Child attended school Yes
        fieldMap.put("Section6:Question2F:No","Check Box5");   //Child attended school No
        fieldMap.put("Section6:Question2G", "vha1010ezrprint[0].#subform[1].expenses_paid[0]");
        fieldMap.put("Section6:Question3:Spouse", "vha1010ezrprint[0].#subform[1].spouse_amount[0]");
        fieldMap.put("Section6:Question3:Child", "vha1010ezrprint[0].#subform[1].child_amount[0]");
        fieldMap.put("Section6:Question3:Yes","Check Box1");   //If dependent did not live with you, did you provide support  Yes

        // Section 7 Pervious year gross anuall income
        fieldMap.put("Section7:Question1:Veteran", "vha1010ezrprint[0].#subform[1].veteran_amount1[0]");
        fieldMap.put("Section7:Question1:Spouse", "vha1010ezrprint[0].#subform[1].spouse_amount1[0]");
        fieldMap.put("Section7:Question1:Child", "vha1010ezrprint[0].#subform[1].child_amount1[0]");
        fieldMap.put("Section7:Question2:Veteran", "vha1010ezrprint[0].#subform[1].veteran_amount2[0]");
        fieldMap.put("Section7:Question2:Spouse", "vha1010ezrprint[0].#subform[1].spouse_amount2[0]");
        fieldMap.put("Section7:Question2:Child", "vha1010ezrprint[0].#subform[1].child_amount2[0]");
        fieldMap.put("Section7:Question3:Veteran", "vha1010ezrprint[0].#subform[1].veteran_amount3[0]");
        fieldMap.put("Section7:Question3:Spouse", "vha1010ezrprint[0].#subform[1].spouse_amount3[0]");
        fieldMap.put("Section7:Question3:Child", "vha1010ezrprint[0].#subform[1].child_amount3[0]");

        // Section 8 previous calendar year deductible expenses

        fieldMap.put("Section8:Question1", "vha1010ezrprint[0].#subform[1].previous_amount1[0]");
        fieldMap.put("Section8:Question2", "vha1010ezrprint[0].#subform[1].previous_amount2[0]");
        fieldMap.put("Section8:Question3", "vha1010ezrprint[0].#subform[1].previous_amount3[0]");

        // Section  9 pervious calendar year net worth
        fieldMap.put("Section9:Question1:Veteran", "vha1010ezrprint[0].#subform[1].previous_veteran_amount1[0]");
        fieldMap.put("Section9:Question1:Spouse", "vha1010ezrprint[0].#subform[1].previous_spouse_amount1[0]");
        fieldMap.put("Section9:Question1:Child", "vha1010ezrprint[0].#subform[1].previous_child_amount1[0]");
        fieldMap.put("Section9:Question2:Veteran", "vha1010ezrprint[0].#subform[1].previous_veteran_amount2[0]");
        fieldMap.put("Section9:Question2:Spouse", "vha1010ezrprint[0].#subform[1].previous_spouse_amount2[0]");
        fieldMap.put("Section9:Question2:Child", "vha1010ezrprint[0].#subform[1].previous_child_amount2[0]");
        fieldMap.put("Section9:Question3:Veteran", "vha1010ezrprint[0].#subform[1].previous_veteran_amount3[0]");
        fieldMap.put("Section9:Question3:Spouse", "vha1010ezrprint[0].#subform[1].previous_spouse_amount3[0]");
        fieldMap.put("Section9:Question3:Child", "vha1010ezrprint[0].#subform[1].previous_child_amount3[0]");

        // Section 11 signature & date
        fieldMap.put("Section11:Date", "vha1010ezrprint[0].#subform[1].signature_date[0]");

    }
    
    private void fillSection1() throws DocumentException, IOException {
    	// log.info("1010EZR fillSection1 ");
        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("VeteranName"),p_legalname);
        fields.setField((String) fieldMap.get("Section1:Question2"),p_aliasname);

        if (person.getGender() != null) {
            if (person.getGender().getName().equals("Male")) {
                //fields.setField((String) fieldMap.get("Section1:Question3"), "0");
            	fields.setField((String)fieldMap.get("Section1:Question3:Male"), "Yes");  //DM
            } else if (person.getGender().getName().equals("Female")) {
                //fields.setField((String) fieldMap.get("Section1:Question3"), "1");
            	fields.setField((String)fieldMap.get("Section1:Question3:Female"), "Yes");  //DM
            }
        }
        
       SSN officialSSN = person.getOfficialSsn();
       this.veteranSSN = officialSSN!=null? JspUtils.displaySSN(officialSSN.getSsnText()):"";
       fields.setField((String)fieldMap.get("Section1:Question4"),officialSSN!=null? JspUtils.displaySSN(officialSSN.getSsnText()):"");
       fields.setField((String)fieldMap.get("VeteranSSN"),officialSSN!=null? JspUtils.displaySSN(officialSSN.getSsnText()):"");
       ImpreciseDate birthdate = null;
       if (person.getBirthRecord() != null)
            birthdate = person.getBirthRecord().getBirthDate();
       fields.setField((String) fieldMap.get("Section1:Question5"), DateUtils.format(birthdate, null));

        // 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:Question6"),resultBuffer.toString());
            fields.setField((String) fieldMap.get("Section1:Question6A"),permAddress.getCity());
            fields.setField((String)fieldMap.get("Section1:Question6B"),stateProvince);
            fields.setField((String)fieldMap.get("Section1:Question6C"),zipPostalCode);
            fields.setField((String)fieldMap.get("Section1:Question6D"),permAddress.getCounty());
        }

        Phone homephone = person.getHomePhone();
        if (homephone != null)
            fields.setField((String)fieldMap.get("Section1:Question6E"),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:Question6G"),cellphonenumber);
        //fields.setField((String)fieldMap.get("Section1:Question6H"),pagephonenumber);
        fields.setField((String)fieldMap.get("Section1:Question6F"),emailaddress);

        MaritalStatus mstatus = person.getMaritalStatus();
        if (mstatus != null) {
            if (mstatus.getName().equalsIgnoreCase("MARRIED")) {
                //fields.setField((String)fieldMap.get("Section1:Question7"), "0");
            	fields.setField((String)fieldMap.get("Section1:Question7:Married"), "Yes");
            } else if (mstatus.getName().equalsIgnoreCase("NEVER MARRIED")) {
                //fields.setField((String)fieldMap.get("Section1:Question7"), "1");
            	fields.setField((String)fieldMap.get("Section1:Question7:NeverMarried"), "Yes");
            } else if (mstatus.getName().equalsIgnoreCase("SEPARATED")) {
                //fields.setField((String)fieldMap.get("Section1:Question7"), "2");
            	fields.setField((String)fieldMap.get("Section1:Question7:Separated"), "Yes");
            } else if (mstatus.getName().toUpperCase().indexOf("WIDOW") >= 0) {
                //fields.setField((String)fieldMap.get("Section1:Question7"), "3");
            	fields.setField((String)fieldMap.get("Section1:Question7:Widowed"), "Yes");
            } else if (mstatus.getName().equalsIgnoreCase("UNKNOWN")) {
                //fields.setField((String)fieldMap.get("Section1:Question7"), "5");
            	fields.setField((String)fieldMap.get("Section1:Question7:Unknown"), "Yes");
            } else if (mstatus.getName().equalsIgnoreCase("DIVORCED")) {
                //fields.setField((String)fieldMap.get("Section1:Question7"), "4");
            	fields.setField((String)fieldMap.get("Section1:Question7: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_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());
            String a_w_phone = Phone.getFormattedPhone(primary_next_of_kin.getAlternatePhone());
            String a_addr = p_address != null ? p_address.getFormattedAddress(): "";
            
            fields.setField((String) fieldMap.get("Section1:Question8"), ( a_name + "\n" + a_addr + "    Relationship: " + a_role).toString());
            fields.setField((String) fieldMap.get("Section1:Question8A"),a_h_phone);
            fields.setField((String) fieldMap.get("Section1:Question8B"), a_w_phone);
        }

        if (emergency_contact != null) {
            Address e_address = emergency_contact.getAddress();
            String e_addr = 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:Question9"),e_name + "\n" + e_addr + "   Relationship: " + e_role);
            fields.setField((String) fieldMap.get("Section1:Question9A"),e_h_phone);
            fields.setField((String) fieldMap.get("Section1:Question9B"),e_w_phone);
        }
        /* Question10 left unchecked based on UC Specification */
    }

    /**
     * Fill SECTION II - INSURANCE INFORMATION of the fillable PDF document
     * 
     * @throws DocumentException
     * @throws IOException
     */
    private void fillSection2() throws DocumentException, IOException {
    	// log.info("1010EZR fillSection2 ");
        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"),"0");
            	fields.setField((String)fieldMap.get("Section2:Question6:No"),"No");
            	fields.setField((String)fieldMap.get("Section2:Question6:Yes"),"Yes");}
            else if ( Boolean.FALSE.equals(medicaidfactor.getEligibleForMedicaid()))
            //fields.setField((String) fieldMap.get("Section2:Question6"),"1");
        	fields.setField((String)fieldMap.get("Section2:Question6:No"),"Yes");

        if (insurances != null && insurances.size() != 0)
            //fields.setField((String) fieldMap.get("Section2:Question1"),"0");
        	fields.setField((String)fieldMap.get("Section2:Question1:Yes"),"Yes");
        else
            //fields.setField((String) fieldMap.get("Section2:Question1"),"1");
        	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("HEALTH BENEFITS RENEWAL, 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"), "0");
            	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"),"1");
            	fields.setField((String)fieldMap.get("Section2:Question8:No"), "Yes");
            
            if (LatestMedicareA != null) {
                //fields.setField((String) fieldMap.get("Section2:Question7"), "0");
            	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"), "1");
            	fields.setField((String)fieldMap.get("Section2:Question7:No"), "Yes");
        }
    }

    /**
     * Fill SECTION III - EMPLOYMENT INFORMATION of the fillable PDF document
     * 
     * @throws DocumentException
     * @throws IOException
     */
    private void fillSection3() throws DocumentException, IOException {
    	// log.info("1010EZR fillSection3 ");
    	 // fulltime = 0 partime = 1 not employed = 2 retired = 3
    	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));
    			}
    		}
        }
    }
      
     private void fillSection5() throws DocumentException, IOException { 
    	 // log.info("1010EZR fillSection5 ");
         IncomeTest test = person.getIncomeTest(this.incomeYear); 
        
         if ( test == null || test.getDiscloseFinancialInformation() == null)
        	 FinDisclosureFlag = false;
         
         else {
	         if(isTrue(test.getDiscloseFinancialInformation()))  {
	             fields.setField((String) fieldMap.get("Section4:Yes"),"Yes");
	             FinDisclosureFlag = true;
	         }
	         else if(isFalse(test.getDiscloseFinancialInformation()))  {
	             fields.setField((String) fieldMap.get("Section4:No"),"Yes");
	             FinDisclosureFlag = false;
	         }
         }
         
         // test only
        //  FinDisclosureFlag = true;
     }

    /**
     * Fill SECTION VI - DEPENDENT INFORMATION of the fillable PDF document
     * 
     * @throws DocumentException
     * @throws IOException
     */
 private void fillSection6() throws DocumentException, IOException { 
	 
	 // log.info("1010EZR fillSection6 ");
     if (spouse != null) {
         fields.setField((String)fieldMap.get("Section6:Question1"),spouse.getName()!= null ? this.getLastFirstMiddleByComma(spouse.getName()): "");
         fields.setField((String)fieldMap.get("Section6:Question1A"),spouse.getMaidenName());
         fields.setField((String)fieldMap.get("Section6:Question1B"),spouse.getOfficialSsn()!= null ? JspUtils.displaySSN(spouse.getOfficialSsn().getSsnText()): "");
         fields.setField((String)fieldMap.get("Section6:Question1C"),DateUtils.format(spouse.getDob(), null));
         fields.setField((String)fieldMap.get("Section6:Question1D"),DateUtils.format(spouse.getMarriageDate(), null));
         // new VOA 3.1
       //   String spAddr = spouse.getAddress()!= null? spouse.getAddress().getFormattedAddress():"";
       //  String spPhone = spouse.getHomePhone()!=null? spouse.getHomePhone().getFormattedPhone():"";
         fields.setField((String)fieldMap.get("Section6:Question1E"),getSpouseAddressPhone(spouse)); 
         
         if (FinDisclosureFlag && sf.getLivedWithPatient()!= null && !sf.getLivedWithPatient().booleanValue()){
            //fields.setField((String)fieldMap.get("Section6:Question3:Spouse"),ftmt.getContributionToSpouse()!=null? ftmt.getContributionToSpouse().toString(): "");
        	 fields.setField((String)fieldMap.get("Section6:Question3:Yes"),"Yes");   //DM 
         }   
     }
     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("Section6:Question2"), dependent.getName()!=null ?this.getLastFirstMiddleByComma(dependent.getName()):"" ); 
                    if (dependent.getRelationship()!=null){
	                    if( Relationship.CODE_SON.getCode().equals(dependent.getRelationship().getCode()) )
	                        //fields.setField((String)fieldMap.get("Section6:Question2A"),"3");
	                    	fields.setField((String)fieldMap.get("Section6:Question2A:Son"),"Yes");   //
	                    else if ( Relationship.CODE_DAUGHTER.getCode().equals(dependent.getRelationship().getCode()) )
	                         //fields.setField((String)fieldMap.get("Section6:Question2A"),"0");
	                    	fields.setField((String)fieldMap.get("Section6:Question2A:Daughter"),"Yes");   //DM 
	                    else if ( Relationship.CODE_STEPSON.getCode().equals(dependent.getRelationship().getCode()) )
	                         //fields.setField((String)fieldMap.get("Section6:Question2A"),"1");
	                    	fields.setField((String)fieldMap.get("Section6:Question2A:Stepson"),"Yes");   //
	                    else if ( Relationship.CODE_STEPDAUGHTER.getCode().equals(dependent.getRelationship().getCode()) )
	                         //fields.setField((String)fieldMap.get("Section6:Question2A"),"2");
	                    	fields.setField((String)fieldMap.get("Section6:Question2A:Stepdaughter"),"Yes");   //
                    }   
                    fields.setField((String)fieldMap.get("Section6:Question2B"),dependent.getOfficialSsn()!=null? JspUtils.displaySSN(dependent.getOfficialSsn().getSsnText()):"" );
                    fields.setField((String)fieldMap.get("Section6:Question2C"),DateUtils.format(dependent.getStartDate(), null));
                    fields.setField((String)fieldMap.get("Section6:Question2D"),DateUtils.format(dependent.getDob(), null));
                    
                    if (df.getIncapableOfSelfSupport()!=null && df.getIncapableOfSelfSupport().booleanValue())
                        //fields.setField((String)fieldMap.get("Section6:Question2E"),"0");
                    	fields.setField((String)fieldMap.get("Section6:Question2E:Yes"),"Yes");   //DM  
                    	
                    else
                        //fields.setField((String)fieldMap.get("Section6:Question2E"),"1");
                    	fields.setField((String)fieldMap.get("Section6:Question2E:No"),"Yes");   //DM 
                    
                    
                    if (df.getAttendedSchool()!=null && df.getAttendedSchool().booleanValue())
                        //fields.setField((String)fieldMap.get("Section6:Question2F"),"0");
                    	fields.setField((String)fieldMap.get("Section6:Question2F:Yes"),"Yes");   //DM 
                    else
                        //fields.setField((String)fieldMap.get("Section6:Question2F"),"1");
                    	fields.setField((String)fieldMap.get("Section6:Question2F:No"),"Yes");   //DM 
                    
                    if (FinDisclosureFlag ){
                        if (df.getLivedWithPatient()!= null && !df.getLivedWithPatient().booleanValue())
                            //fields.setField((String)fieldMap.get("Section6:Question3:Child"),df.getAmountContributedToSupport()!=null? df.getAmountContributedToSupport().toString(): "");
                        	fields.setField((String)fieldMap.get("Section6:Question3:Yes"),"Yes");   //DM 
                        	fields.setField((String)fieldMap.get("Section6: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("HEALTH BENEFITS RENEWAL, 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 VI - 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 VII - PREVIOUS CALENDAR YEAR GROSS ANNUAL INCOME OF
     * VETERAN, SPOUSE AND DEPENDENT CHILDREN of the fillable PDF document
     * 
     * @throws DocumentException
     * @throws IOException
     */

     private void fillSection7_8_9() throws DocumentException, IOException 
     { 
    	// log.info("1010EZR fillSection7,8,9 ");
    	 DependentFinancials df = null;  
    	 Dependent dependent = null;
    	 if (FinDisclosureFlag ){
    		if ( ftmt !=null ){
    			fields.setField((String)fieldMap.get("Section7:Question1:Veteran"),ftmt.getTotalEmploymentIncome()!=null && ftmt.getTotalEmploymentIncome().getAmount()!=null ? ftmt.getTotalEmploymentIncome().getAmount().toString():"");
    			fields.setField((String)fieldMap.get("Section7:Question2:Veteran"),ftmt.getFarmRanchBusinessIncome()!=null && ftmt.getFarmRanchBusinessIncome().getAmount()!=null ? ftmt.getFarmRanchBusinessIncome().getAmount().toString():"");
    			fields.setField((String)fieldMap.get("Section7:Question3:Veteran"),ftmt.getOtherIncome()!=null && ftmt.getOtherIncome().getAmount()!=null ? ftmt.getOtherIncome().getAmount().toString():"");
    			fields.setField((String)fieldMap.get("Section8:Question1"),ftmt.getNonReimbursableExpense()!=null && ftmt.getNonReimbursableExpense().getAmount()!=null? ftmt.getNonReimbursableExpense().getAmount().toString():"");
     			fields.setField((String)fieldMap.get("Section8:Question2"),ftmt.getFuneralBurialExpense()!=null && ftmt.getFuneralBurialExpense().getAmount()!=null ? ftmt.getFuneralBurialExpense().getAmount().toString(): "");
     			fields.setField((String)fieldMap.get("Section8:Question3"),ftmt.getVeteranEducationExpense()!=null && ftmt.getVeteranEducationExpense().getAmount()!=null ? ftmt.getVeteranEducationExpense().getAmount().toString():"");
     			fields.setField((String)fieldMap.get("Section9:Question1:Veteran"),ftmt.getCashAndBankAccountBalances()!=null && ftmt.getCashAndBankAccountBalances().getAmount()!=null ? ftmt.getCashAndBankAccountBalances().getAmount().toString():"");
     			fields.setField((String)fieldMap.get("Section9:Question2:Veteran"),ftmt.getRealEstate()!=null && ftmt.getRealEstate().getAmount()!=null? ftmt.getRealEstate().getAmount().toString():"");
     			fields.setField((String)fieldMap.get("Section9:Question3:Veteran"),ftmt.getOtherPropertyOrAssets()!=null && ftmt.getOtherPropertyOrAssets().getAmount()!=null? ftmt.getOtherPropertyOrAssets().getAmount().toString():"");
    		}
            if(sf != null) {  // :new BigDecimal(0d).toString()
            	fields.setField((String)fieldMap.get("Section7:Question1:Spouse"),sf.getTotalEmploymentIncome()!=null && sf.getTotalEmploymentIncome().getAmount()!=null ? sf.getTotalEmploymentIncome().getAmount().toString():"");
            	fields.setField((String)fieldMap.get("Section7:Question2:Spouse"),sf.getFarmRanchBusinessIncome()!=null && sf.getFarmRanchBusinessIncome().getAmount()!= null ? sf.getFarmRanchBusinessIncome().getAmount().toString():"");
            	fields.setField((String)fieldMap.get("Section7:Question3:Spouse"),sf.getOtherIncome()!=null && sf.getOtherIncome().getAmount()!=null ? sf.getOtherIncome().getAmount().toString():""); 
    			fields.setField((String)fieldMap.get("Section9:Question1:Spouse"),sf.getCashAndBankAccountBalances()!=null && sf.getCashAndBankAccountBalances().getAmount()!=null ? sf.getCashAndBankAccountBalances().getAmount().toString(): "");
     			fields.setField((String)fieldMap.get("Section9:Question2:Spouse"),sf.getRealEstate()!=null && sf.getRealEstate().getAmount()!=null ? sf.getRealEstate().getAmount().toString(): "");
     			fields.setField((String)fieldMap.get("Section9:Question3:Spouse"),sf.getOtherPropertyOrAssets()!=null && sf.getOtherPropertyOrAssets().getAmount()!=null? sf.getOtherPropertyOrAssets().getAmount().toString(): "");
            }

            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 VI
        	   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("Section7:Question1:Child"),df.getTotalEmploymentIncome()!=null && df.getTotalEmploymentIncome().getAmount()!=null? df.getTotalEmploymentIncome().getAmount().toString():"");
		                	fields.setField((String)fieldMap.get("Section7:Question2:Child"),df.getFarmRanchBusinessIncome()!=null && df.getFarmRanchBusinessIncome().getAmount()!=null ? df.getFarmRanchBusinessIncome().getAmount().toString():"");
		                	fields.setField((String)fieldMap.get("Section7: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("HEALTH BENEFITS RENEWAL, 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 VII - 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 IX
		       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("Section9:Question1:Child"),df.getCashAndBankAccountBalances()!=null && df.getCashAndBankAccountBalances().getAmount()!=null ? df.getCashAndBankAccountBalances().getAmount().toString(): "");
		                	fields.setField((String)fieldMap.get("Section9:Question2:Child"),df.getRealEstate()!=null && df.getRealEstate().getAmount()!=null ? df.getRealEstate().getAmount().toString():"");
		                	fields.setField((String)fieldMap.get("Section9: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("HEALTH BENEFITS RENEWAL, 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 IX - 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);
	    			 	}
                    }
               }
           }
       }
  }

    private void fillSection11() throws DocumentException, IOException {
    	// log.info("1010EZR fillSection11 ");
    	fields.setField((String) fieldMap.get("Section11:Date"),
                new SimpleDateFormat("MM/dd/yyyy").format(new Date()));
    }
     
    private String addCurrencySymbol(String currency) { 
        if (currency != null && StringUtils.isNotEmpty(currency)) 
        { return "$"+" "+currency; } 
        return "$"; 
    }
    
    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 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 String getInsuranceCompanyAddrPhone(InsurancePolicy insurance) {
        StringBuffer insuranceInfo = new StringBuffer();
        Address insAddr = insurance.getAddress();
        
        if (insurance.getCompanyName() != null && StringUtils.isNotEmpty(insurance.getCompanyName()))
            insuranceInfo.append(insurance.getCompanyName());
        
        String addrInfo = getAddressInTwoLines(insAddr);
        if (addrInfo != null && StringUtils.isNotEmpty(addrInfo)) {
           if (insuranceInfo.length() > 0) {
                insuranceInfo.append("\n");
            }
            insuranceInfo.append(addrInfo);
        }
        
        if (insurance.getBusinessPhone() != null && StringUtils.isNotEmpty(insurance.getBusinessPhone().getFormattedPhone())) {
            /*if (insuranceInfo.length() > 0) {
                insuranceInfo.append("     Phone: ");
            }*/
        	if (insuranceInfo.length() > 0) {
                insuranceInfo.append("    Phone: ");
            }
            insuranceInfo.append(insurance.getBusinessPhone().getFormattedPhone());
        }
        return insuranceInfo.toString();
    }
	
    private String getSpouseAddressPhone(Spouse lspouse) {
        StringBuffer spouseAddrPhone = new StringBuffer();
        Address spouseAddr = lspouse.getAddress();
        
        String addrInfo = getAddressInTwoLines(spouseAddr);
        if (addrInfo != null && StringUtils.isNotEmpty(addrInfo)) {
        	spouseAddrPhone.append(addrInfo);
        }
        
        if (lspouse.getHomePhone() != null && StringUtils.isNotEmpty(lspouse.getHomePhone() .getFormattedPhone())) {
        	if (spouseAddrPhone.length() > 0) {
        		// spouseAddrPhone.append("    Phone: ");
        		spouseAddrPhone.append("\n");
            }
        	spouseAddrPhone.append(lspouse.getHomePhone().getFormattedPhone());
        }
        return spouseAddrPhone.toString();
    }
    
    private String getEmployerCompanyAddrPhone(Employment em) {
        StringBuffer employerInfo = new StringBuffer();
        Address insAddr = em.getEmployerAddress();
        
        if (em.getEmployerName()!= null && StringUtils.isNotEmpty(em.getEmployerName()))
        	employerInfo.append(em.getEmployerName());
        
        String addrInfo = getAddressInTwoLines(insAddr);
        if (addrInfo != null && StringUtils.isNotEmpty(addrInfo)) {
           if (employerInfo.length() > 0) {
        	   employerInfo.append("\n");
            }
           employerInfo.append(addrInfo);
        }
        
        if (em.getEmployerPhone()!= null && StringUtils.isNotEmpty(em.getEmployerPhone())) {
        	if (employerInfo.length() > 0) {
        		employerInfo.append("    Phone: ");
            }
        	employerInfo.append(em.getEmployerPhone());
        }
        return employerInfo.toString();
    }
    
	private String getAddressInTwoLines(Address inAddr){
		
		if ( inAddr == null ) return null;
		StringBuffer retAddr = new StringBuffer();
		String addr1 = inAddr.getLine1()!=null ? inAddr.getLine1():"";
		String addr2 = inAddr.getLine2()!=null ? inAddr.getLine2():"";
		String addr3 = inAddr.getLine2()!=null ? inAddr.getLine3():"";
	    if ( StringUtils.isNotEmpty(addr1))
	    {
	    	retAddr.append(addr1);
	    }
	    if (StringUtils.isNotEmpty(addr2))
	    {
	    	retAddr.append(" "+addr2);
	    }
	    if (StringUtils.isNotEmpty(addr3))
	    {
	    	retAddr.append(" "+addr3);
	    }
	    if (StringUtils.isNotEmpty(inAddr.getCity()) )
	    {
	    	if (retAddr.length()>0)
	    		retAddr.append("\n");
	    	retAddr.append(inAddr.getCity());
	    	
	    	if (StringUtils.isNotEmpty(inAddr.getState()) )
	    		retAddr.append(", "+inAddr.getState());
	    	
	    	if (StringUtils.isNotEmpty(inAddr.getZipCode()) )
	    		retAddr.append(" "+inAddr.getZipCode());
	    }
	    else {
	    	if (StringUtils.isNotEmpty(inAddr.getState()) ){
	    		if (retAddr.length()>0)
	    			retAddr.append("\n");
	    		retAddr.append(inAddr.getState());

	    		if (StringUtils.isNotEmpty(inAddr.getZipCode()) )
		    		retAddr.append(" "+inAddr.getZipCode());
	    	}
	    	else if (StringUtils.isNotEmpty(inAddr.getZipCode())){
	    		if (retAddr.length()>0)
	    			retAddr.append("\n");
	    		retAddr.append(inAddr.getZipCode());
	    	}
		}
	    return retAddr.toString(); 
	}

    private String getLastFirstMiddleByComma(Name name){
    	
    	StringBuffer buf = new StringBuffer();
	    if (name == null )
	    	return "";

	    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();
	}      

    private InputStream readTemplate(String fillableFormFileName)throws Exception
    { 
    	// log.info("1010EZR inside readTemplate "+fillableFormFileName);
    	FileInputStream inFillablePDFFile = new FileInputStream(fillableFormFileName);
    	InputStream inFillablePDF = (InputStream)inFillablePDFFile;
    	return inFillablePDF;
    }
    
    public void display1010EZR(HttpServletResponse resp)throws Exception{
    	
    	String finalFname = this.getOutputFilePath() + this.getFinalFileName();
    	InputStream input= null;
    	DataOutputStream dataostream = null;
    	try {
	    	input= new FileInputStream(finalFname);
		    resp.setContentType("application/pdf");
		    resp.setHeader("Content-Disposition", "inline");
		    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) {
    			dataostream.close();
    		}
		    
		     File file_temp = new File(finalFname);
		     if ( file_temp!=null && file_temp.exists()) {
		    	 file_temp.delete();	
		     }
    	}
	}
}
