/**
   * Set the DbVitals and DbCase values from the FirstCallInformation form. Creation date:
   * (10/25/2002 11:00:39 AM)
   *
   * @param deceased com.aldorsolutions.webfdms.beans.DbVitalsDeceased
   * @param form fdms.ui.struts.form.FirstCallInformationForm
   * @param errors org.apache.struts.action.ActionErrors
   */
  public void setVitalsDeceased(
      DbVitalsDeceased deceased,
      DbVitalsInformant informant,
      CemAnStatus form,
      ActionErrors errors) {
    try {

      deceased.setDecmrmrs(form.getPrefix());
      deceased.setDecFName(form.getFirstName());
      deceased.setDecMName(form.getMiddleName());
      deceased.setDecLName(form.getLastName());
      deceased.setSuffix(form.getSuffix());
      deceased.setDecFullName(form.getMemorialName());
      deceased.setDecMaiden(form.getMaidenName());
      deceased.setDateOfBirth(FormatDate.convertToDateMMDDYYYY(form.getBirthDate()));
      deceased.setDateOfDeath(FormatDate.convertToDateMMDDYYYY(form.getDeathDate()));
      deceased.setDateOfBurial(FormatDate.convertToDateMMDDYYYY(form.getServiceDate()));

      // if the deceased's residence is the same as the informant's then update the deceased's
      // address
      if (form.getDeceasedSame()) {
        deceased.setDeceasedSame("Y");
        deceased.setDecResStreet(
            form.getInformantStreet()
                + " "
                + form.getInformantStreet2()
                + " "
                + form.getInformantStreet3());
        deceased.setDecResCityTWP(form.getInformantCity());
        deceased.setDecResState(form.getInformantState());
        deceased.setDecResZip(form.getInformantZip());
        deceased.setDecResPhone(form.getInformantPhone());
      } else {
        deceased.setDeceasedSame("N");
      }

    } catch (Exception e) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.setData"));
    }

    return;
  }
  private String getFromDate(ReportForm reportForm, ActionMessages errors) {
    String fromDate = null;
    if (reportForm.getListType().compareToIgnoreCase("R") == 0
        || reportForm.getListType().compareToIgnoreCase("S") == 0) {

      // Get From Date
      try {
        fromDate = FormatDate.convertToDateYYYYMMDD(reportForm.getFromDate());
      } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.date.fromdate"));

        formErrors.add("fromDate");
      }

    } else if (reportForm.getListType().compareToIgnoreCase("weekly") == 0) {
      try {

        fromDate = FormatDate.convertToDateMMDDYYYY(FormatDate.getCurrentDateFormatedMMDDYYYY());

        fromDate = FormatDate.addToDateMMDDYYYY(fromDate, -8, 0);

        fromDate = FormatDate.convertUnformattedMDYtoYMD(fromDate);

      } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.date.fromdate"));
        formErrors.add("toDate");
      }

    } else if (reportForm.getListType().compareToIgnoreCase("monthly") == 0) {
      try {

        fromDate = FormatDate.convertToDateMMDDYYYY(FormatDate.getCurrentDateFormatedMMDDYYYY());

        fromDate = FormatDate.addToDateMMDDYYYY(fromDate, 0, -1);

        fromDate = FormatDate.convertUnformattedMDYtoYMD(fromDate);

      } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.date.fromdate"));
        formErrors.add("toDate");
      }
    }
    return fromDate;
  }
  private void validateForm(
      DatabaseTransaction t,
      DbUserSession sessionUser,
      fdms.ui.struts.form.CemAnStatus form,
      ActionErrors errors) {

    String checkDate = null;

    // Validate Arrange Date
    if (form.getArrangeDate() != null && form.getArrangeDate().trim().length() > 0) {
      try {
        checkDate = FormatDate.convertToDateMMDDYYYY(form.getArrangeDate());
      } catch (Exception e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.arrangedate"));
        formErrors.add("arrangeDate");
      }
    }

    // Chapel is required.
    if (form.getChapel() == null || form.getChapel().trim().length() == 0) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.chapel"));
      formErrors.add("chapel");
    }

    // Director is required.
    if (form.getDirector() == null || form.getDirector().trim().length() == 0) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.director"));
      formErrors.add("director");
    }

    // Validate PreNeed Date if entered.
    if (form.getPreneedDate() != null && form.getPreneedDate().trim().length() > 0) {
      try {
        checkDate = FormatDate.convertToDateMMDDYYYY(form.getPreneedDate());
      } catch (Exception e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.origpndate"));
        formErrors.add("preneedDate");
      }
    }

    // If the user changed the contract number, check for duplicate Contract Numbers.
    if (form.getContractNumber() != null
        && form.getContractNumber().trim().length() > 0
        && (!form.getContractNumber().equals(form.getNextContractNumber()))) {

      DbCase checkCase = new DbCase();
      checkCase.setNew();
      checkCase.setLocale(sessionUser.getRegion());
      if (form.getVitalsId() == null
          || form.getVitalsId().trim().length() == 0
          || form.getVitalsId() == "0") {
        checkCase.setId(0);
      } else {
        checkCase.setId(FormatNumber.parseInteger(form.getVitalsId()));
      }
      checkCase.setContractCode(form.getContractNumber());
      if (FdmsDb.getInstance().checkCaseExists(t, checkCase, DbCasePeer.CONTRACTCODE)) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.duplicate.contractNumber"));
        formErrors.add("contractNumber");
      }
    }

    // Deceased Memorial Name is required.
    if (form.getMemorialName() == null || form.getMemorialName().trim().length() == 0) {
      if (form.getMiddleName() != null && form.getMiddleName().trim().length() > 0) {
        form.setMemorialName(
            form.getFirstName() + " " + form.getMiddleName() + " " + form.getLastName());
      } else {
        form.setMemorialName(form.getFirstName() + " " + form.getLastName());
      }
      if (form.getMemorialName() == null || form.getMemorialName().trim().length() == 0) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.memorialName.required"));
        formErrors.add("memorialName");
      }
    }

    // Deceased First Name is required.
    if (form.getFirstName() == null || form.getFirstName().trim().length() == 0) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.registration.nullFirstName"));
      formErrors.add("firstName");
    }

    // Deceased Last Name is required.
    if (form.getLastName() == null || form.getLastName().trim().length() == 0) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.registration.nullLastName"));
      formErrors.add("lastName");
    }

    // Validate Date of Birth
    if (form.getBirthDate() != null && form.getBirthDate().trim().length() > 0) {
      try {
        checkDate = FormatDate.convertToDateMMDDYYYY(form.getBirthDate());
      } catch (Exception e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.birthdate"));
        formErrors.add("birthDate");
      }
    }

    // Validate Date of Death
    if (form.getDeathDate() != null && form.getDeathDate().trim().length() > 0) {
      try {
        checkDate = FormatDate.convertToDateMMDDYYYY(form.getDeathDate());
      } catch (Exception e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.deathdate"));
        formErrors.add("deathDate");
      }
    }

    // Validate Service Date
    if (form.getServiceDate() != null && form.getServiceDate().trim().length() > 0) {
      try {
        checkDate = FormatDate.convertToDateMMDDYYYY(form.getServiceDate());
      } catch (Exception e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.servicedate"));
        formErrors.add("serviceDate");
      }
    }

    // Validate Disposition Date
    if (form.getDispDate() != null && form.getDispDate().trim().length() > 0) {
      try {
        checkDate = FormatDate.convertToDateMMDDYYYY(form.getDispDate());
      } catch (Exception e) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.dispdate"));
        formErrors.add("dispDate");
      }
    }

    return;
  }
  /**
   * Set the DbVitals and DbCase values from the FirstCallInformation form. Creation date:
   * (10/25/2002 11:00:39 AM)
   *
   * @param t com.aldorsolutions.webfdms.database.DatabaseTransaction
   * @param firstCall com.aldorsolutions.webfdms.beans.DbVitalsFirstCall
   * @param informant com.aldorsolutions.webfdms.beans.DbVitalsInformant
   * @param caseinfo com.aldorsolutions.webfdms.beans.DbCase
   * @param nextkin com.aldorsolutions.webfdms.beans.DbVitalsNextKin
   * @param nextkin com.aldorsolutions.webfdms.beans.DbVitalsExecutor
   * @param form fdms.ui.struts.form.FirstCallInformationForm
   * @param errors org.apache.struts.action.ActionErrors
   */
  public void setVitalsRest(
      DatabaseTransaction t,
      DbUserSession sessionUser,
      DbVitalsDeceased deceased,
      DbVitalsFirstCall firstCall,
      DbVitalsInformant informant,
      DbCase caseinfo,
      DbVitalsNextKin nextkin,
      DbVitalsExecutor executor,
      DbCemAtneed cematneed,
      CemAnStatus form,
      ActionErrors errors) {

    boolean continueDuplicate = true;

    try {
      if (form.isExecutorSame()) {
        logger.debug("Executor is the same");

        executor.setIsExecutorSame("Y");
        executor.setExecutorPersonId(form.getExecutorPersonId());
        executor.setExecutorFirstname(form.getInformantFirst());
        executor.setExecutorLastname(form.getInformantLast());
        executor.setExecutorStreet(form.getInformantStreet());
        executor.setExecutorStreet2(form.getInformantStreet2());
        executor.setExecutorStreet3(form.getInformantStreet3());
        executor.setExecutorCity(form.getInformantCity());
        executor.setExecutorState(form.getInformantState());
        executor.setExecutorZip(form.getInformantZip());
        executor.setExecutorPhone(FormatString.formatPhone(form.getInformantPhone()));
        executor.setExecutorRelation(form.getInformantRelation());
        executor.setExecutorEmail(form.getInformantEmail());

        // sets the vitals id for DbExecutor so I can insert values into database
        Persistent p = (Persistent) executor;
        p.setId(new Integer(form.getVitalsId()).intValue());

      } else {
        logger.debug("Executor is not the same");

        executor.setIsExecutorSame("N");
        executor.setExecutorPersonId(form.getExecutorPersonId());
        executor.setExecutorFirstname(form.getExecutorFirstName());
        executor.setExecutorLastname(form.getExecutorLastName());
        executor.setExecutorStreet(form.getExecutorStreet());
        executor.setExecutorStreet2(form.getExecutorStreet2());
        executor.setExecutorStreet3(form.getExecutorStreet3());
        executor.setExecutorCity(form.getExecutorCity());
        executor.setExecutorState(form.getExecutorState());
        executor.setExecutorZip(form.getExecutorZip());
        executor.setExecutorPhone(FormatString.formatPhone(form.getExecutorPhone()));
        executor.setExecutorRelation(form.getExecutorRelation());
        executor.setExecutorEmail(form.getExecutorEmail());

        // sets the vitals id for DbExecutor so I can insert values into database
        Persistent p = (Persistent) executor;
        p.setId(new Integer(form.getVitalsId()).intValue());
      }

      firstCall.setArrangeDate(FormatDate.convertToDateMMDDYYYY(form.getArrangeDate()));
      firstCall.setDispositionDate(FormatDate.convertToDateMMDDYYYY(form.getDispDate()));
      firstCall.setOriginalPnDate(FormatDate.convertToDateMMDDYYYY(form.getPreneedDate()));
      firstCall.setArrangeTime(form.getTime());
      firstCall.setPlaceDeathAddr(form.getLocationDeceased());
      firstCall.setSource(form.getSource());
      firstCall.setEmbalmingReason(form.getEmbalming());
      firstCall.setPlaceDeath(form.getPlaceDeath());
      firstCall.setPlaceDeathCity(form.getPlaceDeathCity());
      firstCall.setPlaceDeathState(form.getPlaceDeathState());
      firstCall.setPlaceDeathZip(form.getPlaceDeathZip());
      firstCall.setAgeYears(FormatNumber.parseInteger(form.getAge()));

      int chapelId = 0;
      if (form.getChapel() != null) {
        try {
          chapelId = Integer.parseInt(form.getChapel());
        } catch (NumberFormatException e) {
          // unable to parse int from String
        }
      }

      logger.debug("ChapelId : " + chapelId);

      DbLocation dbLocation = FdmsDb.getInstance().getLocation(t, chapelId);
      if (dbLocation != null) {
        firstCall.setFacilityName(dbLocation.getName());
        firstCall.setFacilityStreet(dbLocation.getAddr1());
        firstCall.setFacilityCityStZip(
            dbLocation.getCity() + ", " + dbLocation.getState() + ", " + dbLocation.getZip());
        firstCall.setFacilityLicenseNo(dbLocation.getLicenseNumber());
        firstCall.setFacilityPhone(FormatString.formatPhone(dbLocation.getPhone()));
      } else {
        firstCall.setFacilityName(form.getFacilityName());
        firstCall.setFacilityStreet(form.getFacilityStreet());
        firstCall.setFacilityCityStZip(
            form.getFacilityCity() + ", " + form.getFacilityState() + ", " + form.getFacilityZip());
        firstCall.setFacilityPhone(FormatString.formatPhone(form.getFacilityPhone()));
        firstCall.setFacilityLicenseNo(form.getFacilityLicense());
      }

      firstCall.setShippingInfo(form.getShippingInfo());

      DbArrangers dbArranger =
          FdmsDb.getInstance().getArranger(t, Integer.parseInt(form.getDirector()));
      firstCall.setArrangerName(dbArranger.getName());
      firstCall.setArrangerID(dbArranger.getId());

      informant.setSalutation(form.getInformantSalutation());
      informant.setFname(form.getInformantFirst());
      informant.setMname(form.getInformantMiddle());
      informant.setLname(form.getInformantLast());
      informant.setStreet(form.getInformantStreet());
      informant.setRoad2(form.getInformantStreet2());
      informant.setRoad3(form.getInformantStreet3());
      informant.setCity(form.getInformantCity());
      informant.setState(form.getInformantState());
      informant.setZip(form.getInformantZip());
      informant.setPhone(FormatString.formatPhone(form.getInformantPhone()));
      informant.setRelated(form.getInformantRelation());
      informant.setInformantEmail(form.getInformantEmail());

      if (form.getNextKinSame()) {
        nextkin.setSameAsInformant("Y");
        nextkin.setSalutation(form.getInformantSalutation());
        nextkin.setFirstname(form.getInformantFirst());
        nextkin.setLastname(form.getInformantLast());
        nextkin.setStreet(form.getInformantStreet());
        nextkin.setRoad2(form.getInformantStreet2());
        nextkin.setRoad3(form.getInformantStreet3());
        nextkin.setCity(form.getInformantCity());
        nextkin.setState(form.getInformantState());
        nextkin.setZip(form.getInformantZip());
        nextkin.setPhone(FormatString.formatPhone(form.getInformantPhone()));
        nextkin.setRelation(form.getInformantRelation());
      } else {
        nextkin.setSameAsInformant("N");
        nextkin.setSalutation(form.getNextKinSalutation());
        nextkin.setFirstname(form.getNextKinFirst());
        nextkin.setLastname(form.getNextKinLast());
        nextkin.setStreet(form.getNextKinStreet());
        nextkin.setRoad2(form.getNextKinStreet2());
        nextkin.setRoad3(form.getNextKinStreet3());
        nextkin.setCity(form.getNextKinCity());
        nextkin.setState(form.getNextKinState());
        nextkin.setZip(form.getNextKinZip());
        nextkin.setPhone(FormatString.formatPhone(form.getNextKinPhone()));
        nextkin.setRelation(form.getNextKinRelation());
      }

      cematneed.setCem_plottype(form.getCem_plottype());
      cematneed.setCem_section(form.getCem_section());
      cematneed.setCem_block(form.getCem_block());
      cematneed.setCem_lot_tier(form.getCem_lot_tier());
      cematneed.setCem_grave_row(form.getCem_grave_row());
      cematneed.setCem_Amount(form.getCem_Amount());
      cematneed.setCem_ANBuyerAptNo(form.getCem_ANBuyerAptNo());
      cematneed.setCem_ANBuyerCity(form.getCem_ANBuyerCity());
      cematneed.setCem_ANBuyerMidName(form.getCem_ANBuyerMidName());
      cematneed.setCem_ANBuyerTitle(form.getCem_ANBuyerTitle());
      cematneed.setCem_ANBuyerPhone(form.getCem_ANBuyerPhone());
      cematneed.setCem_ANBuyerState(form.getCem_ANBuyerState());
      cematneed.setCem_ANBuyerStreet(form.getCem_ANBuyerStreet());
      cematneed.setCem_ANBuyerFirstName(form.getCem_ANBuyerFirstName());
      cematneed.setCem_ANBuyerLastName(form.getCem_ANBuyerLastName());
      cematneed.setCem_ANBuyerZip(form.getCem_ANBuyerZip());
      cematneed.setCem_MapID(form.getCem_MapID());
      cematneed.setCem_Record(form.getCem_Record());
      cematneed.setCem_ContractDate(form.getCem_ContractDate());
      cematneed.setCem_MiscDesc(form.getCem_MiscDesc());
      cematneed.setCem_MiscAmount(form.getCem_MiscAmount());

      deceased.setDecFName(form.getBeneficiaryFirst());
      deceased.setDecMName(form.getBeneficiaryMiddle());
      deceased.setDecLName(form.getBeneficiaryLast());
      deceased.setDecResStreet(form.getBeneficiaryStreet());
      deceased.setDecResMailCity(form.getBeneficiaryCity());
      deceased.setDecResState(form.getBeneficiaryState());
      deceased.setDecResZip(form.getBeneficiaryZipCode());
      deceased.setDecResPhone(form.getBeneficiaryPhone());
      deceased.setSSNo(FormatString.removeDashes(form.getBeneficiarySocialSecurityNumber()));
      deceased.setDecFullName(form.getBeneficiaryFirst() + " " + form.getBeneficiaryLast());
      deceased.setDecmrmrs(form.getBeneficiaryTitle());
      deceased.setDecAptNo(form.getBeneficiaryAptno());

      caseinfo.setChapelLocation(dbLocation.getName());
      caseinfo.setChapelNumber(dbLocation.getId());
      caseinfo.setLocale(dbLocation.getLocaleNumber());
      caseinfo.setDeathDate(FormatDate.convertToDateYYYYMMDD(form.getDeathDate()));
      caseinfo.setServiceDate(FormatDate.convertToDateYYYYMMDD(form.getServiceDate()));
      caseinfo.setSaleDate(FormatDate.convertToDateYYYYMMDD(form.getServiceDate()));

      DatabaseTransaction x = null;

      // Regardless of whether the user changed the contract number or not, we need to make sure
      // that the
      // contract number is unique before we proceed.
      if (form.getContractNumber() != null && form.getContractNumber().trim().length() > 0) {
        try {
          x = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser);
          while (continueDuplicate) {
            // Check for duplicate Contract Numbers.
            DbCase checkCase = new DbCase();
            checkCase.setNew();
            checkCase.setLocale(sessionUser.getRegion());
            checkCase.setId(deceased.getId());
            checkCase.setContractCode(form.getContractNumber());
            if (FdmsDb.getInstance().checkCaseExists(x, checkCase, DbCasePeer.CONTRACTCODE)) {
              // AppLog.trace("Contract " +form.getContractNumber() + " is a duplicate.");
              // If the user changed the contract number, give them an error
              if (!form.getNextContractNumber().equals(form.getContractNumber())) {
                errors.add(
                    ActionErrors.GLOBAL_ERROR, new ActionError("error.duplicate.contractNumber"));
                formErrors.add("contractNumber");
                continueDuplicate = false;
              } else {
                // contract number is same so need to increment and retest for duplicate
                form.setContractNumber(
                    String.valueOf(
                        SessionHelpers.nextContractNumber(
                            sessionUser.getDbLookup(), sessionUser.getRegion())));
                form.setNextContractNumber(form.getContractNumber());
                // AppLog.trace("Incremented contract# because duplicated. New next
                // number="+form.getContractNumber());
              }
            } else {
              continueDuplicate = false;
            }
          }
        } catch (Exception e) {
          logger.error("Error : ", e);
        } finally {
          if (x != null) {
            x.closeConnection();
            x = null;
          }
        }
      }

      caseinfo.setContractCode(form.getContractNumber());
      caseinfo.setCaseCode(form.getCaseNumber());

      // Add Informant as BillTo if no BillTos already exist.
      DbBillto[] dbBillTo = FdmsDb.getInstance().getBilltoForID(t, deceased.getId());
      if (dbBillTo == null || dbBillTo.length == 0) {
        if ((form.getInformantFirst() != null && form.getInformantFirst().trim().length() > 0)
            || (form.getInformantLast() != null && form.getInformantLast().trim().length() > 0)) {
          DbBillto newBillTo = new DbBillto();
          newBillTo.setNew();
          // newBillTo.setCashSale();
          newBillTo.setCity(form.getInformantCity());
          // newBillTo.setContractSigner();
          // newBillTo.setCounty();
          newBillTo.setEmailAddress(form.getInformantEmail());
          // newBillTo.setFileVersion();
          newBillTo.setFirstName(form.getInformantFirst());
          newBillTo.setHomePhone(FormatString.formatPhone(form.getInformantPhone()));
          newBillTo.setHonorific(form.getInformantSalutation());
          // newBillTo.setLanguage(form.getInformant);
          newBillTo.setLastName(form.getInformantLast());
          // newBillTo.setRefused(form.getInformant);
          newBillTo.setRelation(form.getInformantRelation());
          newBillTo.setSendInvoice("Y");
          newBillTo.setSeqNo(Short.parseShort("0"));
          // newBillTo.setSocialSecurityNo(form.getInformant);
          newBillTo.setState(form.getInformantState());
          newBillTo.setStreet1(form.getInformantStreet());
          newBillTo.setStreet2(form.getInformantStreet2());
          newBillTo.setStreet3(form.getInformantStreet3());
          // newBillTo.setStreet4(form.getInformant);
          newBillTo.setVitalsID(deceased.getId());
          // newBillTo.setWorkPhone(form.getInformant);
          newBillTo.setZip(form.getInformantZip());
          if (form.getInformantContractSigner()) {
            newBillTo.setContractSigner("Y");
          }
          t.addPersistent(newBillTo);
        }
      }

    } catch (Exception e) {
      logger.error("Exception in setVitalsRest() ", e);
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.ui.setData"));
    }

    return;
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws javax.servlet.ServletException, java.io.IOException {

    ActionErrors errors = new ActionErrors();
    HttpSession session = request.getSession();
    DbUserSession sessionUser = SessionHelpers.getUserSession(request);
    DatabaseTransaction t = null;
    DbSpeedData[] dbSpeedData = null;
    DbLocation[] dbLocation = null;
    LocaleDTO userlocale = null;

    MiscCashReceiptsForm miscCashReceipts = new MiscCashReceiptsForm();
    java.util.ArrayList locationList = new java.util.ArrayList();
    java.util.ArrayList glDescriptionList = new java.util.ArrayList();
    java.util.ArrayList cashAcctList = new java.util.ArrayList();
    java.util.ArrayList payMethodList = new java.util.ArrayList();
    java.util.ArrayList pleaseSelect = new java.util.ArrayList();

    if (sessionUser == null) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.login.invalid"));
    }

    // Database Access Logic
    try {
      t = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser);

      // Set the list of receipt types in session.
      SessionHelpers.setReceiptTypesInSession(request);

      // Populate the locationList collection
      dbLocation = FdmsDb.getInstance().getLocationsForRegion(t, sessionUser.getRegion());
      // AppLog.trace("DbLocation list length = " +dbLocation.length);
      for (int i = 0; i < dbLocation.length; i++) {
        String listValue = String.valueOf(dbLocation[i].getId());
        String listLabel = dbLocation[i].getName();
        locationList.add(new OptionsList(listValue, listLabel));
      }

      // Populate the glDescriptionList collection
      dbSpeedData =
          FdmsDb.getInstance()
              .getSpeedData(sessionUser.getDbLookup(), sessionUser.getRegion(), "REVTYPE");
      // AppLog.trace("DbSpeedData for REVTYPE list length = " +dbSpeedData.length);
      for (int i = 0; i < dbSpeedData.length; i++) {
        String listValue = CsvTable.getField(dbSpeedData[i].getData(), 2);
        String listLabel = CsvTable.getField(dbSpeedData[i].getData(), 1);
        glDescriptionList.add(new OptionsList(listValue, listLabel));
      }

      // Populate the cashAcctList collection
      dbSpeedData =
          FdmsDb.getInstance()
              .getSpeedData(sessionUser.getDbLookup(), sessionUser.getRegion(), "CASHTYPE");
      // AppLog.trace("DbSpeedData for CASHTYPE list length = " +dbSpeedData.length);
      for (int i = 0; i < dbSpeedData.length; i++) {
        String listValue = CsvTable.getField(dbSpeedData[i].getData(), 2);
        String listLabel = CsvTable.getField(dbSpeedData[i].getData(), 1);
        cashAcctList.add(new OptionsList(listValue, listLabel));
      }

      // Populate the payMethodList", payMethodList)
      userlocale =
          FdmsDb.getInstance().getLocale(sessionUser.getDbLookup(), sessionUser.getRegion());
      dbSpeedData =
          FdmsDb.getInstance()
              .getSpeedData(sessionUser.getDbLookup(), sessionUser.getRegion(), "PAYMETHOD");
      // AppLog.trace("DbSpeedData for PAYMETHOD list length = " +dbSpeedData.length);
      for (int i = 0; i < dbSpeedData.length; i++) {
        if (dbSpeedData[i].getData() != null && dbSpeedData[i].getData().length() > 1) {
          String listValue = dbSpeedData[i].getData().substring(0, 2);
          String listLabel = dbSpeedData[i].getData();
          payMethodList.add(new OptionsList(listValue, listLabel));
        }
      }

      // Form Defaults
      miscCashReceipts.setSubmitButton("");
      miscCashReceipts.setAmountOfTran("0");
      miscCashReceipts.setDateOfTran(FormatDate.getCurrentDateFormatedMMDDYYYY());
      miscCashReceipts.setFormId("None");
      miscCashReceipts.setReceiptNumber(String.valueOf(userlocale.getNextReceiptNo()));

      pleaseSelect.add(new OptionsList("", "--Select--"));
      // AppLog.trace("Finished setting miscCashReceipts form bean");

    } catch (PersistenceException pe) {
      logger.error("Persistence Exception in ShowMiscCashReceipts.doPerform. " + pe);
      errors.add(
          ActionErrors.GLOBAL_ERROR, new ActionError("error.PersistenceException", pe.getCause()));
    } catch (Exception pe) {
      logger.error("Exception in ShowMiscCashReceipts.doPerform. ", pe);
      errors.add(
          ActionErrors.GLOBAL_ERROR, new ActionError("error.GeneralException", pe.getMessage()));
    } finally {
      if (t != null) t.closeConnection();
    }

    // Set Form Bean Into Scope
    session.setAttribute("miscCashReceipts", miscCashReceipts);
    session.setAttribute("locationList", locationList);
    session.setAttribute("glDescriptionList", glDescriptionList);
    session.setAttribute("cashAcctList", cashAcctList);
    session.setAttribute("payMethodList", payMethodList);
    session.setAttribute("pleaseSelect", pleaseSelect);
    // AppLog.trace("Setting miscCashReceipts form bean and collection arrays into session scope.");

    ActionForward actionForward = mapping.findForward("miscCashReceipts");

    if (!errors.isEmpty()) {
      // AppLog.info("ShowMiscCahsReceipts invoking forward mapping getInput().");
      saveErrors(request, errors);
      actionForward = new ActionForward(mapping.getInput());
    }

    return actionForward;
  }
  /**
   * Called from ProcessMiscCashReceipts, this Method validates the data from the MiscCashReceipts
   * form. If a validation error occurs, the error is stored in the errors collection. Creation
   * date: (8/13/2002 3:41:28 PM)
   */
  public void validateData(fdms.ui.struts.form.MiscCashReceiptsForm form, ActionErrors errors) {

    try {

      // AmountOfTran is Required
      try {
        if (form.getAmountOfTran() == null || form.getAmountOfTran().trim().equals("")) {
          errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.nullAmountOfTran"));
          formErrors.add("amountOfTran");
        } else {
          if (FormatCurrency.convertToCurrency(form.getAmountOfTran()) == 0) {
            errors.add(
                ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.invalidAmountOfTran"));
            formErrors.add("amountOfTran");
          }
        }
      } catch (Exception e) {
        errors.add(
            ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.invalidAmountOfTran"));
        formErrors.add("amountOfTran");
      }

      // ArAcct
      if (form.getArAcct() == null || form.getArAcct().trim().equals("")) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.nullArAcct"));
        formErrors.add("arAcct");
      }

      // DateOfTran
      if (form.getDateOfTran() == null || form.getDateOfTran().trim().equals("")) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.nullDateOfTran"));
        formErrors.add("dateOfTran");
      } else {
        try {
          FormatDate.convertToDate(form.getDateOfTran());
        } catch (Exception de) {
          errors.add(
              ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.invalidDateOfTran"));
          formErrors.add("dateOfTran");
        }
      }

      // Description
      if (form.getDescription() == null || form.getDescription().trim().equals("")) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.nullDescription"));
        formErrors.add("description");
      }

      // GlAcct
      if (form.getGlAcct() == null || form.getGlAcct().trim().equals("")) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.nullGlAcct"));
        formErrors.add("glAcct");
      }

      // LocationId
      if (form.getLocationId() == null || form.getLocationId().trim().equals("")) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.nullLocationId"));
        formErrors.add("locationId");
      }

      // PayMethod
      if (form.getPayMethod() == null || form.getPayMethod().trim().equals("")) {
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.nullPayMethod"));
        formErrors.add("payMethod");
      }

      // ReceiptNo is not required but must be numeric
      try {
        if (form.getReceiptNumber() != null && (!form.getReceiptNumber().trim().equals(""))) {
          Integer.parseInt(form.getReceiptNumber());
        }
      } catch (Exception ne) {
        errors.add(
            ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.invalidReceiptNumber"));
        formErrors.add("receiptNumber");
      }

    } catch (Exception e) {
      logger.error("Catching errors in ProcessMiscCashReceipts.validateData. ", e);
    }
  }
  /** Insert the method's description here. Creation date: (11/22/2002 9:31:43 AM) */
  public void setNewForm(
      HttpServletRequest request,
      DbUserSession sessionUser,
      HttpSession session,
      fdms.ui.struts.form.MiscCashReceiptsForm form,
      ActionErrors errors) {

    DatabaseTransaction t = null;
    DbSpeedData[] dbSpeedData = null;
    DbLocation[] dbLocation = null;
    LocaleDTO userlocale = null;
    ArrayList locationList = new ArrayList();
    ArrayList glDescriptionList = new ArrayList();
    ArrayList cashAcctList = new ArrayList();
    ArrayList payMethodList = new ArrayList();
    ArrayList pleaseSelect = new ArrayList();

    // Database Access Logic
    try {
      t = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser);

      // Set the list of receipt types in session.
      SessionHelpers.setReceiptTypesInSession(request);

      // Populate the locationList collection
      dbLocation = FdmsDb.getInstance().getLocationsForRegion(t, sessionUser.getRegion());
      // AppLog.trace("DbLocation list length = " +dbLocation.length);
      for (int i = 0; i < dbLocation.length; i++) {
        String listValue = String.valueOf(dbLocation[i].getId());
        String listLabel = dbLocation[i].getName();
        locationList.add(new OptionsList(listValue, listLabel));
      }

      // Populate the glDescriptionList collection
      dbSpeedData =
          FdmsDb.getInstance()
              .getSpeedData(sessionUser.getDbLookup(), sessionUser.getRegion(), "REVTYPE");
      // AppLog.trace("DbSpeedData for REVTYPE list length = " +dbSpeedData.length);
      for (int i = 0; i < dbSpeedData.length; i++) {
        String listValue = CsvTable.getField(dbSpeedData[i].getData(), 2);
        String listLabel = CsvTable.getField(dbSpeedData[i].getData(), 1);
        glDescriptionList.add(new OptionsList(listValue, listLabel));
      }

      // Populate the cashAcctList collection
      dbSpeedData =
          FdmsDb.getInstance()
              .getSpeedData(sessionUser.getDbLookup(), sessionUser.getRegion(), "CASHTYPE");
      // AppLog.trace("DbSpeedData for CASHTYPE list length = " +dbSpeedData.length);
      for (int i = 0; i < dbSpeedData.length; i++) {
        String listValue = CsvTable.getField(dbSpeedData[i].getData(), 2);
        String listLabel = CsvTable.getField(dbSpeedData[i].getData(), 1);
        cashAcctList.add(new OptionsList(listValue, listLabel));
      }

      // Populate the payMethodList", payMethodList)
      userlocale =
          FdmsDb.getInstance().getLocale(sessionUser.getDbLookup(), sessionUser.getRegion());

      dbSpeedData =
          FdmsDb.getInstance()
              .getSpeedData(sessionUser.getDbLookup(), sessionUser.getRegion(), "PAYMETHOD");
      // AppLog.trace("DbSpeedData for PAYMETHOD list length = " +dbSpeedData.length);
      for (int i = 0; i < dbSpeedData.length; i++) {
        String listValue = dbSpeedData[i].getData().substring(0, 2);
        String listLabel = dbSpeedData[i].getData();
        payMethodList.add(new OptionsList(listValue, listLabel));
      }

      // Form Defaults
      form.setSubmitButton("");
      form.setAmountOfTran("0");
      form.setDateOfTran(FormatDate.getCurrentDateFormatedMMDDYYYY());
      form.setFormId("None");
      form.setReceiptNumber(String.valueOf(userlocale.getNextReceiptNo()));

      pleaseSelect.add(new OptionsList("", "--Select--"));
      // AppLog.trace("Finished setting miscCashReceipts form bean");

    } catch (PersistenceException pe) {
      logger.error("Persistence Exception in ProcessMiscCashReceipts.setNewForm. " + pe);
      errors.add(
          ActionErrors.GLOBAL_ERROR, new ActionError("error.PersistenceException", pe.getCause()));
    } catch (Exception pe) {
      logger.error("Exception in ProcessMiscCashReceipts.setNewForm. ", pe);
      errors.add(
          ActionErrors.GLOBAL_ERROR, new ActionError("error.GeneralException", pe.getMessage()));
    } finally {
      if (t != null) {
        try {
          t.closeConnection();
        } catch (Exception e) {
          logger.error("Error in closeConnection() : ", e);
        }
      }
    }

    // Set Form Bean Into Scope
    session.setAttribute("locationList", locationList);
    session.setAttribute("glDescriptionList", glDescriptionList);
    session.setAttribute("cashAcctList", cashAcctList);
    session.setAttribute("payMethodList", payMethodList);
    session.setAttribute("pleaseSelect", pleaseSelect);
    // AppLog.trace("Setting miscCashReceipts collection arrays into session scope.");

  }
  /**
   * Called from ProcessMiscCashReceipts, this Method sets the History record from the
   * MiscCashReceipts form values. If am error occurs, the error is stored in the errors collection.
   * Creation date: (8/13/2002 3:41:43 PM)
   */
  public void setHistory(
      DatabaseTransaction t,
      DbUserSession sessionUser,
      DbHistory dbHistory,
      fdms.ui.struts.form.MiscCashReceiptsForm form,
      ActionErrors errors) {

    String errorField = new String();
    String formField = null;
    DbLocale userlocale = null;
    DatabaseTransaction tlocale = null;
    int receiptNumber = 0;

    try {

      errorField = "VitalsMasterKey";
      dbHistory.setLMainKey(0);

      errorField = "ARAcct";
      formField = "arAcct";
      dbHistory.setCHistARacct(form.getArAcct());

      errorField = "Date";
      formField = "dateOfTran";
      dbHistory.setCHistDate(
          new java.sql.Date(FormatDate.convertToDate(form.getDateOfTran()).getTime()));

      errorField = "Description";
      formField = "description";
      dbHistory.setCHistDesc(form.getDescription());

      errorField = "GLAcct";
      formField = "glAcct";
      dbHistory.setCHistGLAcct(form.getGlAcct());

      errorField = "ManualReceipt";
      formField = "manualReceiptNo";
      dbHistory.setCHistManualReceipt(form.getManualReceiptNo());

      errorField = "OriginalPosting";
      formField = "";
      dbHistory.setCHistOriginalPosting('N');

      errorField = "PayMethod";
      formField = "getPayMethod";
      dbHistory.setCHistPayMethod(form.getPayMethod());

      errorField = "Posted";
      formField = "";
      dbHistory.setCHistPosted('N');

      errorField = "SPF";
      formField = "";
      dbHistory.setCHistSPF('R');

      // Set Receipt Number from locale
      try {
        tlocale = (DatabaseTransaction) DatabaseTransaction.getTransaction(sessionUser);
        userlocale = FdmsDb.getInstance().getLocaleWithLock(tlocale, sessionUser.getRegion());
        if (userlocale == null) {
          throw new java.sql.SQLException("No locale for user region.");
        }
        receiptNumber = userlocale.getNextReceiptNo();
        userlocale.setNextReceiptNo(receiptNumber + 1);
        tlocale.addPersistent(userlocale);
        tlocale.save();
        // AppLog.trace("ProcessMiscCashReceipts: next receipt number = " +receiptNumber);

      } catch (java.sql.SQLException e) {
        if (e.getErrorCode() == 1205) {
          // AppLog.warning("ProcessMiscCashReceipts - DbLocale locked from updating."
          // +sessionUser.getRegion());
          throw new PersistenceException("User locale temporarily locked. Try again.");
        }
        // AppLog.warning("ProcessMiscCashReceipts - invalid region for user "
        // +sessionUser.getUserName());
        throw new PersistenceException("Invalid region for user", e);
      } finally {
        if (t != null) {
          t.closeConnection();
        }
      }

      errorField = "ReceiptNo";
      dbHistory.setLHistReceiptNo(receiptNumber);

      errorField = "Amount";
      dbHistory.setLHistAmount(
          FormatNumber.parseInteger(
              String.valueOf(FormatCurrency.convertToCurrency(form.getAmountOfTran()))));

      errorField = "LocationId";
      dbHistory.setLocationId(Integer.parseInt(form.getLocationId()));

      t.addPersistent(dbHistory);

    } catch (Exception e) {
      errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.receipts.set" + errorField));
      formErrors.add(formField);
    }

    return;
  }
  /**
   * Method execute
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return ActionForward
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws javax.servlet.ServletException, java.io.IOException {

    HttpSession session = request.getSession();
    DbUserSession user = (DbUserSession) session.getAttribute(SessionValueKeys.DB_USER);
    ReportForm reportForm = (ReportForm) form;
    ActionMessages errors = new ActionMessages();

    // ArrayList <CheckListBean> checkURL = new ArrayList <CheckListBean>();
    // session.setAttribute("checkURL", checkURL);

    String requestType = reportForm.getRequestType();
    if (requestType == null) {
      requestType = "";
    }
    String pageName = "";
    reportForm.setReportURL(pageName);
    setReport(reportForm, user, session, errors, request);

    if (reportForm.getListType() == null) {
      reportForm.setListType(request.getParameter("all"));
    } else {
      reportForm.setListType(reportForm.getListType());
    }

    if (requestType.compareToIgnoreCase("changeLocale") == 0) {
      changeLocale(reportForm, user, session, errors, request);
      // changeCategory(reportForm, user, session, errors, request);
      return (mapping.findForward("localeChange"));
    } else if (requestType.compareToIgnoreCase("changeLocation") == 0) {
      // changeCategory(reportForm, user, session, errors, request);
      return (mapping.findForward("localeChange"));
    } else if (requestType.compareToIgnoreCase("changeCategory") == 0) {
      // changeCategory(reportForm, user, session, errors, request);
      return (mapping.findForward("localeChange"));
    } else {

      // ArrayList <OptionsList> reports = new ArrayList<OptionsList>();
      // reports.add( new OptionsList( "0" ,"--Select--"));
      // request.setAttribute("reports",reports);
    }

    if (requestType.compareToIgnoreCase("print") == 0) {

      //			Timer smsTimer = new Timer("SMSThread", true);
      //			CompanyManagerBean cmBean = new CompanyManagerBean();
      //			CompanyDTO company = cmBean.getCompany(user.getCompanyID());
      //			smsTimer.schedule(new SMSGenerator(company,1), 0l);

      ReportSchedulingDTO reportScheduling = new ReportSchedulingDTO();
      setReportScheduling(reportForm, reportScheduling, errors, user);
      reportScheduling.setReportType(ReportSchedulingDTO.REPORT_TYPE_REALTIME);
      reportScheduling.setStatus("Q");
      ReportSchedulingDAO reportScheDAo = new ReportSchedulingDAO(user);
      try {
        reportScheDAo.addReportScheduling(reportScheduling);
      } catch (Exception e) {

      }

      String crystalFlag =
          UtilSingleton.getInstance()
              .getProperty(user.getConfigID(), "CrystalServer.useReportingService");

      if (crystalFlag != null && "true".equals(crystalFlag)) {
        CompanyManagerBean cmBean = new CompanyManagerBean();
        CompanyDTO company = cmBean.getCompany(user.getCompanyID());
        runNow(reportScheduling, company);
      }

      reportForm.setFromDate(FormatDate.getCurrentDateFormatedMMDDYYYY());
      reportForm.setToDate(FormatDate.getCurrentDateFormatedMMDDYYYY());
      reportForm.setUserLocaleId("0");
      reportForm.setUserLocationId("0");
      reportForm.setCategory("0");

    } else if (requestType.compareToIgnoreCase("schedule") == 0) {

      ReportSchedulingDTO reportScheduling = new ReportSchedulingDTO();
      setReportScheduling(reportForm, reportScheduling, errors, user);

      int repeatNumber = 0;
      try {
        repeatNumber = FormatNumber.parseInteger(reportForm.getRepeatNumber());
      } catch (Exception e) {
        //
      }
      String fromDate = getFromDate(reportForm, errors);
      java.util.Date fDate = FormatDate.convertToDateYYMMDD(fromDate);
      String toDate = getToDate(reportForm, errors);
      java.util.Date tDate = FormatDate.convertToDateYYMMDD(toDate);
      Date rDate = new Date();
      try {
        rDate = FormatDate.convertToDate(reportForm.getRunDate());
      } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.date.rundate"));
        formErrors.add("runDate");
      }

      ReportSchedulingDAO reportScheDAo = new ReportSchedulingDAO(user);

      if (repeatNumber > 0) { // do more than 1 time.

        boolean scheduleNow = true;
        Timer timer = new Timer(true);

        for (int i = 0; i < repeatNumber; i++) {
          try {
            //						ReportSchedulingDTO aSchedule = new ReportSchedulingDTO();
            //						copyObj(reportScheduling,aSchedule);
            reportScheDAo.addReportScheduling(reportScheduling);
            if (scheduleNow) {
              Calendar date = Calendar.getInstance();
              date.setTime((java.util.Date) reportScheduling.getRunDate());
              // date.add(Calendar.MINUTE, 5);
              // set runtime. (CDT)
              date.set(Calendar.HOUR_OF_DAY, reportScheduling.getRunTimeHH()); // 0-23

              date.set(Calendar.MINUTE, reportScheduling.getRunTimeMM());
              if (date.getTimeInMillis() <= System.currentTimeMillis()) {
                CompanyManagerBean cmBean = new CompanyManagerBean();
                CompanyDTO company = cmBean.getCompany(user.getCompanyID());
                runNow(reportScheduling, company);
              } else {
                scheduleNow = false;
              }
            }
            // setSchedule(timer, aSchedule, user);
            ReportSchedulingDTO aSchedule = new ReportSchedulingDTO();
            copyObj(reportScheduling, aSchedule);
            reportScheduling = aSchedule;
          } catch (Exception e) {

          }

          String strFDate = FormatDate.convertDateToMMDDYYYY(fDate);
          String strTDate = FormatDate.convertDateToMMDDYYYY(tDate);
          String strRDate = FormatDate.convertDateToMMDDYYYY(rDate);
          int field = -1;
          if (reportForm.getRepeatType().compareToIgnoreCase("D") == 0) {
            field = 1;

          } else if (reportForm.getRepeatType().compareToIgnoreCase("W") == 0) {
            field = 7;

          } else if (reportForm.getRepeatType().compareToIgnoreCase("M") == 0) {
            field = 0;
          }
          if (field > -1) {
            strRDate = FormatDate.addToDateMMDDYYYY(strRDate, field, (field == 0 ? 1 : 0));
            strFDate = FormatDate.addToDateMMDDYYYY(strFDate, field, (field == 0 ? 1 : 0));
            strTDate = FormatDate.addToDateMMDDYYYY(strTDate, field, (field == 0 ? 1 : 0));
            rDate = FormatDate.convertMMDDYYYYToDateYYMMDD(strRDate);
            fDate = FormatDate.convertMMDDYYYYToDateYYMMDD(strFDate);
            tDate = FormatDate.convertMMDDYYYYToDateYYMMDD(strTDate);
            reportScheduling.setRunDate(new java.sql.Date(rDate.getTime()));
            reportScheduling.setFromDate(new java.sql.Date(fDate.getTime()));
            reportScheduling.setToDate(new java.sql.Date(tDate.getTime()));
          }
        }
      } else { // do only one time
        try {
          reportScheDAo.addReportScheduling(reportScheduling);
          Calendar date = Calendar.getInstance();
          date.setTime((java.util.Date) reportScheduling.getRunDate());
          // date.add(Calendar.MINUTE, 5);
          // set runtime. (CDT)
          date.set(Calendar.HOUR_OF_DAY, reportScheduling.getRunTimeHH()); // 0-23

          date.set(Calendar.MINUTE, reportScheduling.getRunTimeMM());
          if (date.getTimeInMillis() <= System.currentTimeMillis()) {
            CompanyManagerBean cmBean = new CompanyManagerBean();
            CompanyDTO company = cmBean.getCompany(user.getCompanyID());
            runNow(reportScheduling, company);
          }
          // setSchedule( null, reportScheduling,  user);
        } catch (Exception e) {

        }
      }
    }
    // we comment it out because we don't want it to do the pupup but let the user look at the
    // printed report list.
    // reportForm.setReportURL(pageName);
    return (mapping.findForward("localeChange"));
  }
  private void setReportScheduling(
      ReportForm reportForm,
      ReportSchedulingDTO reportScheduling,
      ActionMessages errors,
      DbUserSession user) {
    int formID = 0;
    try {
      formID = FormatNumber.parseInteger(reportForm.getSelectReport());
    } catch (Exception e) {
      //
    }

    // for only locale/location
    // Get selected location
    String location = null;
    try {
      location = reportForm.getUserLocationId();
    } catch (Exception e) {
      //
    }
    // Get selected location
    String locale = null;
    try {
      locale = reportForm.getUserLocaleId();
    } catch (Exception e) {
      //
    }

    // for this array version we don't need.
    //		String strLocale = null;
    //		String strLocation = null;
    //		if (Constants.GLOBAL_LOCALE_STRING.equals(reportForm.getType())) { // for all locales
    //			strLocale = "ALL";
    //			strLocation = "ALL";
    //
    //		} else if (Constants.GLOBAL_LOCATION_STRING.equals(reportForm.getType())) { // for specific
    // locales
    //			String[] localeIds = reportForm.getLocaleIds();
    //			strLocale = "[";
    //			for (int i = 0; i < localeIds.length; i++) {
    //				if (strLocale.length()> 1){
    //	        		strLocale += ",";
    //				}
    //	        	strLocale = strLocale+localeIds[i];
    //			}
    //			 strLocale = strLocale+"]";
    //			 strLocation = "ALL";
    //		}
    //		else { //for specific locations.
    //			strLocale="ALL";
    //			String[] locationIds = reportForm.getLocaleIds();
    //			strLocation="[";
    //			for (int i = 0; i < locationIds.length; i++) {
    //				if (strLocation.length()> 1){
    //					strLocation += ",";
    //				}
    //				strLocation = strLocation+locationIds[i];
    //			}
    //			strLocation = strLocation+"]";
    //		}
    // end for this version

    String repeatType = "N";
    int repeatNumber = 0;

    reportScheduling.setFormID(formID);
    reportScheduling.setUserId(user.getId());
    // for only one locale version
    reportScheduling.setLocale(locale);
    reportScheduling.setLocation(location);
    // end

    // for this locals/locations
    //		reportScheduling.setLocale(strLocale);
    //		reportScheduling.setLocation(strLocation);
    // end version

    String fromDate = getFromDate(reportForm, errors);
    java.util.Date fDate = FormatDate.convertToDateYYMMDD(fromDate);

    try {
      reportScheduling.setFromDate(new java.sql.Date(fDate.getTime()));
    } catch (Exception e) {
      errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.date.fromdate"));
      formErrors.add("fromDate");
    }

    String toDate = getToDate(reportForm, errors);
    java.util.Date tDate = FormatDate.convertToDateYYMMDD(toDate);
    try {
      reportScheduling.setToDate(new java.sql.Date(tDate.getTime()));
    } catch (Exception e) {
      errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.date.todate"));
      formErrors.add("toDate");
    }

    Date rDate = new Date();

    try {
      reportScheduling.setRunDate(new java.sql.Date(rDate.getTime()));
    } catch (Exception e) {
      errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.date.todate"));
      formErrors.add("toDate");
    }

    int runHH = reportForm.getHH();
    reportScheduling.setRunTimeHH(runHH);
    int runMM = reportForm.getMM();
    reportScheduling.setRunTimeMM(runMM);

    reportScheduling.setRepeatType(repeatType);
    reportScheduling.setRepeatNumber(repeatNumber);
    long createdTimestamp = System.currentTimeMillis();
    reportScheduling.setDatetime(createdTimestamp);

    String emailTo = "";
    reportScheduling.setEmailTo(emailTo);
    String emailCC = "";
    reportScheduling.setEmailCC(emailCC);

    reportScheduling.setStatus("");
    reportScheduling.setReportName("");

    String requestType = reportForm.getRequestType();
    if (requestType == null) {
      requestType = "";
    }
    if (requestType.compareToIgnoreCase("schedule") == 0) {
      repeatType = reportForm.getRepeatType();
      repeatNumber = 0;
      try {
        repeatNumber = FormatNumber.parseInteger(reportForm.getRepeatNumber());
      } catch (Exception e) {
        //
      }
      reportScheduling.setRepeatType(repeatType);

      try {
        rDate = FormatDate.convertToDate(reportForm.getRunDate());
      } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.date.rundate"));
        formErrors.add("runDate");
      }

      try {
        reportScheduling.setRunDate(new java.sql.Date(rDate.getTime()));
      } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.date.runDate"));
        formErrors.add("runDate");
      }

      reportScheduling.setRepeatType(repeatType);
      reportScheduling.setRepeatNumber(repeatNumber);
      createdTimestamp = System.currentTimeMillis();
      reportScheduling.setDatetime(createdTimestamp);
      reportScheduling.setReportName("");
      emailTo = "";
      emailTo = reportForm.getRecipientsTo().replace(':', ';');
      emailTo = emailTo.replace(' ', ';');
      emailTo = emailTo.replace(',', ';');
      reportScheduling.setEmailTo(emailTo);
      emailCC = "";
      emailCC = reportForm.getRecipientsCC().replace(':', ';');
      emailCC = emailCC.replace(' ', ';');
      emailCC = emailCC.replace(',', ';');
      reportScheduling.setEmailCC(emailCC);
      reportScheduling.setStatus("Q");
      reportScheduling.setReportType(ReportSchedulingDTO.REPORT_TYPE_SCHEDULING);
    }
  }