com.rr.wabshs.ui.clients.clientController.java Source code

Java tutorial

Introduction

Here is the source code for com.rr.wabshs.ui.clients.clientController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rr.wabshs.ui.clients;

import com.rr.wabshs.ui.security.decryptObject;
import com.rr.wabshs.ui.security.encryptObject;
import com.registryKit.user.User;
import com.registryKit.client.clientSearchFields;
import com.registryKit.client.modifiedFields;
import com.registryKit.program.programManager;
import com.registryKit.program.program;
import com.registryKit.client.programClientFields;
import com.registryKit.client.programClientSections;
import com.registryKit.client.programClients;
import com.registryKit.client.storageClientAddressInfo;
import com.registryKit.client.storageClients;
import com.registryKit.client.clientManager;
import com.registryKit.client.crosswalkData;
import com.registryKit.client.customProgramFields;
import com.registryKit.client.engagementManager;
import com.registryKit.client.engagements;
import com.registryKit.client.programClientEntities;
import com.registryKit.client.programPatientEntryMethods;
import com.registryKit.hierarchy.hierarchyManager;
import com.registryKit.hierarchy.programHierarchyDetails;
import com.registryKit.partnerProfile.partnerProfileManager;
import com.registryKit.partnerProfile.partnerprofile;
import com.registryKit.programProfile.programProfileFields;
import com.registryKit.programProfile.programProfileManager;
import com.registryKit.survey.participantSurveyAssoc;
import com.registryKit.survey.participants;
import com.registryKit.survey.submittedSurveys;
import com.registryKit.survey.submittedsurveyforsessionparticipant;
import com.registryKit.survey.submittedsurveyprogramprofiles;
import com.registryKit.survey.submittedsurveysessionaggregatedata;
import com.registryKit.survey.submittedsurveysessiondocuments;
import com.registryKit.survey.submittedsurveysessionparticipants;
import com.registryKit.survey.submittedsurveysessionpartners;
import com.registryKit.survey.submittedsurveysessionpopulationreacheddata;
import com.registryKit.survey.submittedsurveysessions;
import com.registryKit.survey.submittedsurveysessionstaff;
import com.registryKit.survey.surveyManager;
import com.registryKit.survey.surveys;
import com.registryKit.user.userManager;
import com.registryKit.user.userProgramModules;
import com.rr.wabshs.ui.reference.USStateList;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author chadmccue
 */
@Controller
@RequestMapping(value = { "/clients", "/participants" })
public class clientController {

    private static Integer moduleId = 1;

    @Autowired
    private programManager programmanager;

    @Autowired
    private clientManager clientmanager;

    @Autowired
    private userManager usermanager;

    @Autowired
    private hierarchyManager hierarchymanager;

    @Autowired
    private engagementManager engagementmanager;

    @Autowired
    private surveyManager surveymanager;

    @Autowired
    private programProfileManager programprofilemanager;

    @Autowired
    private partnerProfileManager partnerprofilemanager;

    @Value("${programId}")
    private Integer programId;

    private List<clientSearchFields> searchFields = null;

    @Value("${topSecret}")
    private String topSecret;

    private static boolean allowCreate = false;
    private static boolean allowEdit = false;
    private static boolean allowDelete = false;

    /**
     * The '' request will display the list of client.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView listClients(HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws Exception {

        program programDetails = programmanager.getProgramById(programId);

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/clients");

        /* Get the client search fields */
        List<clientSearchFields> programSearchFields = clientmanager.getClientSearchFields(programId);
        mav.addObject("programSearchFields", programSearchFields);

        searchFields = programSearchFields;

        /* Get the client entry methods */
        List<programPatientEntryMethods> entryMethods = clientmanager.getClientEntryMethods(programId);
        mav.addObject("entryMethods", entryMethods);

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        /* Get user permissions */
        userProgramModules modulePermissions = usermanager.getUserModulePermissions(programId, userDetails.getId(),
                moduleId);
        Integer userId = 0;
        if (userDetails.getRoleId() == 2) {
            allowCreate = true;
            allowDelete = true;
        } else {
            allowCreate = modulePermissions.isAllowCreate();
            allowDelete = modulePermissions.isAllowDelete();
            userId = userDetails.getId();
        }

        mav.addObject("allowCreate", allowCreate);
        mav.addObject("allowDelete", allowDelete);

        List<Object[]> entities = hierarchymanager.getProgramHierarchyTitles(programId);

        List<programHierarchyDetails> level1Items = hierarchymanager
                .getProgramHierarchyItems((Integer) entities.get(0)[0], userId);
        mav.addObject("level1Items", level1Items);

        mav.addObject("level1Name", entities.get(0)[1]);
        mav.addObject("level2Name", entities.get(1)[1]);
        mav.addObject("level3Name", entities.get(2)[1]);

        mav.addObject("savedSearchString", session.getAttribute("searchString"));
        mav.addObject("savedSearchEntity1", session.getAttribute("selectedEntity1"));
        mav.addObject("savedSearchEntity2", session.getAttribute("selectedEntity2"));
        mav.addObject("savedSearchEntity3", session.getAttribute("selectedEntity3"));

        return mav;
    }

    /**
     * The 'getClientList' GET request will return the view containing the table for the list of client based on the search parameters.
     * 
     * @param request
     * @param response
     * @param session
     * @param searchString  The string containing the list of search parameters.
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "getClientList", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView getClientList(HttpSession session,
            @RequestParam(value = "searchString", required = false) String searchString,
            @RequestParam(value = "selectedEntity1", required = true) Integer selectedEntity1,
            @RequestParam(value = "selectedEntity2", required = true) Integer selectedEntity2,
            @RequestParam(value = "selectedEntity3", required = true) Integer selectedEntity3) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/clients/clientList");

        session.setAttribute("searchString", searchString);
        session.setAttribute("selectedEntity1", selectedEntity1);
        session.setAttribute("selectedEntity2", selectedEntity2);
        session.setAttribute("selectedEntity3", selectedEntity3);

        /* Get the client */
        List<Integer> clientIds = clientmanager.getClients(programId, searchFields, searchString, selectedEntity1,
                selectedEntity2, selectedEntity3, true);

        List<client> clients = new ArrayList<client>();

        /* Get the client details */
        if (!clientIds.isEmpty()) {
            for (Integer id : clientIds) {

                storageClients clientDetails = clientmanager.getClientDetails(id);
                storageClientAddressInfo addressInfo = clientmanager.getClientAddressInfo(id);

                client c = new client();
                if (clientDetails.getFirstName() != null && clientDetails.getLastName() != null) {
                    c.setName(clientDetails.getFirstName() + " " + clientDetails.getLastName());
                }
                c.setSourcePatientId(clientDetails.getSourcePatientId());
                c.setEmail(clientDetails.getEmail());
                c.setDateReferred(clientDetails.getDateCreated());
                c.setAddress(addressInfo.getAddress1());
                c.setAddress2(addressInfo.getAddress2());
                c.setCity(addressInfo.getCity());
                c.setState(addressInfo.getState());
                c.setZip(addressInfo.getZipCode());
                c.setPhoneNumber(addressInfo.getPhone1());

                /* Get the client engagements */
                c.setLastEngagement(engagementmanager.getLastEngagement(id, programId, "visitDate"));

                encryptObject encrypt = new encryptObject();
                Map<String, String> map;

                //Encrypt the use id to pass in the url
                map = new HashMap<String, String>();
                map.put("id", Integer.toString(id));
                map.put("topSecret", topSecret);

                String[] encrypted = encrypt.encryptObject(map);

                c.setEncryptedId(encrypted[0]);
                c.setEncryptedSecret(encrypted[1]);

                clients.add(c);

            }
        }
        mav.addObject("clients", clients);
        mav.addObject("searchString", searchString);

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        /* Get user permissions */
        userProgramModules modulePermissions = usermanager.getUserModulePermissions(programId, userDetails.getId(),
                moduleId);
        if (userDetails.getRoleId() == 2) {
            allowCreate = true;
            allowDelete = true;
        } else {
            allowCreate = modulePermissions.isAllowCreate();
            allowDelete = modulePermissions.isAllowDelete();
        }

        mav.addObject("allowCreate", allowCreate);
        mav.addObject("allowDelete", allowDelete);

        return mav;
    }

    /**
     * The '/createClientByEngagement' request will submit the new client number as a new client and return the 
     * encrypted id values.
     *
     * @param clientNumber  The number entered for the new client
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/createClientByEngagement", method = RequestMethod.POST)
    @ResponseBody
    public String createClientByEngagement(HttpSession session, @RequestParam Integer clientNumber)
            throws Exception {

        User userDetails = (User) session.getAttribute("userDetails");

        programClients newClient = new programClients();
        newClient.setProgramId(programId);
        newClient.setMciReview(false);
        newClient.setStatus(true);
        newClient.setSystemUserId(userDetails.getId());

        int clientId = clientmanager.saveNewClient(newClient);

        /* Create new storage_pateint entry */
        clientmanager.savePatientClientNumber(clientId, clientNumber);

        Map<String, String> map = new HashMap<String, String>();
        map.put("id", Integer.toString(clientId));
        map.put("topSecret", topSecret);

        encryptObject encrypt = new encryptObject();

        String[] encrypted = encrypt.encryptObject(map);

        String returnString = "i=" + encrypted[0] + "&v=" + encrypted[1];

        return returnString;

    }

    /**
     * The '/details' GET request will display the selected client details page.
     * 
     * @param i The encrypted url value containing the selected user id
     * @param v The encrypted url value containing the secret decode key
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public ModelAndView getClientDetails(HttpSession session, @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v) throws Exception {

        ModelAndView mav = new ModelAndView();

        User userDetails = (User) session.getAttribute("userDetails");

        int clientId = 0;

        if (i != null && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            clientId = Integer.parseInt(result[0].substring(4));
        }

        List<programClientSections> sections = clientmanager.getSections(programId);

        if (sections != null && sections.size() > 0) {

            for (programClientSections section : sections) {

                /* Get the fields associated the section */
                List<programClientFields> sectionFields = clientmanager.getClientFields(section.getId(), programId,
                        clientId);

                if (sectionFields != null && sectionFields.size() > 0) {
                    section.setSectionFields(sectionFields);
                }
            }

        }

        programClients client;

        if (clientId == 0) {
            mav.setViewName("/newClient");
            mav.addObject("allowEdit", true);
        } else {
            client = clientmanager.getProgramClient(clientId);

            programClientEntities clientEntities = clientmanager.getClientEntities(clientId);
            mav.addObject("entitylevel1", clientEntities.getEntity1Id());
            mav.addObject("entitylevel2", clientEntities.getEntity2Id());
            mav.addObject("entitylevel3", clientEntities.getEntity3Id());

            mav.addObject("iparam", URLEncoder.encode(i, "UTF-8"));
            mav.addObject("vparam", URLEncoder.encode(v, "UTF-8"));

            userProgramModules modulePermissions = usermanager.getUserModulePermissions(programId,
                    userDetails.getId(), moduleId);
            if (userDetails.getRoleId() == 2) {
                allowEdit = true;
            } else {
                allowEdit = modulePermissions.isAllowEdit();
            }

            mav.addObject("allowEdit", allowEdit);

            mav.setViewName("/clientDetails");
        }

        Integer userId;
        if (userDetails.getRoleId() == 2) {
            userId = 0;
        } else {
            userId = userDetails.getId();
        }

        clientFormDetails formDetails = new clientFormDetails();
        formDetails.setSections(sections);
        mav.addObject("formDetails", formDetails);

        mav.addObject("clientId", clientId);

        List<Object[]> entities = hierarchymanager.getProgramHierarchyTitles(programId);

        List<programHierarchyDetails> level1Items = hierarchymanager
                .getProgramHierarchyItems((Integer) entities.get(0)[0], userId);
        mav.addObject("level1Items", level1Items);

        mav.addObject("level1Name", entities.get(0)[1]);
        mav.addObject("level2Name", entities.get(1)[1]);
        mav.addObject("level3Name", entities.get(2)[1]);

        return mav;
    }

    /**
     * The '/details' POST request will submit the client details form.
     * 
     * @param client    The object containing all the client detail form fields
     * @param i     The encrypted url value containing the selected user id
     * @param v     The encrypted url value containing the secret decode key
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/details", method = RequestMethod.POST)
    public ModelAndView saveClientDetails(@ModelAttribute(value = "formDetails") clientFormDetails formDetails,
            HttpSession session, RedirectAttributes redirectAttr, @RequestParam String action,
            @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v,
            @RequestParam(value = "level1Entity", required = true) Integer level1Entity,
            @RequestParam(value = "level2Entity", required = true) Integer level2Entity,
            @RequestParam(value = "level3Entity", required = true) Integer level3Entity) throws Exception {

        int clientId = 0;

        String returnString;

        boolean newClient = false;

        User userDetails = (User) session.getAttribute("userDetails");

        if (i != null && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            clientId = Integer.parseInt(result[0].substring(4));

            returnString = "i=" + URLEncoder.encode(i, "UTF-8") + "&v=" + URLEncoder.encode(v, "UTF-8");

        } else {
            programClients client = new programClients();
            client.setProgramId(programId);
            client.setSystemUserId(userDetails.getId());
            client.setMciReview(false);
            client.setStatus(true);

            clientId = clientmanager.saveNewClient(client);

            Map<String, String> map = new HashMap<String, String>();
            map.put("id", Integer.toString(clientId));
            map.put("topSecret", topSecret);

            encryptObject encrypt = new encryptObject();

            String[] encrypted = encrypt.encryptObject(map);

            returnString = "i=" + encrypted[0] + "&v=" + encrypted[1];

            newClient = true;

        }

        programClientEntities clientEntity = new programClientEntities();
        clientEntity.setEngagementId(0);
        clientEntity.setProgramPatientId(clientId);
        clientEntity.setEntity1Id(level1Entity);
        clientEntity.setEntity2Id(level2Entity);
        clientEntity.setEntity3Id(level3Entity);

        clientmanager.saveClientEntity(clientEntity);

        List<programClientSections> sections = formDetails.getSections();

        if (null != sections && sections.size() > 0) {
            for (programClientSections section : sections) {
                List<programClientFields> sectionFields = section.getSectionFields();
                if (null != sectionFields && sectionFields.size() > 0) {
                    clientmanager.updateClientFields(newClient, clientId, sectionFields, userDetails.getId());
                }
            }
        }

        if (action.equals("save")) {

            //If new patient send directly to the engagment form
            if (newClient) {
                redirectAttr.addFlashAttribute("savedStatus", "updated");
                ModelAndView mav = new ModelAndView(
                        new RedirectView("/clients/engagements/details?" + returnString));
                return mav;
            } else {
                redirectAttr.addFlashAttribute("savedStatus", "updated");
                ModelAndView mav = new ModelAndView(new RedirectView("/clients/details?" + returnString));
                return mav;
            }

        } else {
            ModelAndView mav = new ModelAndView(new RedirectView("/clients?msg=updated"));
            return mav;
        }

    }

    /**
     * The 'getFieldModifications' GET request will return the list of field modifications.
     * 
     * @param session
     * @param fieldId The field to retrieve modifications for
     * @param clientId  The client to get the modifications for
     * @return  The request will return the modifiedList view
     * @throws Exception 
     */
    @RequestMapping(value = "/getFieldModifications", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView getFieldModifications(HttpSession session,
            @RequestParam(value = "fieldId", required = true) Integer fieldId,
            @RequestParam(value = "clientId", required = true) Integer clientId) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/clients/modifiedList");

        /* Get the field modifications */
        List<modifiedFields> fieldModifications = clientmanager.getFieldModifications(programId, fieldId, clientId);
        mav.addObject("fieldModifications", fieldModifications);
        return mav;

    }

    /**
    * The '/getEntityValues.do' GET request will return a list of columns for the passed in organization entity
    *
    * @param tableName
    *
    * @return The function will return a list of organization hierarchy items.
    */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/getEntityValues.do", method = RequestMethod.GET)
    @ResponseBody
    public List getEntityValues(HttpSession session,
            @RequestParam(value = "entityValue", required = true) Integer entityValue,
            @RequestParam(value = "level", required = true) Integer level) throws Exception {

        User userDetails = (User) session.getAttribute("userDetails");

        Integer userId;
        if (userDetails.getRoleId() == 2) {
            userId = 0;
        } else {
            userId = userDetails.getId();
        }

        List values = hierarchymanager.getProgramOrgHierarchyItems(programId, level, entityValue, userId);

        return values;
    }

    /**
    * The '/getActiveEntityValues.do' GET request will return a list of columns for the passed in organization entity
    *
    * @param tableName
    *
    * @return The function will return a list of organization hierarchy items.
    */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/getActiveEntityValues.do", method = RequestMethod.GET)
    @ResponseBody
    public List getActiveEntityValues(HttpSession session,
            @RequestParam(value = "entityValue", required = true) Integer entityValue,
            @RequestParam(value = "level", required = true) Integer level) throws Exception {

        User userDetails = (User) session.getAttribute("userDetails");

        Integer userId;
        if (userDetails.getRoleId() == 2) {
            userId = 0;
        } else {
            userId = userDetails.getId();
        }

        List values = hierarchymanager.getActiveProgramOrgHierarchyItems(programId, level, entityValue, userId);

        return values;
    }

    /**
     * The '/getMultipleEntityValues.do' GET request will return a list of columns for the passed in organization entity
     *
     * @param tableName
     *
     * @return The function will return a list of organization hierarchy items.
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/getMultipleEntityValues.do", method = RequestMethod.GET)
    @ResponseBody
    public List getMultipleEntityValues(HttpSession session,
            @RequestParam(value = "entityValues", required = true) List<String> entityValues,
            @RequestParam(value = "level", required = true) Integer level) throws Exception {

        User userDetails = (User) session.getAttribute("userDetails");

        Integer userId;
        if (userDetails.getRoleId() == 2) {
            userId = 0;
        } else {
            userId = userDetails.getId();
        }

        List values = hierarchymanager.getProgramOrgHierarchyItems(programId, level, entityValues, userId);

        return values;
    }

    /**
     * The '/getMultipleActiveEntityValues.do' GET request will return a list of columns for the passed in organization entity
     *
     * @param tableName
     *
     * @return The function will return a list of organization hierarchy items.
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/getMultipleActiveEntityValues.do", method = RequestMethod.GET)
    @ResponseBody
    public List getMultipleActiveEntityValues(HttpSession session,
            @RequestParam(value = "entityValues", required = true) List<String> entityValues,
            @RequestParam(value = "level", required = true) Integer level) throws Exception {

        User userDetails = (User) session.getAttribute("userDetails");

        Integer userId;
        if (userDetails.getRoleId() == 2) {
            userId = 0;
        } else {
            userId = userDetails.getId();
        }

        List values = hierarchymanager.getActiveProgramOrgHierarchyItems(programId, level, entityValues, userId);

        return values;
    }

    /**
     * The 'checkParticipantId' GET request will query the system to make sure the participant Id is not already used for the selected site.
     * 
     * @param i
     * @param v
     * @param enteredDate
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/checkParticipantId", method = RequestMethod.GET, produces = {
            MediaType.TEXT_PLAIN_VALUE })
    @ResponseBody
    public String checkParticipantId(@RequestParam Integer clientid, @RequestParam String participantId,
            @RequestParam Integer level3Entity) throws Exception {

        boolean participantIdOk = clientmanager.checkParticipantId(clientid, participantId, programId, level3Entity,
                "sourcePatientId");

        return Boolean.toString(participantIdOk);

    }

    /**
     * The '/deleteClient' GET request will change the status of the selected client .
     * 
     * @param i The encrypted url value containing the selected user id
     * @param v The encrypted url value containing the secret decode key
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/deleteClient", method = RequestMethod.GET)
    @ResponseBody
    public boolean deleteClient(HttpSession session, @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v) throws Exception {

        boolean returnVal = true;

        if (i != null && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            Integer clientId = Integer.parseInt(result[0].substring(4));

            /* Check the client has no sessions */
            List<engagements> clientEngagements = engagementmanager.getEngagements(clientId, programId);

            if (clientEngagements == null || clientEngagements.size() == 0) {
                //programClients clientDetails = clientmanager.getProgramClient(clientId);

                //clientDetails.setStatus(false);

                //clientmanager.updateClient(clientDetails);
                clientmanager.deleteClient(clientId, programId);

            } else {
                returnVal = false;
            }
        }

        return returnVal;
    }

    /**
    * The '/activityLogs' request will display the list of submitted activity logs.
    *
    * @param request
    * @param response
    * @return   the administrator dashboard view
    * @throws Exception
    */
    @RequestMapping(value = "/activityLogs", method = RequestMethod.GET)
    public ModelAndView listActivityLogs(HttpServletRequest request, HttpServletResponse response,
            HttpSession session) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/participants/activityLogs");

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        List<submittedSurveys> activityLogs = new ArrayList<submittedSurveys>();

        List<submittedSurveys> submittedSurveys = surveymanager.getActivityLogsForSessionData(userDetails,
                programId);

        if (submittedSurveys != null && submittedSurveys.size() > 0) {
            encryptObject encrypt = new encryptObject();
            Map<String, String> map;
            for (submittedSurveys submittedSurvey : submittedSurveys) {
                boolean addSubmittedSurvey = false;
                //if(submittedSurvey.getSelectedProgramIds() != null && !"".equals(submittedSurvey.getSelectedProgramIds())) {
                //if(!"".equals(submittedSurvey.getTrackIndividuals()) && "Yes".equals(submittedSurvey.getTrackIndividuals())) {
                addSubmittedSurvey = true;
                //}
                //}

                if (addSubmittedSurvey == true) {
                    //Encrypt the use id to pass in the url
                    map = new HashMap<String, String>();
                    map.put("id", Integer.toString(submittedSurvey.getId()));
                    map.put("topSecret", topSecret);

                    String[] encrypted = encrypt.encryptObject(map);

                    submittedSurvey.setEncryptedId(encrypted[0]);
                    submittedSurvey.setEncryptedSecret(encrypted[1]);
                    activityLogs.add(submittedSurvey);
                }
            }
        }

        mav.addObject("activityLogs", activityLogs);

        return mav;

    }

    /**
     * The '/activityLogs/sessions' request will display the list of submitted activity log sessions.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/sessions", method = RequestMethod.GET)
    public ModelAndView listActivityLogSessions(HttpServletRequest request, HttpServletResponse response,
            HttpSession session, @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v,
            @RequestParam(value = "j", required = false) Integer j) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/participants/activityLogs/sessions");

        int submittedSurveyId = 0;
        boolean allowNewSession = false;

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        /* Get user permissions */
        userProgramModules modulePermissions = usermanager.getUserModulePermissions(programId, userDetails.getId(),
                moduleId);
        Integer userId = 0;
        boolean allowStaffAccess = false;
        boolean allowCreate = false;
        boolean allowEdit = false;
        boolean allowDelete = false;

        if (userDetails.getRoleId() == 2) {
            allowStaffAccess = true;
            allowCreate = true;
            allowEdit = true;
            allowDelete = true;
        } else {
            userId = userDetails.getId();
            if (modulePermissions.isAllowLevel3()) {
                allowStaffAccess = true;
            }
            allowCreate = modulePermissions.isAllowCreate();
            allowEdit = modulePermissions.isAllowEdit();
            allowDelete = modulePermissions.isAllowDelete();
        }

        mav.addObject("allowCreate", allowCreate);
        mav.addObject("allowEdit", allowEdit);
        mav.addObject("allowDelete", allowDelete);

        mav.addObject("allowStaffAccess", allowStaffAccess);

        if (i != null && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            submittedSurveyId = Integer.parseInt(result[0].substring(4));

            /* Get the selected program */
            submittedsurveyprogramprofiles selProgram = surveymanager.getSurveySelectedPrograms(submittedSurveyId,
                    0, 0);

            // Need to figure out how data is being tracked for this survey submission
            String dataTrackedBy = "Enter Individual data";

            submittedSurveys submittedSurveyDetails = surveymanager.getActivityLogsForSessionData(userDetails,
                    programId, submittedSurveyId);
            mav.addObject("submittedSurveyDetails", submittedSurveyDetails);

            String submittedSurveyAnswer = surveymanager.getSubmittedSurveyQuestionAnswerByQuestionTag(
                    submittedSurveyId, submittedSurveyDetails.getSurveyId(), "aggregateTracking");

            if (submittedSurveyAnswer != null && !"".equals(submittedSurveyAnswer)) {
                if ("Aggregate".equals(submittedSurveyAnswer)
                        || "Individual participant".equals(submittedSurveyAnswer)
                        || "Population reach".equals(submittedSurveyAnswer)) {
                    dataTrackedBy = submittedSurveyAnswer;
                }
            }

            mav.addObject("dataTrackedBy", dataTrackedBy);

            //Get a list of staff members
            List<partnerprofile> staffMembers = partnerprofilemanager.getStaffMembers(programId, userDetails,
                    submittedSurveyId);

            if (staffMembers != null && staffMembers.size() > 0) {
                encryptObject encrypt = new encryptObject();
                Map<String, String> map;
                for (partnerprofile staff : staffMembers) {
                    //Encrypt the use id to pass in the url
                    map = new HashMap<String, String>();
                    map.put("id", Integer.toString(staff.getId()));
                    map.put("topSecret", topSecret);

                    String[] encrypted = encrypt.encryptObject(map);

                    staff.setEncryptedId(encrypted[0]);
                    staff.setEncryptedSecret(encrypted[1]);
                }
            }

            mav.addObject("staffMembers", staffMembers);

            //Get a list of staff members
            List<partnerprofile> partners = partnerprofilemanager.getPartners(programId, userDetails,
                    submittedSurveyId);

            if (staffMembers != null && staffMembers.size() > 0) {
                encryptObject encrypt = new encryptObject();
                Map<String, String> map;
                for (partnerprofile partner : partners) {
                    //Encrypt the use id to pass in the url
                    map = new HashMap<String, String>();
                    map.put("id", Integer.toString(partner.getId()));
                    map.put("topSecret", topSecret);

                    String[] encrypted = encrypt.encryptObject(map);

                    if (userDetails.getRoleId() != 2) {
                        if (allowStaffAccess) {
                            if (partner.getSystemUserId() != userDetails.getId()) {
                                partner.setShowName(false);
                            } else {
                                partner.setShowName(true);
                            }
                        } else {
                            partner.setShowName(false);
                        }
                    } else {
                        partner.setShowName(true);
                    }

                    partner.setEncryptedId(encrypted[0]);
                    partner.setEncryptedSecret(encrypted[1]);
                }
            }

            mav.addObject("partners", partners);

            List<submittedsurveysessions> sessions;

            if ("Individual participant".equals(dataTrackedBy)) {
                /* Get a list of submitted participants */
                List<participants> participants = surveymanager.getParticipants(programId, submittedSurveyId);

                if (participants != null && participants.size() > 0) {
                    encryptObject encrypt = new encryptObject();
                    Map<String, String> map;
                    for (participants participant : participants) {
                        //Encrypt the use id to pass in the url
                        map = new HashMap<String, String>();
                        map.put("id", Integer.toString(participant.getId()));
                        map.put("topSecret", topSecret);

                        String[] encrypted = encrypt.encryptObject(map);

                        if (userDetails.getRoleId() != 2) {
                            if (allowStaffAccess) {
                                if (participant.getSystemUserId() != userDetails.getId()) {
                                    participant.setShowName(false);
                                } else {
                                    participant.setShowName(true);
                                }
                            } else {
                                participant.setShowName(false);
                            }
                        } else {
                            participant.setShowName(true);
                        }

                        participant.setEncryptedId(encrypted[0]);
                        participant.setEncryptedSecret(encrypted[1]);
                    }
                }

                //Get available reports for participants
                List<programProfileFields> profileFields = programprofilemanager.getProgramProfileFields(programId,
                        selProgram.getProgramProfileId());
                Integer surveyCustomFieldId = 0;
                if (profileFields != null && profileFields.size() > 0) {
                    for (programProfileFields field : profileFields) {
                        if ("surveys".equals(field.getFieldTag())) {
                            surveyCustomFieldId = field.getCustomfieldId();
                        }
                    }
                }

                if (surveyCustomFieldId > 0) {
                    customProgramFields customFieldDetails = clientmanager
                            .getCustomFieldDetails(surveyCustomFieldId);
                    List<surveys> availSurveys = surveymanager.getProgramProfileSurveys(programId,
                            customFieldDetails, selProgram.getProgramProfileId());

                    if (availSurveys != null && availSurveys.size() > 0) {
                        encryptObject encrypt = new encryptObject();
                        Map<String, String> map;
                        for (surveys survey : availSurveys) {
                            //Encrypt the use id to pass in the url
                            map = new HashMap<String, String>();
                            map.put("id", Integer.toString(survey.getId()));
                            map.put("topSecret", topSecret);

                            String[] encrypted = encrypt.encryptObject(map);

                            survey.setEncryptedId(encrypted[0]);
                            survey.setEncryptedSecret(encrypted[1]);
                        }
                        mav.addObject("availSurveys", availSurveys);
                    }
                }

                mav.addObject("participants", participants);

                sessions = surveymanager.getSubmittedSurveySessions(submittedSurveyId);
            }
            //Population Reached
            else if ("Population reach".equals(dataTrackedBy)) {
                //List<crosswalkData> countyData = clientmanager.getCrosswalkDataByCWName(programId, "County List");
                //mav.addObject("countyData", countyData);

                String selSchoolDistricts = surveymanager.getSubmittedSurveyQuestionAnswerByQuestionTag(
                        submittedSurveyId, submittedSurveyDetails.getSurveyId(), "schoolDistrict");
                mav.addObject("schoolDistricts", selSchoolDistricts);

                sessions = surveymanager.getSubmittedSurveySessionsWithPopulationData(submittedSurveyId);

            }
            //Aggregate
            else {
                sessions = surveymanager.getSubmittedSurveySessions(submittedSurveyId);

                if (sessions != null && sessions.size() > 0) {

                    for (submittedsurveysessions sess : sessions) {

                        List<submittedsurveysessionaggregatedata> aggregateData = surveymanager
                                .getSubmittedSurveySessionAggregateData(sess.getId());

                        if (aggregateData == null || aggregateData.isEmpty()) {
                            sess.setAggregateData(populateNewAggregateDataList(sess.getId()));
                        } else {
                            sess.setAggregateData(aggregateData);
                        }
                    }
                }
            }

            mav.addObject("activityLogSessions", sessions);
            allowNewSession = true;

        }
        mav.addObject("i", i);
        mav.addObject("v", v);
        mav.addObject("j", j);
        mav.addObject("allowNewSession", allowNewSession);

        return mav;

    }

    /**
     * The '/activityLogs/addNewSession.do' POST request will submit a new session for the clicked activity log.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addNewSession.do", method = RequestMethod.POST)
    @ResponseBody
    public Integer addNewSession(HttpSession session, @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v,
            @RequestParam(value = "j", required = false) Integer j,
            @RequestParam(value = "dataTrackedBy", required = false) String dataTrackedBy) throws Exception {

        int submittedSurveyId = 0;

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        if (i != null && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            submittedSurveyId = Integer.parseInt(result[0].substring(4));

            /* Get a list of submitted sessions */
            List<submittedsurveysessions> sessions = surveymanager.getSubmittedSurveySessions(submittedSurveyId);

            /* Get the selected program */
            submittedsurveyprogramprofiles selProgram = surveymanager.getSurveySelectedPrograms(submittedSurveyId,
                    0, 0);

            submittedsurveysessions newSession = new submittedsurveysessions();
            newSession.setSubmittedSurveyId(submittedSurveyId);
            newSession.setSystemUserId(userDetails.getId());
            newSession.setSessionType(dataTrackedBy);
            Integer sessionNum = sessions.size() + 1;
            newSession.setSessionNum(sessionNum);

            if (j != null && j > 0) {
                String CSAPCategory = programprofilemanager.getTableDataByFieldTag(programId, j, "CSAPCategory");
                newSession.setCSAPMainCategory(CSAPCategory);
            }

            surveymanager.saveSurveySession(newSession);
        }

        return 1;
    }

    /**
     * The '/activityLogs/addStaffMemberToSession.do' POST request will submit a new session for the clicked activity log.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addStaffMemberToSession.do", method = RequestMethod.POST)
    @ResponseBody
    public String addStaffMemberToSession(HttpSession session,
            @RequestParam(value = "sessionId", required = false) String sessionIdAsStromg,
            @RequestParam(value = "staffId", required = false) String staffIdAsString) throws Exception {

        Integer sessionId = Integer.parseInt(sessionIdAsStromg);
        Integer staffId = Integer.parseInt(staffIdAsString);

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        String returnMsg = "";

        if (sessionId > 0 && staffId > 0) {
            submittedsurveysessions sessionDetails = surveymanager.getSubmittedSurveySession(sessionId);
            partnerprofile staffDetails = partnerprofilemanager.getPartnerDetails(staffId);

            submittedsurveysessionstaff newEntry = new submittedsurveysessionstaff();
            newEntry.setStaffId(staffId);
            newEntry.setSessionId(sessionId);
            newEntry.setSystemUserId(userDetails.getId());
            surveymanager.saveStaffMemberToSurvey(newEntry);

            returnMsg = sessionDetails.getSessionNum() + "," + staffDetails.getPartnerFirstName() + " "
                    + staffDetails.getPartnerLastName();
        }

        return returnMsg;
    }

    /**
     * The '/activityLogs/removeStaffMemberFromSession.do' POST request will submit a new session for the clicked activity log.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/removeStaffMemberFromSession.do", method = RequestMethod.POST)
    @ResponseBody
    public String removeStaffMemberFromSession(HttpSession session,
            @RequestParam(value = "sessionId", required = false) String sessionIdAsStromg,
            @RequestParam(value = "staffId", required = false) String staffIdAsString) throws Exception {

        Integer sessionId = Integer.parseInt(sessionIdAsStromg);
        Integer staffId = Integer.parseInt(staffIdAsString);

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        String returnMsg = "";

        if (sessionId > 0 && staffId > 0) {
            submittedsurveysessions sessionDetails = surveymanager.getSubmittedSurveySession(sessionId);
            partnerprofile staffDetails = partnerprofilemanager.getPartnerDetails(staffId);

            surveymanager.removeStaffMemberFromSurvey(sessionId, staffId);

            returnMsg = sessionDetails.getSessionNum() + "," + staffDetails.getPartnerFirstName() + " "
                    + staffDetails.getPartnerLastName();
        }

        return returnMsg;
    }

    /**
     * The '/activityLogs/addParticipantToSession.do' POST request will submit a new session for the clicked activity log.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addParticipantToSession.do", method = RequestMethod.POST)
    @ResponseBody
    public String addParticipantToSession(HttpSession session,
            @RequestParam(value = "sessionId", required = false) String sessionIdAsStromg,
            @RequestParam(value = "participantId", required = false) String participantIdAsString)
            throws Exception {

        Integer sessionId = Integer.parseInt(sessionIdAsStromg);
        Integer participantId = Integer.parseInt(participantIdAsString);

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        String returnMsg = "";

        if (sessionId > 0 && participantId > 0) {
            submittedsurveysessions sessionDetails = surveymanager.getSubmittedSurveySession(sessionId);
            participants participantDetails = surveymanager.getParticipant(participantId);

            submittedsurveysessionparticipants newEntry = new submittedsurveysessionparticipants();
            newEntry.setParticipantId(participantId);
            newEntry.setSessionId(sessionId);
            newEntry.setSystemUserId(userDetails.getId());
            surveymanager.saveParticipantToSurvey(newEntry);

            returnMsg = sessionDetails.getSessionNum() + "," + participantDetails.getFirstName() + " "
                    + participantDetails.getLastName();
        }

        return returnMsg;
    }

    /**
     * The '/activityLogs/removeParticipantFromSession.do' POST request will submit a new session for the clicked activity log.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/removeParticipantFromSession.do", method = RequestMethod.POST)
    @ResponseBody
    public String removeParticipantFromSession(HttpSession session,
            @RequestParam(value = "sessionId", required = false) String sessionIdAsStromg,
            @RequestParam(value = "participantId", required = false) String participantIdAsString)
            throws Exception {

        Integer sessionId = Integer.parseInt(sessionIdAsStromg);
        Integer participantId = Integer.parseInt(participantIdAsString);

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        String returnMsg = "";

        if (sessionId > 0 && participantId > 0) {
            submittedsurveysessions sessionDetails = surveymanager.getSubmittedSurveySession(sessionId);
            participants participantDetails = surveymanager.getParticipant(participantId);

            surveymanager.removeParticipantFromSurvey(sessionId, participantId);

            returnMsg = sessionDetails.getSessionNum() + "," + participantDetails.getFirstName() + " "
                    + participantDetails.getLastName();
        }

        return returnMsg;
    }

    /**
     * The '/activityLogs/participantDetails' request will display the list of submitted activity log sessions.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/participantDetails", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView participantDetails(HttpSession session,
            @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v,
            @RequestParam(value = "j", required = false) String j,
            @RequestParam(value = "w", required = false) String w) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/clients/participants/participantDetails");

        participants participantDetails;
        Integer participantId = 0;
        Integer submitedSurveyId = 0;

        if (j != null && w != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(j, w);

            String[] result = obj.toString().split((","));

            submitedSurveyId = Integer.parseInt(result[0].substring(4));
        }

        if (i != null && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            participantId = Integer.parseInt(result[0].substring(4));
        }

        if (participantId == 0) {
            participantDetails = new participants();
        } else {
            participantDetails = surveymanager.getParticipant(participantId);
        }

        //Get a list of states
        USStateList stateList = new USStateList();

        //Get the object that will hold the states
        mav.addObject("stateList", stateList.getStates());
        mav.addObject("submittedSurveyId", submitedSurveyId);

        mav.addObject("participantDetails", participantDetails);

        return mav;
    }

    /**
    * The '/activityLogs/participantDetails' POST request will handle submitting the participant.
    *
    * @param userDetails    The object containing the user form fields
    * @param result          The validation result
    * @param redirectAttr    The variable that will hold values that can be read after the redirect
    *
    * @return   Will send the program admin to the details of the new staff member
        
    * @throws Exception
    */
    @RequestMapping(value = "/activityLogs/participantDetails", method = RequestMethod.POST)
    public @ResponseBody Integer saveParticipantDetails(
            @ModelAttribute(value = "participantDetails") participants participantDetails,
            @RequestParam(value = "submittedSurveyId", required = false) Integer submittedSurveyId,
            BindingResult result, HttpSession session) throws Exception {

        /* Check for duplicate email address 
        User existingUser = usermanager.checkDuplicateUsername(newuserDetails.getUsername(), programId, 0);
            
        if (existingUser != null ) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/users/newUser");
        mav.addObject("existingUser", "The username is already being used by another user.");
        return mav;
        }*/

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        boolean newUser = true;

        if (participantDetails.getId() > 0) {
            newUser = false;
        }

        participantDetails.setSystemUserId(userDetails.getId());
        participantDetails.setProgramId(programId);
        Integer participantId = surveymanager.saveSurveyParticipant(participantDetails);

        if (newUser == false) {
            return 1;
        } else {
            //Save the associated surveyId
            participantSurveyAssoc surveyAssociation = new participantSurveyAssoc();
            surveyAssociation.setParticipantId(participantId);
            surveyAssociation.setSubmittedSurveyId(submittedSurveyId);

            surveymanager.saveSurveyParticipantAssociation(surveyAssociation);
            return 2;
        }
    }

    /**
     * The '/activityLogs/saveSessionDate.do' POST request will handle submitting the session date.
     *
     * @param sessionId    The id of the selected session
     * @param dateSel      The selected date for the session
     *
     * @return   Will send the program admin to the details of the new staff member
         
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/saveSessionDate.do", method = RequestMethod.POST)
    public @ResponseBody Integer saveSessionDate(
            @RequestParam(value = "sessionId", required = false) Integer sessionId,
            @RequestParam(value = "dateSel", required = false) String dateSel, HttpSession session)
            throws Exception {

        submittedsurveysessions sessionDetails = surveymanager.getSubmittedSurveySession(sessionId);
        sessionDetails.setDateOfSession(dateSel);

        surveymanager.saveSurveySession(sessionDetails);

        return 1;

    }

    /**
     * The '/activityLogs/addStaffMemberSessionDirectHours.do' POST request will handle submitting the staff session direct hours.
     *
     * @param sessionId    The id of the selected session
     * @param staffId      The selected staff for the session
     * @param hours        The selected number of hours for the session
     *
     * @return   Will send the program admin to the details of the new staff member
         
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addStaffMemberSessionDirectHours.do", method = RequestMethod.POST)
    public @ResponseBody Integer addStaffMemberSessionDirectHours(
            @RequestParam(value = "sessionId", required = false) Integer sessionId,
            @RequestParam(value = "staffId", required = false) Integer staffId,
            @RequestParam(value = "hours", required = true) String hours, HttpSession session) throws Exception {

        submittedsurveysessionstaff sessionStaffDetails = surveymanager.getSubmittedSurveySessionStaff(sessionId,
                staffId);
        sessionStaffDetails.setDirectStaffTimeHours(hours);

        surveymanager.saveStaffMemberToSurvey(sessionStaffDetails);

        return 1;

    }

    /**
     * The '/activityLogs/addStaffMemberSessionDirectMinutes.do' POST request will handle submitting the staff session direct minutes.
     *
     * @param sessionId    The id of the selected session
     * @param staffId      The selected staff for the session
     * @param minutes        The selected number of minutes for the session
     *
     * @return   Will send the program admin to the details of the new staff member
         
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addStaffMemberSessionDirectMinutes.do", method = RequestMethod.POST)
    public @ResponseBody Integer addStaffMemberSessionDirectMinutes(
            @RequestParam(value = "sessionId", required = false) Integer sessionId,
            @RequestParam(value = "staffId", required = false) Integer staffId,
            @RequestParam(value = "minutes", required = true) String minutes, HttpSession session)
            throws Exception {

        submittedsurveysessionstaff sessionStaffDetails = surveymanager.getSubmittedSurveySessionStaff(sessionId,
                staffId);
        sessionStaffDetails.setDirectStaffTimeMinutes(minutes);

        surveymanager.saveStaffMemberToSurvey(sessionStaffDetails);

        return 1;

    }

    /**
     * The '/activityLogs/addStaffMemberSessionIndirectHours.do' POST request will handle submitting the staff session indirect hours.
     *
     * @param sessionId    The id of the selected session
     * @param staffId      The selected staff for the session
     * @param hours        The selected number of hours for the session
     *
     * @return   Will send the program admin to the details of the new staff member
         
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addStaffMemberSessionIndirectHours.do", method = RequestMethod.POST)
    public @ResponseBody Integer addStaffMemberSessionIndirectHours(
            @RequestParam(value = "sessionId", required = false) Integer sessionId,
            @RequestParam(value = "staffId", required = false) Integer staffId,
            @RequestParam(value = "hours", required = true) String hours, HttpSession session) throws Exception {

        submittedsurveysessionstaff sessionStaffDetails = surveymanager.getSubmittedSurveySessionStaff(sessionId,
                staffId);
        sessionStaffDetails.setIndirectStaffTimeHours(hours);

        surveymanager.saveStaffMemberToSurvey(sessionStaffDetails);

        return 1;

    }

    /**
     * The '/activityLogs/addStaffMemberSessionIndirectMinutes.do' POST request will handle submitting the staff session indirect minutes.
     *
     * @param sessionId    The id of the selected session
     * @param staffId      The selected staff for the session
     * @param minutes      The selected number of minutes for the session
     *
     * @return   Will send the program admin to the details of the new staff member
         
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addStaffMemberSessionIndirectMinutes.do", method = RequestMethod.POST)
    public @ResponseBody Integer addStaffMemberSessionIndirectMinutes(
            @RequestParam(value = "sessionId", required = false) Integer sessionId,
            @RequestParam(value = "staffId", required = false) Integer staffId,
            @RequestParam(value = "minutes", required = true) String minutes, HttpSession session)
            throws Exception {

        submittedsurveysessionstaff sessionStaffDetails = surveymanager.getSubmittedSurveySessionStaff(sessionId,
                staffId);
        sessionStaffDetails.setIndirectStaffTimeMinutes(minutes);

        surveymanager.saveStaffMemberToSurvey(sessionStaffDetails);

        return 1;

    }

    /**
     * The '/activityLogs/sessionDetails' request will display the details of the selected log session.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/sessionDetails", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView sessionDetails(HttpSession session,
            @RequestParam(value = "sessionId", required = false) Integer sessionId) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/clients/participants/sessionDetails");

        submittedsurveysessions sessionDetails = surveymanager.getSubmittedSurveySession(sessionId);

        //Get a list of states
        USStateList stateList = new USStateList();

        //Get the object that will hold the states
        mav.addObject("stateList", stateList.getStates());

        List<crosswalkData> CSAPStrategyData = clientmanager.getCrosswalkDataByCWName(programId,
                "CSAP Strategy Category");
        mav.addObject("CSAPStrategyData", CSAPStrategyData);

        /* Get a list of survey documents */
        List<submittedsurveysessiondocuments> sessionDocuments = surveymanager
                .getSubmittedSessionDocuments(sessionId);

        if (sessionDocuments != null && sessionDocuments.size() > 0) {
            for (submittedsurveysessiondocuments document : sessionDocuments) {
                if (document.getUploadedFile() != null && !"".equals(document.getUploadedFile())) {
                    int index = document.getUploadedFile().lastIndexOf('.');
                    document.setFileExt(document.getUploadedFile().substring(index + 1));

                    if (document.getUploadedFile().length() > 60) {
                        String shortenedTitle = document.getUploadedFile().substring(0, 30) + "..."
                                + document.getUploadedFile().substring(document.getUploadedFile().length() - 10,
                                        document.getUploadedFile().length());
                        document.setShortenedTitle(shortenedTitle);
                    }
                    document.setEncodedTitle(URLEncoder.encode(document.getUploadedFile(), "UTF-8"));
                }
            }
        }

        //if("".equals(sessionDetails.getCSAPMainCategory()) || sessionDetails.getCSAPMainCategory() == null) {
        /* Get the selected program */
        submittedsurveyprogramprofiles selProgram = surveymanager
                .getSurveySelectedPrograms(sessionDetails.getSubmittedSurveyId(), 0, 0);
        if (selProgram.getProgramProfileId() > 0) {
            String CSAPCategory = programprofilemanager.getTableDataByFieldTag(programId,
                    selProgram.getProgramProfileId(), "CSAPCategory");
            sessionDetails.setCSAPMainCategory(CSAPCategory);
        }
        // }

        mav.addObject("sessionDocuments", sessionDocuments);

        mav.addObject("sessionDetails", sessionDetails);

        return mav;
    }

    /**
     * The '/activityLogs/sessionDetails' POST request will handle submitting the session details.
     *
     * @param sessionDetails    The object containing the session form fields
     * @param result          The validation result
     * @param redirectAttr    The variable that will hold values that can be read after the redirect
     *
     * @return   Will send the program admin to the details of the new staff member
         
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/sessionDetails", method = RequestMethod.POST)
    public @ResponseBody Integer savesessionDetails(
            @ModelAttribute(value = "sessionDetails") submittedsurveysessions sessionDetails,
            @RequestParam(value = "sessionDocuments", required = false) List<MultipartFile> sessionDocuments,
            BindingResult result, HttpSession session) throws Exception {

        surveymanager.saveSurveySession(sessionDetails);

        if (sessionDocuments != null) {

            /* Get a list of completed surveys the logged in user has access to */
            User userDetails = (User) session.getAttribute("userDetails");

            for (MultipartFile uploadedFile : sessionDocuments) {

                submittedsurveysessiondocuments sessionDocument = new submittedsurveysessiondocuments();
                sessionDocument.setSystemUserId(userDetails.getId());
                sessionDocument.setSubmittedSurveyId(sessionDetails.getId());

                surveymanager.saveSurveySessionDocument(sessionDocument, uploadedFile, programId);
            }
        }

        return sessionDetails.getSessionNum();
    }

    /**
     * The 'getActivityLogs.do' GET request will return a list of available activity logs that have saved participants.
     * 
     * @param i The encrypted userId
     * @param v The encrypted secret
     * @param programId The clicked program
     * @return  This function will return the program department model
     * @throws Exception 
     */
    @RequestMapping(value = "/activityLogs/getActivityLogs.do", method = RequestMethod.GET)
    public @ResponseBody ModelAndView getActivityLogs(@RequestParam String i, @RequestParam String v,
            @RequestParam String j, HttpSession session) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/clients/participants/pullParticipants");

        if (i != null && v != null) {

            mav.addObject("activityLogId", i);
            mav.addObject("v", v);
            mav.addObject("j", j);

            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            Integer submittedSurveyId = Integer.parseInt(result[0].substring(4));

            /* Get a list of completed surveys the logged in user has access to */
            User userDetails = (User) session.getAttribute("userDetails");

            List<submittedSurveys> activityLogs = new ArrayList<submittedSurveys>();

            List<submittedSurveys> submittedSurveys = surveymanager.getActivityLogsForSessionData(userDetails,
                    programId);

            if (submittedSurveys != null && submittedSurveys.size() > 0) {
                encryptObject encrypt = new encryptObject();
                Map<String, String> map;
                for (submittedSurveys submittedSurvey : submittedSurveys) {
                    boolean addSubmittedSurvey = false;
                    if (submittedSurvey.getSelectedProgramIds() != null
                            && !"".equals(submittedSurvey.getSelectedProgramIds())) {

                        String submittedSurveyAnswer = surveymanager.getSubmittedSurveyQuestionAnswerByQuestionTag(
                                submittedSurvey.getId(), submittedSurvey.getSurveyId(), "aggregateTracking");

                        if (submittedSurveyAnswer != null && !"".equals(submittedSurveyAnswer)) {
                            if ("Individual participant".equals(submittedSurveyAnswer)
                                    && submittedSurvey.getTotalParticipants().compareTo(BigInteger.ZERO) > 0) {
                                addSubmittedSurvey = true;
                            }
                        }
                    }

                    if (addSubmittedSurvey == true) {
                        //Encrypt the use id to pass in the url
                        map = new HashMap<String, String>();
                        map.put("id", Integer.toString(submittedSurvey.getId()));
                        map.put("topSecret", topSecret);

                        String[] encrypted = encrypt.encryptObject(map);

                        submittedSurvey.setEncryptedId(encrypted[0]);
                        submittedSurvey.setEncryptedSecret(encrypted[1]);
                        activityLogs.add(submittedSurvey);
                    }
                }
            }
            mav.addObject("activityLogs", activityLogs);
        }

        return mav;
    }

    /**
     * The 'getActivityLogParticipants.do' POST request will return a list of available activity logs that have saved participants.
     * 
     * @param i The encrypted userId
     * @param v The encrypted secret
     * @param programId The clicked program
     * @return  This function will return the program department model
     * @throws Exception 
     */
    @RequestMapping(value = "/activityLogs/getActivityLogParticipants.do", method = RequestMethod.POST)
    public @ResponseBody ModelAndView getActivityLogParticipants(@RequestParam String i, @RequestParam String v,
            @RequestParam String j, @RequestParam List<Integer> selectedActivityLogs, HttpSession session)
            throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/clients/participants/participantList");

        if (i != null && v != null) {

            mav.addObject("activityLogId", i);
            mav.addObject("v", v);
            mav.addObject("j", j);

            List<participants> participants = surveymanager.getParticipants(programId, selectedActivityLogs);

            mav.addObject("participants", participants);
        }

        return mav;
    }

    /**
     * The 'loadActivityLogParticipants.do' POST request will return a list of available activity logs that have saved participants.
     * 
     * @param i The encrypted userId
     * @param v The encrypted secret
     * @param programId The clicked program
     * @return  This function will return the program department model
     * @throws Exception 
     */
    @RequestMapping(value = "/activityLogs/loadActivityLogParticipants.do", method = RequestMethod.POST)
    public @ResponseBody ModelAndView loadActivityLogParticipants(@RequestParam String i, @RequestParam String v,
            @RequestParam List<Integer> selectedParticipants, HttpSession session) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/clients/participants/participantList");

        if (i != null && v != null && selectedParticipants.size() > 0) {

            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            Integer submittedSurveyId = Integer.parseInt(result[0].substring(4));

            for (Integer participant : selectedParticipants) {
                participantSurveyAssoc surveyAssociation = new participantSurveyAssoc();
                surveyAssociation.setParticipantId(participant);
                surveyAssociation.setSubmittedSurveyId(submittedSurveyId);
                surveymanager.saveSurveyParticipantAssociation(surveyAssociation);
            }

            mav.addObject("completed", 1);
        }

        return mav;
    }

    /**
     * The '/activityLogs/addSessionTotalAggregateParticipants.do' POST request will handle submitting the total number of participants
     * in aggregate data.
     *
     * @param sessionId    The id of the selected session
     * @param totalInGroup The total number of participants in a session (Aggregate)
     * @param minutes      The selected number of minutes for the session
     *
     * @return   Will send the program admin to the details of the new staff member
         
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addSessionTotalAggregateParticipants.do", method = RequestMethod.POST)
    public @ResponseBody Integer addSessionTotalAggregateParticipants(
            @RequestParam(value = "sessionId", required = false) Integer sessionId,
            @RequestParam(value = "totalInGroup", required = true) String totalInGroup, HttpSession session)
            throws Exception {

        submittedsurveysessions sessionDetails = surveymanager.getSubmittedSurveySession(sessionId);
        sessionDetails.setTotalInGroup(Integer.parseInt(totalInGroup));
        surveymanager.saveSurveySession(sessionDetails);

        return 1;

    }

    /**
     * The '/activityLogs/addSessionTotalReached.do' POST request will handle submitting the staff session indirect minutes.
     *
     * @param sessionId    The id of the selected session
     * @param staffId      The selected staff for the session
     * @param minutes      The selected number of minutes for the session
     *
     * @return   Will send the program admin to the details of the new staff member
         
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addSessionTotalReached.do", method = RequestMethod.POST)
    public @ResponseBody Integer addSessionTotalReached(
            @RequestParam(value = "sessionId", required = false) Integer sessionId,
            @RequestParam(value = "totalReached", required = true) String totalReached, HttpSession session)
            throws Exception {

        submittedsurveysessionpopulationreacheddata sessionPopReachedData = surveymanager
                .getSubmittedSurveySessionPopulationData(sessionId);

        if (sessionPopReachedData == null) {
            submittedsurveysessionpopulationreacheddata newSessionPopReachedData = new submittedsurveysessionpopulationreacheddata();
            newSessionPopReachedData.setSessionId(sessionId);
            newSessionPopReachedData.setTotalReached(Integer.parseInt(totalReached.replace(",", "")));
            surveymanager.saveSessionPopData(newSessionPopReachedData);
        } else {
            sessionPopReachedData.setTotalReached(Integer.parseInt(totalReached.replace(",", "")));
            surveymanager.updateSessionPopData(sessionPopReachedData);
        }

        return 1;

    }

    /**
     * The '/activityLogs/addSessionCountyReached.do' POST request will handle submitting the staff session indirect minutes.
     *
     * @param sessionId    The id of the selected session
     * @param staffId      The selected staff for the session
     * @param minutes      The selected number of minutes for the session
     *
     * @return   Will send the program admin to the details of the new staff member
         
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addSessionCountyReached.do", method = RequestMethod.POST)
    public @ResponseBody Integer addSessionCountyReached(
            @RequestParam(value = "sessionId", required = false) Integer sessionId,
            @RequestParam(value = "countiesSelected", required = true) List<String> countiesSelected,
            HttpSession session) throws Exception {

        submittedsurveysessionpopulationreacheddata sessionPopReachedData = surveymanager
                .getSubmittedSurveySessionPopulationData(sessionId);

        if (sessionPopReachedData == null) {
            submittedsurveysessionpopulationreacheddata newSessionPopReachedData = new submittedsurveysessionpopulationreacheddata();
            newSessionPopReachedData.setSessionId(sessionId);
            newSessionPopReachedData.setCountyReached(String.join(", ", countiesSelected).replace(", ", ","));
            surveymanager.saveSessionPopData(newSessionPopReachedData);
        } else {
            sessionPopReachedData.setCountyReached(String.join(", ", countiesSelected).replace(", ", ","));
            surveymanager.updateSessionPopData(sessionPopReachedData);
        }

        return 1;

    }

    @RequestMapping(value = "/activityLogs/saveSessionAggregateData", method = RequestMethod.POST)
    public @ResponseBody Integer saveSessionAggregateData(
            @ModelAttribute(value = "submittedsurveysessions") submittedsurveysessions submittedsurveysessions,
            BindingResult result, HttpSession session) throws Exception {

        if (submittedsurveysessions.getAggregateData() != null
                && submittedsurveysessions.getAggregateData().size() > 0) {
            //Remove existing session aggregate Data
            surveymanager.removeSurveySessionAggregateData(
                    submittedsurveysessions.getAggregateData().get(0).getSessionId());
            for (submittedsurveysessionaggregatedata aggregateData : submittedsurveysessions.getAggregateData()) {
                if ("null".equals(aggregateData.getTotalCount()) || "".equals(aggregateData.getTotalCount())) {
                    aggregateData.setTotalCount(0);
                }
                surveymanager.saveSurveySessionAggregateData(aggregateData);
            }
        }

        return 1;
    }

    private List<submittedsurveysessionaggregatedata> populateNewAggregateDataList(Integer sessionId) {

        List<submittedsurveysessionaggregatedata> aggregateDataList = new ArrayList<submittedsurveysessionaggregatedata>();

        submittedsurveysessionaggregatedata newAggregateData;

        //Age Breakdown
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("0-4");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("5-11");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("12-14");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("15-17");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("18-20");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("21-24");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("25-44");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("45-64");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("65 and over");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*AgeBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Age Not Known");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        //Gender
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_genders");
        newAggregateData.setRowId(1);
        newAggregateData.setDisplayName("Male");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_genders");
        newAggregateData.setRowId(2);
        newAggregateData.setDisplayName("Female");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_genders");
        newAggregateData.setRowId(4);
        newAggregateData.setDisplayName("Unkown/Refused to State");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        //Race
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(3);
        newAggregateData.setDisplayName("American Indian/Alaskan Native");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(19);
        newAggregateData.setDisplayName("Asian - Asian Indian");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(20);
        newAggregateData.setDisplayName("Asian - Chinese");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(21);
        newAggregateData.setDisplayName("Asian - Filipino");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(22);
        newAggregateData.setDisplayName("Asian - Japanese");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(23);
        newAggregateData.setDisplayName("Asian - Korean");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(24);
        newAggregateData.setDisplayName("Asian - Vietnamese");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(25);
        newAggregateData.setDisplayName("Asian - Other");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(2);
        newAggregateData.setDisplayName("Black");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(26);
        newAggregateData.setDisplayName("Native Hawaiian/Other Pacific Islander - Guamanian or Chamorro");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(27);
        newAggregateData.setDisplayName("Native Hawaiian/Other Pacific Islander - Samoan");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(28);
        newAggregateData.setDisplayName("Native Hawaiian/Other Pacific Islander - Other");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(1);
        newAggregateData.setDisplayName("White");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(29);
        newAggregateData.setDisplayName("Two or more races (Multiracial)");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_races");
        newAggregateData.setRowId(30);
        newAggregateData.setDisplayName("Other Race");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        //Hispanic data
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_hispanics");
        newAggregateData.setRowId(45);
        newAggregateData.setDisplayName("Not Hispanic, Latino(a) or Spanish");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_hispanics");
        newAggregateData.setRowId(46);
        newAggregateData.setDisplayName("Mexican, Mexican American, Chicano");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_hispanics");
        newAggregateData.setRowId(42);
        newAggregateData.setDisplayName("Puerto Rican");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_hispanics");
        newAggregateData.setRowId(43);
        newAggregateData.setDisplayName("Cuban");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_hispanics");
        newAggregateData.setRowId(47);
        newAggregateData.setDisplayName("Other Hispanic, Latino or Spanish Origin");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_hispanics");
        newAggregateData.setRowId(48);
        newAggregateData.setDisplayName("Hispanic ethnicity unknown");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        //Transgender data
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_transgender");
        newAggregateData.setRowId(1);
        newAggregateData.setDisplayName("Transgendered");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_transgender");
        newAggregateData.setRowId(2);
        newAggregateData.setDisplayName("Not transgendered");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_transgender");
        newAggregateData.setRowId(3);
        newAggregateData.setDisplayName("Unknown");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        //Sexual Orientation data
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_sexualorientation");
        newAggregateData.setRowId(1);
        newAggregateData.setDisplayName("Straight");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_sexualorientation");
        newAggregateData.setRowId(2);
        newAggregateData.setDisplayName("Gay/Lesbian");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_sexualorientation");
        newAggregateData.setRowId(3);
        newAggregateData.setDisplayName("Bisexual");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_sexualorientation");
        newAggregateData.setRowId(5);
        newAggregateData.setDisplayName("Questioning");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_sexualorientation");
        newAggregateData.setRowId(6);
        newAggregateData.setDisplayName("Queer");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_sexualorientation");
        newAggregateData.setRowId(7);
        newAggregateData.setDisplayName("Gender Neutral");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_sexualorientation");
        newAggregateData.setRowId(8);
        newAggregateData.setDisplayName("Two-spirit");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_sexualorientation");
        newAggregateData.setRowId(9);
        newAggregateData.setDisplayName("Choose not to identify");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        //Laugage spoken data
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_languages");
        newAggregateData.setRowId(485);
        newAggregateData.setDisplayName("English");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_languages");
        newAggregateData.setRowId(486);
        newAggregateData.setDisplayName("Spanish");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_languages");
        newAggregateData.setRowId(503);
        newAggregateData.setDisplayName("Other");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("lu_languages");
        newAggregateData.setRowId(504);
        newAggregateData.setDisplayName("Unknown");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        //How well speaks english data
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*HowWell");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Very well");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*HowWell");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Well");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*HowWell");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Not well");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*HowWell");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Not at all");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*HowWell");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Unknown");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        //Family economic data
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*FamilyEconomic");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Appear to be living in poverty");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*FamilyEconomic");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Do not appear to be living in poverty");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*FamilyEconomic");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Unknown financial circumstances");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        //Military Service data
        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*MilitaryBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Currently serve in the Armed Forces");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*MilitaryBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Currently serve in the Reserves");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*MilitaryBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Currently serve in the National Guard");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*MilitaryBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName(
                "Served in the past, but do not currently serve in the Armed Forces, Reserves, or National Guard");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*MilitaryBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Never served in the Armed Forces, Reserves, or National Guard");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        newAggregateData = new submittedsurveysessionaggregatedata();
        newAggregateData.setSessionId(sessionId);
        newAggregateData.setTableName("*MilitaryBreakdown");
        newAggregateData.setRowId(0);
        newAggregateData.setDisplayName("Military status unknown");
        newAggregateData.setTotalCount(0);
        aggregateDataList.add(newAggregateData);

        return aggregateDataList;
    }

    /**
     * The '/activityLogs/participantPastSurveys' request will display the list of submitted session surveys for the passed
     * in participant.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/participantPastSurveys", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView participantPastSurveys(HttpSession session,
            @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v,
            @RequestParam(value = "sessionId", required = false) Integer sessionId) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/clients/participants/showPastSurveys");

        participants participantDetails;
        Integer participantId = 0;

        if (i != null && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

            Object obj = decrypt.decryptObject(i, v);

            String[] result = obj.toString().split((","));

            participantId = Integer.parseInt(result[0].substring(4));
        }

        if (participantId == 0) {
            participantDetails = new participants();
        } else {
            participantDetails = surveymanager.getParticipant(participantId);
        }

        if (sessionId > 0 && participantId > 0) {
            List<submittedsurveyforsessionparticipant> participantSessionSurveys = surveymanager
                    .getParticipantSessionSurveys(sessionId, participantId);
            if (participantSessionSurveys != null && participantSessionSurveys.size() > 0) {
                encryptObject encrypt = new encryptObject();
                Map<String, String> map;

                for (submittedsurveyforsessionparticipant survey : participantSessionSurveys) {
                    //Encrypt the use id to pass in the url
                    map = new HashMap<String, String>();
                    map.put("id", Integer.toString(survey.getSubmittedSurveyId()));
                    map.put("topSecret", topSecret);

                    String[] encrypted = encrypt.encryptObject(map);

                    survey.setEncryptedId(encrypted[0]);
                    survey.setEncryptedSecret(encrypted[1]);
                }
            }

            mav.addObject("participantSessionSurveys", participantSessionSurveys);
        }

        mav.addObject("participantDetails", participantDetails);

        return mav;
    }

    /**
     * The 'deleteSessionDocument' POST request will remove the clicked uploaded
     * document.
     *
     * @param documentId The id of the clicked document.
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deleteSessionDocument.do", method = RequestMethod.POST)
    public @ResponseBody Integer deleteDocument(
            @RequestParam(value = "documentId", required = true) Integer documentId) throws Exception {

        submittedsurveysessiondocuments documentDetails = surveymanager.getSessionDocumentById(documentId);
        documentDetails.setStatus(false);
        surveymanager.saveSurveySessionDocument(documentDetails, null, programId);
        return 1;
    }

    /**
     * The 'deleteSession' POST request will remove the selected session
     * document.
     *
     * @param sessionId The id of the clicked session.
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deleteSession.do", method = RequestMethod.POST)
    public @ResponseBody Integer deleteSession(
            @RequestParam(value = "sessionId", required = true) Integer sessionId,
            @RequestParam(value = "submittedSurveyId", required = true) Integer submittedSurveyId)
            throws Exception {
        surveymanager.deleteSession(sessionId, submittedSurveyId);
        return 1;
    }

    /**
     * The '/activityLogs/addPartnerToSession.do' POST request will submit a new session for the clicked activity log.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/addPartnerToSession.do", method = RequestMethod.POST)
    @ResponseBody
    public String addPartnerToSession(HttpSession session,
            @RequestParam(value = "sessionId", required = false) String sessionIdAsStromg,
            @RequestParam(value = "partnerId", required = false) String partnerIdAsString) throws Exception {

        Integer sessionId = Integer.parseInt(sessionIdAsStromg);
        Integer partnerId = Integer.parseInt(partnerIdAsString);

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        String returnMsg = "";

        if (sessionId > 0 && partnerId > 0) {
            submittedsurveysessions sessionDetails = surveymanager.getSubmittedSurveySession(sessionId);
            partnerprofile partnerDetails = partnerprofilemanager.getPartnerDetails(partnerId);

            submittedsurveysessionpartners newEntry = new submittedsurveysessionpartners();
            newEntry.setPartnerProfileId(partnerId);
            newEntry.setSessionId(sessionId);
            newEntry.setSystemUserId(userDetails.getId());
            surveymanager.savePartnerToSurvey(newEntry);

            if (!"".equals(partnerDetails.getPartnerFirstName())) {
                returnMsg = "Partner " + partnerDetails.getPartnerFirstName() + " "
                        + partnerDetails.getPartnerLastName();
            } else if (!"".equals(partnerDetails.getOrganizationName())) {
                returnMsg = "Partner " + partnerDetails.getOrganizationName();
            } else {
                returnMsg = "The selected partner";
            }

        }

        return returnMsg;
    }

    /**
     * The '/activityLogs/removePartnerFromSession.do' POST request will submit a new session for the clicked activity log.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "/activityLogs/removePartnerFromSession.do", method = RequestMethod.POST)
    @ResponseBody
    public String removePartnerFromSession(HttpSession session,
            @RequestParam(value = "sessionId", required = false) String sessionIdAsStromg,
            @RequestParam(value = "partnerId", required = false) String partnerIdAsString) throws Exception {

        Integer sessionId = Integer.parseInt(sessionIdAsStromg);
        Integer partnerId = Integer.parseInt(partnerIdAsString);

        /* Get a list of completed surveys the logged in user has access to */
        User userDetails = (User) session.getAttribute("userDetails");

        String returnMsg = "";

        if (sessionId > 0 && partnerId > 0) {
            submittedsurveysessions sessionDetails = surveymanager.getSubmittedSurveySession(sessionId);
            partnerprofile partnerDetails = partnerprofilemanager.getPartnerDetails(partnerId);

            surveymanager.removePartnerFromSurvey(sessionId, partnerId);

            if (!"".equals(partnerDetails.getPartnerFirstName())) {
                returnMsg = "Partner " + partnerDetails.getPartnerFirstName() + " "
                        + partnerDetails.getPartnerLastName();
            } else if (!"".equals(partnerDetails.getOrganizationName())) {
                returnMsg = "Partner " + partnerDetails.getOrganizationName();
            } else {
                returnMsg = "The selected partner";
            }
        }

        return returnMsg;
    }

}