com.rr.wabshs.ui.surveys.surveyController.java Source code

Java tutorial

Introduction

Here is the source code for com.rr.wabshs.ui.surveys.surveyController.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.surveys;

import com.registryKit.client.clientManager;
import com.registryKit.client.engagementManager;
import com.registryKit.client.multipleFieldsFromTable;
import com.registryKit.document.document;
import com.registryKit.document.documentFolder;
import com.registryKit.document.documentManager;
import com.registryKit.hierarchy.hierarchyManager;
import com.registryKit.hierarchy.programHierarchyDetails;
import com.registryKit.partnerProfile.partnerProfileManager;
import com.registryKit.partnerProfile.partnerprofile;
import com.registryKit.programProfile.programProfileManager;
import com.registryKit.programProfile.programprofile;
import com.registryKit.survey.SurveyPages;
import com.registryKit.survey.SurveyQuestionChoices;
import com.registryKit.survey.SurveyQuestions;
import com.registryKit.survey.submittedSurveyDocuments;
import com.registryKit.survey.submittedSurveys;
import com.registryKit.survey.submittedsurveycoordinators;
import com.registryKit.survey.submittedsurveyforsessionparticipant;
import com.registryKit.survey.submittedsurveyprogramprofiles;
import com.registryKit.survey.survey;
import com.registryKit.survey.surveyManager;
import com.registryKit.survey.surveyQuestionAnswers;
import com.registryKit.survey.surveys;
import com.registryKit.user.User;
import com.registryKit.user.userManager;
import com.registryKit.user.userProgramModules;
import com.rr.wabshs.ui.hierarchy.secondTierEntities;
import com.rr.wabshs.ui.hierarchy.thirdTierEntities;
import com.rr.wabshs.ui.security.decryptObject;
import com.rr.wabshs.ui.security.encryptObject;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringEscapeUtils;
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.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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author chadmccue
 */
@Controller
@RequestMapping("/surveys")
public class surveyController {

    private static Integer moduleId = 11;

    @Autowired
    private clientManager clientmanager;

    @Autowired
    private surveyManager surveyManager;

    @Autowired
    private engagementManager engagementmanager;

    @Autowired
    private hierarchyManager hierarchymanager;

    @Autowired
    private programProfileManager programprofilemanager;

    @Autowired
    private documentManager documentmanager;

    @Autowired
    private userManager usermanager;

    @Autowired
    private partnerProfileManager partnerprofilemanager;

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

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

    private static List<surveys> surveys;

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

    /**
     * The '' request will display the list of taken surveys.
     *
     * @param request
     * @param response
     * @return   the administrator dashboard view
     * @throws Exception
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView listSubmittedSurveys(@RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v, HttpSession session) throws Exception {

        int year = 114;
        int month = 0;
        int day = 1;
        Date originalDate = new Date(year, month, day);

        Date fromDate = getMonthDate("START");
        Date toDate = getMonthDate("END");

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

        mav.addObject("fromDate", fromDate);
        mav.addObject("toDate", toDate);
        mav.addObject("originalDate", originalDate);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateFrom = df.format(fromDate);
        String dateTo = df.format(toDate);

        /* Get a list of surveys  */
        List<surveys> surveyList = surveyManager.getProgramSurveys(programId);

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

        for (surveys survey : surveyList) {
            //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]);

        }
        surveys = surveyList;
        mav.addObject("surveys", surveyList);

        Integer surveyId;

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

        /* Get the submitted surveys for the selected survey type */
        if (!"".equals(i) && i != null && !"".equals(v) && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

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

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

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

            if (surveyId > 0) {
                mav.addObject("selSurvey", surveyId);
                surveys surveyDetails = surveyManager.getSurveyDetails(surveyId);

                if (surveyDetails != null) {
                    mav.addObject("surveyName", surveyDetails.getTitle());
                    mav.addObject("surveyTag", surveyDetails.getSurveyTag());
                }
            }

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

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

        } else {
            if (surveyList.size() > 0) {
                surveyId = surveyList.get(0).getId();
            } else {
                surveyId = 0;
            }

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

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

            mav = new ModelAndView(new RedirectView("/surveys?i=" + encrypted[0] + "&v=" + encrypted[1]));
        }

        return mav;
    }

    /**
     * 
     * @param fromDate
     * @param toDate
     * @param i
     * @param v
     * @param session
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/getSubmittedSurveys.do", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView getSubmittedSurveys(@RequestParam Date fromDate, @RequestParam Date toDate,
            @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v, HttpSession session) throws Exception {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateFrom = df.format(fromDate);
        String dateTo = df.format(toDate);

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/survey/submittedSurveys");

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

        Integer surveyId = 0;

        /* Get the submitted surveys for the selected survey type */
        if (!"".equals(i) && i != null && !"".equals(v) && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

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

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

            surveyId = 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<String> summaryColumns = new ArrayList<String>();

        if (surveyId > 0) {
            surveys surveyDetails = surveyManager.getSurveyDetails(surveyId);

            if (surveyDetails != null) {

                String customTable = "";

                if ("Coordinator Hours".equals(surveyDetails.getSurveyTag())) {
                    customTable = "submittedsurveycoordinators";
                } else if ("CPWI".equals(surveyDetails.getSurveyTag())) {
                    customTable = "submittedsurveyprogramprofiles";
                } else if ("ActivityReporting".equals(surveyDetails.getSurveyTag())) {
                    customTable = "submittedsurveyprogramprofiles";
                }

                List<submittedSurveys> submittedSurveys = surveyManager.getEntitySurveys(userDetails, surveyId,
                        dateFrom, dateTo, customTable);

                /* Need to get the selected entities */
                if (submittedSurveys != null && !submittedSurveys.isEmpty()) {

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

                    for (submittedSurveys survey : submittedSurveys) {

                        //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("submittedSurveys", submittedSurveys);

                mav.addObject("surveyName", surveyDetails.getTitle());

                if ("Coordinator Hours".equals(surveyDetails.getSurveyTag())) {
                    summaryColumns.add("Entity");
                    summaryColumns.add("Coordinator Name");
                    List<String> surveySummaryColumns = surveyManager.getSurveySummaryColumns(programId, surveyId);
                    if (surveySummaryColumns != null && surveySummaryColumns.size() > 0) {
                        for (String col : surveySummaryColumns) {
                            summaryColumns.add(col);
                        }
                    }
                } else if ("CPWI".equals(surveyDetails.getSurveyTag())) {
                    summaryColumns.add("Entity");
                    summaryColumns.add("Program");
                    List<String> surveySummaryColumns = surveyManager.getSurveySummaryColumns(programId, surveyId);
                    if (surveySummaryColumns != null && surveySummaryColumns.size() > 0) {
                        for (String col : surveySummaryColumns) {
                            summaryColumns.add(col);
                        }
                    }
                } else if ("TribalAnnualReport".equals(surveyDetails.getSurveyTag())) {
                    summaryColumns.add("Entity");
                    List<String> surveySummaryColumns = surveyManager.getSurveySummaryColumns(programId, surveyId);
                    if (surveySummaryColumns != null && surveySummaryColumns.size() > 0) {
                        for (String col : surveySummaryColumns) {
                            summaryColumns.add(col);
                        }
                    }
                } else if ("ActivityReporting".equals(surveyDetails.getSurveyTag())) {
                    summaryColumns.add("Entity");
                    summaryColumns.add("Program");
                    List<String> surveySummaryColumns = surveyManager.getSurveySummaryColumns(programId, surveyId);
                    if (surveySummaryColumns != null && surveySummaryColumns.size() > 0) {
                        for (String col : surveySummaryColumns) {
                            summaryColumns.add(col);
                        }
                    }
                }

            }

        }

        /** Check to see if this program has access to the document module **/
        boolean hasDocumentModule = false;
        String[][] availablePrograms = (String[][]) session.getAttribute("availModules");

        for (int p = 0; p < availablePrograms.length; p++) {
            if (Integer.parseInt(availablePrograms[p][3]) == 10) {
                hasDocumentModule = true;
            }
        }

        mav.addObject("summaryColumns", summaryColumns);
        mav.addObject("hasDocumentModule", hasDocumentModule);

        return mav;

    }

    /**
     * The '/startSurvey' GET request will build out the survey and display the first page of the survey.
     *
     * @param i The encrypted client id
     * @param v The encrypted decryption key
     * @param s The id of the selected survey
     *
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/startSurvey", method = RequestMethod.POST)
    public ModelAndView startSurvey(@RequestParam(value = "s", required = false) String s,
            @RequestParam(value = "i", required = false) String i,
            @RequestParam(value = "v", required = false) String v,
            @RequestParam(value = "selectedEntities", required = false) List<Integer> selectedEntities,
            HttpSession session) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/takeSurvey");
        mav.addObject("surveys", surveys);

        //Set the survey answer array to get ready to hold data
        if (session.getAttribute("questionAnswers") != null) {
            session.removeAttribute("questionAnswers");
        }
        session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>());

        if (session.getAttribute("selectedProgramProfiles") != null) {
            session.removeAttribute("selectedProgramProfiles");
        }
        session.setAttribute("selectedProgramProfiles", new ArrayList<surveyProgramProfiles>());

        if (session.getAttribute("secondTierEntities") != null) {
            session.removeAttribute("secondTierEntities");
        }
        session.setAttribute("secondTierEntities", new ArrayList<secondTierEntities>());

        if (session.getAttribute("seenPages") != null) {
            session.removeAttribute("seenPages");
        }
        session.setAttribute("seenPages", new ArrayList<Integer>());

        if (session.getAttribute("selectedExtras") != null) {
            session.removeAttribute("selectedExtras");
        }
        session.setAttribute("selectedExtras", new ArrayList<surveyExtraInformation>());

        int clientId = 0;
        int surveyId = 0;

        /* Get the submitted surveys for the selected survey type */
        if (!"".equals(i) && i != null && !"".equals(v) && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

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

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

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

        } else {
            surveyId = Integer.parseInt(s);
        }

        if (surveyId > 0) {

            surveys surveyDetails = surveyManager.getSurveyDetails(surveyId);
            mav.addObject("surveyTag", surveyDetails.getSurveyTag());

            /* Make sure the survey is part of this program and active */
            if (surveyDetails.getProgramId() != programId || surveyDetails.getStatus() == false) {

                /* Redirect back to the survey list page */
            } /* Set up the survey */ else {
                survey survey = new survey();
                survey.setClientId(clientId);
                survey.setSurveyId(surveyId);
                survey.setSurveyTitle(surveyDetails.getTitle());
                survey.setPrevButton(surveyDetails.getPrevButtonText());
                survey.setNextButton(surveyDetails.getNextButtonText());
                survey.setSaveButton(surveyDetails.getDoneButtonText());
                survey.setSubmittedSurveyId(0);

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

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

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

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

                mav.addObject("surveyURL", "?i=" + encrypted[0] + "&v=" + encrypted[1]);

                /* Get the pages */
                List<SurveyPages> surveyPages = surveyManager.getSurveyPages(surveyId, false, 0, 0, 0, 0);
                SurveyPages currentPage = surveyManager.getSurveyPage(surveyId, true, 1, clientId, 0, 0, 0, 0, 0);
                survey.setPageTitle(currentPage.getPageTitle());
                survey.setSurveyPageQuestions(currentPage.getSurveyQuestions());
                survey.setTotalPages(surveyPages.size());
                survey.setPageId(currentPage.getId());
                survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId());

                mav.addObject("survey", survey);
                mav.addObject("surveyPages", surveyPages);

                if (surveyDetails.isAssociateToProgram()) {
                    mav.addObject("showPrograms", true);
                } else {
                    mav.addObject("showPrograms", false);
                }
            }
        } else {
            /* Redirect back to the survey list page */

        }

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

        /* Get a list of available tier 3 for the selected tier 2's */
        if (selectedEntities != null && !selectedEntities.isEmpty() && !"".equals(selectedEntities)) {

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

            List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session
                    .getAttribute("secondTierEntities");

            for (Integer entity : selectedEntities) {

                List<thirdTierEntities> tier3EntityList = new ArrayList<thirdTierEntities>();

                secondTierEntities secondTierEntity = new secondTierEntities();
                secondTierEntity.setId(entity);

                programHierarchyDetails secondTierEntityDetails = hierarchymanager
                        .getProgramHierarchyItemDetails(entity);
                secondTierEntity.setName(secondTierEntityDetails.getName());

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

                List tier3Entities = hierarchymanager.getActiveProgramOrgHierarchyItems(programId, 3, entity,
                        userId);

                if (!tier3Entities.isEmpty() && tier3Entities.size() > 0) {

                    for (ListIterator iter = tier3Entities.listIterator(); iter.hasNext();) {

                        Object[] row = (Object[]) iter.next();

                        thirdTierEntities thirdTierEntity = new thirdTierEntities();
                        thirdTierEntity.setId(Integer.parseInt(row[0].toString()));
                        thirdTierEntity.setName(row[1].toString());

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

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

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

                        tier3EntityList.add(thirdTierEntity);

                    }

                    secondTierEntity.setTier3EntityList(tier3EntityList);

                }

                tier2EntityList.add(secondTierEntity);

            }

            mav.addObject("seltier2EntityList", tier2EntityList);

        }

        mav.addObject("selSurvey", surveyId);
        mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", ""));
        mav.addObject("currentPage", 1);
        mav.addObject("currPageNum", 1);

        mav.addObject("qNum", 0);
        mav.addObject("disabled", false);

        return mav;
    }

    /**
     * The '/editSurvey' GET request will build out the survey and display the first page of the survey.
     *
     * @param i The encrypted survey id
     * @param v The encrypted decryption key
     *
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = { "/editSurvey", "/viewSurvey" }, method = RequestMethod.GET)
    public ModelAndView editSurvey(@RequestParam String i, @RequestParam String v, HttpSession session,
            HttpServletRequest request, @RequestParam(value = "sessionId", required = false) Integer sessionId)
            throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/takeSurvey");
        mav.addObject("surveys", surveys);

        //Set the survey answer array to get ready to hold data
        if (session.getAttribute("questionAnswers") != null) {
            session.removeAttribute("questionAnswers");
        }
        session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>());

        if (session.getAttribute("selectedProgramProfiles") != null) {
            session.removeAttribute("selectedProgramProfiles");
        }
        session.setAttribute("selectedProgramProfiles", new ArrayList<surveyProgramProfiles>());

        if (session.getAttribute("secondTierEntities") != null) {
            session.removeAttribute("secondTierEntities");
        }
        session.setAttribute("secondTierEntities", new ArrayList<secondTierEntities>());

        if (session.getAttribute("seenPages") != null) {
            session.removeAttribute("seenPages");
        }
        session.setAttribute("seenPages", new ArrayList<Integer>());

        if (session.getAttribute("selectedExtras") != null) {
            session.removeAttribute("selectedExtras");
        }
        session.setAttribute("selectedExtras", new ArrayList<surveyExtraInformation>());

        int clientId = 0;

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

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

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

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

        /* Get the survey details */
        submittedSurveys submittedSurveyDetails = surveyManager.getSubmittedSurvey(submittedSurveyId);

        surveys surveyDetails = surveyManager.getSurveyDetails(submittedSurveyDetails.getSurveyId());
        mav.addObject("surveyTag", surveyDetails.getSurveyTag());
        if (surveyDetails.isAssociateToProgram()) {
            mav.addObject("showPrograms", true);
        } else {
            mav.addObject("showPrograms", false);
        }

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

        survey survey = new survey();
        survey.setClientId(clientId);
        survey.setSurveyId(submittedSurveyDetails.getSurveyId());
        survey.setSurveyTitle(surveyDetails.getTitle());
        survey.setPrevButton(surveyDetails.getPrevButtonText());
        survey.setNextButton(surveyDetails.getNextButtonText());
        survey.setSaveButton(surveyDetails.getDoneButtonText());
        survey.setSubmittedSurveyId(submittedSurveyId);
        survey.setEntityIds(surveyManager.getSubmittedSurveyEntities(submittedSurveyId, userDetails));

        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(submittedSurveyDetails.getSurveyId()));
        map.put("topSecret", topSecret);

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

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

        mav.addObject("surveyURL", "?i=" + encrypted[0] + "&v=" + encrypted[1]);

        /* Get the pages */
        List<SurveyPages> surveyPages = surveyManager.getSurveyPages(submittedSurveyDetails.getSurveyId(), false, 0,
                0, 0, 0);
        SurveyPages currentPage = surveyManager.getSurveyPage(submittedSurveyDetails.getSurveyId(), true, 1,
                clientId, 0, 0, submittedSurveyId, 0, 0);
        survey.setPageTitle(currentPage.getPageTitle());
        survey.setSurveyPageQuestions(currentPage.getSurveyQuestions());
        survey.setTotalPages(surveyPages.size());
        survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId());
        survey.setPageId(currentPage.getId());

        /* Need to update any date functions */
        if (survey.getSurveyPageQuestions() != null && survey.getSurveyPageQuestions().size() > 0) {
            for (SurveyQuestions question : survey.getSurveyPageQuestions()) {
                if (question.getAnswerTypeId() == 6) {
                    if (question.getQuestionValue().length() > 0
                            && !question.getQuestionValue().contains("^^^^^")) {
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        SimpleDateFormat df2 = new SimpleDateFormat("M/dd/yy");
                        SimpleDateFormat df3 = new SimpleDateFormat("M/dd/yyyy");
                        SimpleDateFormat df4 = new SimpleDateFormat("M/d/yy");
                        SimpleDateFormat df5 = new SimpleDateFormat("M/d/yyyy");
                        SimpleDateFormat df6 = new SimpleDateFormat("MM/d/yyyy");
                        SimpleDateFormat df7 = new SimpleDateFormat("MM/d/yy");
                        SimpleDateFormat df8 = new SimpleDateFormat("MM/dd/yyyy");
                        SimpleDateFormat df9 = new SimpleDateFormat("MM/dd/yy");

                        Date formattedDate;
                        try {
                            formattedDate = df.parse(question.getQuestionValue());
                        } catch (Exception ex) {
                            try {
                                formattedDate = df2.parse(question.getQuestionValue());
                            } catch (Exception ex2) {
                                try {
                                    formattedDate = df3.parse(question.getQuestionValue());
                                } catch (Exception ex3) {
                                    try {
                                        formattedDate = df4.parse(question.getQuestionValue());
                                    } catch (Exception ex4) {
                                        try {
                                            formattedDate = df5.parse(question.getQuestionValue());
                                        } catch (Exception ex5) {
                                            try {
                                                formattedDate = df6.parse(question.getQuestionValue());
                                            } catch (Exception ex6) {
                                                try {
                                                    formattedDate = df7.parse(question.getQuestionValue());
                                                } catch (Exception ex7) {
                                                    try {
                                                        formattedDate = df8.parse(question.getQuestionValue());
                                                    } catch (Exception ex8) {
                                                        formattedDate = df9.parse(question.getQuestionValue());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (question.getDateFormatType() == 2) { //dd/mm/yyyy
                            df.applyPattern("dd/MM/yyyy");
                        } else { //mm/dd/yyyy
                            df.applyPattern("MM/dd/yyyy");
                        }
                        String formattedDateasString = df.format(formattedDate);
                        question.setQuestionValue(formattedDateasString);
                    }
                }
            }
        }

        if (sessionId != null && sessionId > 0) {
            survey.setSessionId(sessionId);
        }

        mav.addObject("survey", survey);
        mav.addObject("surveyPages", surveyPages);

        List<Integer> selectedEntities = surveyManager.getSurveyEntities(submittedSurveyId);

        /* Get a list of available schools for the selected districts */
        if (selectedEntities != null && !selectedEntities.isEmpty() && !"".equals(selectedEntities)) {

            List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session
                    .getAttribute("secondTierEntities");

            for (Integer entityId : selectedEntities) {

                List<thirdTierEntities> tier3EntityList = new ArrayList<thirdTierEntities>();

                secondTierEntities secondTierEntity = new secondTierEntities();
                secondTierEntity.setId(entityId);

                programHierarchyDetails secondTierEntityDetails = hierarchymanager
                        .getProgramHierarchyItemDetails(entityId);
                secondTierEntity.setName(secondTierEntityDetails.getName());

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

                List tier3Entities = hierarchymanager.getProgramOrgHierarchyItems(programId, 3, entityId, userId);

                if (!tier3Entities.isEmpty() && tier3Entities.size() > 0) {

                    for (ListIterator iter = tier3Entities.listIterator(); iter.hasNext();) {

                        Object[] row = (Object[]) iter.next();

                        thirdTierEntities thirdTierEntity = new thirdTierEntities();
                        thirdTierEntity.setId(Integer.parseInt(row[0].toString()));
                        thirdTierEntity.setName(row[1].toString());

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

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

                        thirdTierEntity.setEncryptedId(encrypted2[0]);
                        thirdTierEntity.setEncryptedSecret(encrypted2[1]);

                        tier3EntityList.add(thirdTierEntity);

                    }

                    secondTierEntity.setTier3EntityList(tier3EntityList);

                }

                tier2EntityList.add(secondTierEntity);

            }

            mav.addObject("seltier2EntityList", tier2EntityList);

        }

        mav.addObject("selSurvey", submittedSurveyDetails.getSurveyId());
        mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", ""));

        mav.addObject("qNum", 0);
        mav.addObject("currPageNum", 1);

        boolean disabled = false;
        if ("/surveys/viewSurvey".equals(request.getServletPath())) {
            disabled = true;
        }

        mav.addObject("disabled", disabled);

        return mav;
    }

    /**
     * The '/takeSurvey' POST request will submit the survey page.
     *
     * @param survey
     * @param session
     * @param redirectAttr
     * @param action
     * @param goToPage
     * @param disabled
     * @param entityIds
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/submitSurvey", method = RequestMethod.POST)
    public ModelAndView saveSurveyPage(@ModelAttribute(value = "survey") survey survey, HttpSession session,
            RedirectAttributes redirectAttr, @RequestParam String action, @RequestParam Integer goToPage,
            @RequestParam(value = "entityIds", required = false) List<String> entityIds,
            @RequestParam(value = "selectedEntities", required = false) List<String> selectedEntities,
            @RequestParam(value = "disabled", required = true, defaultValue = "false") boolean disabled,
            @RequestParam(value = "currPageNum", required = true) int currPageNum,
            @RequestParam(value = "showPrograms", required = false) boolean showPrograms,
            @RequestParam(value = "SurveyURL", required = true) String SurveyURL) throws Exception {

        Integer goToQuestion = 0;
        boolean skipToEnd = false;
        boolean submitted = false;

        ModelAndView mav = new ModelAndView();
        mav.addObject("showPrograms", showPrograms);
        mav.addObject("surveyURL", SurveyURL);

        List<Integer> entityIdList = null;
        if (entityIds != null && !"".equals(entityIds) && !entityIds.isEmpty()) {
            entityIdList = new ArrayList<Integer>();

            for (String entityId : entityIds) {
                Integer entityIdasInt = Integer.parseInt(entityId);

                entityIdList.add(entityIdasInt);
            }
            survey.setEntityIds(entityIdList);
        }

        Integer lastQuestionSavedId = 0;
        Integer lastPageSaved = 0;

        if ("next".equals(action) || "done".equals(action) || "save".equals(action)) {
            goToPage = 0;
            Integer lastQuestionSaved = 0;
            List<SurveyQuestions> questions = survey.getSurveyPageQuestions();

            List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                    .getAttribute("questionAnswers");

            for (SurveyQuestions question : questions) {

                boolean questionFound = false;

                List<surveyQuestionAnswers> toRemove = new ArrayList<surveyQuestionAnswers>();

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

                    Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                    while (it.hasNext()) {
                        surveyQuestionAnswers questionAnswer = it.next();

                        if ((questionAnswer.getPageNum() > currPageNum)) {
                            questionAnswer.setSaveToDB(false);
                        }

                        if (questionAnswer.getQuestionId() == question.getId()) {

                            if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                                    && question.getQuestionValue().contains(",")) {
                                toRemove.add(questionAnswer);
                            } else {
                                questionFound = true;

                                boolean isInteger = isQuestionValueNumeric(question.getQuestionValue());

                                if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                                        && isInteger == true) {
                                    SurveyQuestionChoices choiceDetails = surveyManager
                                            .getSurveyQuestionChoice(Integer.parseInt(question.getQuestionValue()));

                                    if (choiceDetails == null) {
                                        questionAnswer.setAnswerText(question.getQuestionValue());
                                    } else {
                                        if (choiceDetails.getChoiceValue() > 0) {
                                            questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                                        } /*else {
                                          questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                                          }*/
                                        questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                                        if (choiceDetails.isSkipToEnd() == true) {
                                            skipToEnd = true;
                                            submitted = true;
                                            lastPageSaved = question.getSurveyPageId();
                                        } else {
                                            if (choiceDetails.getSkipToPageId() > 0) {
                                                SurveyPages pageDetails = surveyManager
                                                        .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                                goToPage = pageDetails.getPageNum();
                                            }

                                            goToQuestion = choiceDetails.getSkipToQuestionId();

                                            lastQuestionSavedId = question.getId();
                                        }

                                        questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                                    }

                                } else {
                                    questionAnswer.setAnswerText(question.getQuestionValue());
                                }

                                questionAnswer.setQuestionId(question.getId());
                                questionAnswer.setProgramPatientId(survey.getClientId());
                                questionAnswer.setProgramEngagementId(survey.getEngagementId());
                                questionAnswer.setqNum(question.getQuestionNum());
                                questionAnswer.setSurveyPageId(question.getSurveyPageId());
                                questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                                questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                                questionAnswer.setSaveToDB(true);
                                questionAnswer.setPageNum(currPageNum);
                            }
                        }
                    }
                }
                if (!toRemove.isEmpty()) {
                    questionAnswers.removeAll(toRemove);
                }

                if (questionFound == false) {

                    if ((question.getAnswerTypeId() == 1 || question.getAnswerTypeId() == 2)
                            && !"".equals(question.getQuestionValue())) {
                        if (question.getQuestionValue().contains(",")) {
                            String[] lineVector = question.getQuestionValue().split(",");
                            boolean answerAdded = true;
                            for (int i = 0; i < lineVector.length; i++) {
                                surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                                boolean isInteger = isQuestionValueNumeric(lineVector[i]);

                                if (isInteger) {
                                    Integer qAnsValue = Integer.parseInt(lineVector[i]);

                                    SurveyQuestionChoices choiceDetails = surveyManager
                                            .getSurveyQuestionChoice(qAnsValue);

                                    if (choiceDetails == null) {
                                        answerAdded = false;
                                        break;
                                    }

                                    if (choiceDetails.getChoiceValue() > 0) {
                                        questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                                    } /*else {
                                      questionAnswer.setAnswerText(choiceDetails.getChoiceText());
                                      }*/
                                    questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                                    if (choiceDetails.isSkipToEnd() == true) {
                                        skipToEnd = true;
                                        submitted = true;
                                        lastPageSaved = question.getSurveyPageId();
                                    } else {
                                        if (choiceDetails.getSkipToPageId() > 0) {
                                            SurveyPages pageDetails = surveyManager
                                                    .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                            goToPage = pageDetails.getPageNum();
                                        }

                                        goToQuestion = choiceDetails.getSkipToQuestionId();

                                        lastQuestionSavedId = question.getId();
                                    }
                                    questionAnswer.setQuestionId(question.getId());
                                    questionAnswer.setProgramPatientId(survey.getClientId());
                                    questionAnswer.setProgramEngagementId(survey.getEngagementId());
                                    questionAnswer.setqNum(question.getQuestionNum());
                                    questionAnswer.setSurveyPageId(question.getSurveyPageId());
                                    questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                                    questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                                    questionAnswer.setSaveToDB(true);
                                    questionAnswer.setPageNum(currPageNum);

                                    questionAnswers.add(questionAnswer);

                                    if (i == 0) {
                                        questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                                    }
                                } else {
                                    answerAdded = false;
                                    break;
                                }
                            }

                            if (!answerAdded) {
                                surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                                questionAnswer.setAnswerText(question.getQuestionValue());

                                questionAnswer.setQuestionId(question.getId());
                                questionAnswer.setProgramPatientId(survey.getClientId());
                                questionAnswer.setProgramEngagementId(survey.getEngagementId());
                                questionAnswer.setqNum(question.getQuestionNum());
                                questionAnswer.setSurveyPageId(question.getSurveyPageId());
                                questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                                questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                                questionAnswer.setSaveToDB(true);
                                questionAnswer.setPageNum(currPageNum);

                                questionAnswers.add(questionAnswer);
                            }

                        } else {

                            surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                            boolean isInteger = isQuestionValueNumeric(question.getQuestionValue());

                            if (isInteger) {
                                SurveyQuestionChoices choiceDetails = surveyManager
                                        .getSurveyQuestionChoice(Integer.parseInt(question.getQuestionValue()));

                                if (choiceDetails != null) {
                                    if (choiceDetails.getChoiceValue() > 0) {
                                        questionAnswer.setAnswerId(choiceDetails.getChoiceValue());
                                    }
                                    questionAnswer.setAnswerText(choiceDetails.getChoiceText());

                                    if (choiceDetails.isSkipToEnd() == true) {
                                        skipToEnd = true;
                                        submitted = true;
                                        lastPageSaved = question.getSurveyPageId();
                                    } else {
                                        if (choiceDetails.getSkipToPageId() > 0) {
                                            SurveyPages pageDetails = surveyManager
                                                    .getSurveyPageDetails(choiceDetails.getSkipToPageId());
                                            goToPage = pageDetails.getPageNum();
                                        }

                                        goToQuestion = choiceDetails.getSkipToQuestionId();

                                        lastQuestionSavedId = question.getId();
                                    }
                                } else {
                                    questionAnswer.setAnswerText(question.getQuestionValue());
                                }

                            } else {
                                questionAnswer.setAnswerText(question.getQuestionValue());
                            }

                            questionAnswer.setAnswerOther(question.getQuestionOtherValue());
                            questionAnswer.setQuestionId(question.getId());
                            questionAnswer.setProgramPatientId(survey.getClientId());
                            questionAnswer.setProgramEngagementId(survey.getEngagementId());
                            questionAnswer.setqNum(question.getQuestionNum());
                            questionAnswer.setSurveyPageId(question.getSurveyPageId());
                            questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                            questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                            questionAnswer.setSaveToDB(true);
                            questionAnswer.setPageNum(currPageNum);

                            questionAnswers.add(questionAnswer);
                        }

                    } else {
                        surveyQuestionAnswers questionAnswer = new surveyQuestionAnswers();

                        questionAnswer.setAnswerText(question.getQuestionValue());

                        questionAnswer.setQuestionId(question.getId());
                        questionAnswer.setProgramPatientId(survey.getClientId());
                        questionAnswer.setProgramEngagementId(survey.getEngagementId());
                        questionAnswer.setqNum(question.getQuestionNum());
                        questionAnswer.setSurveyPageId(question.getSurveyPageId());
                        questionAnswer.setSaveToFieldId(question.getSaveToFieldId());
                        questionAnswer.setRelatedQuestionId(question.getRelatedQuestionId());
                        questionAnswer.setSaveToDB(true);
                        questionAnswer.setPageNum(currPageNum);

                        questionAnswers.add(questionAnswer);
                    }

                }

                lastQuestionSaved = question.getQuestionNum();
            }

            /* Remove questions passed the last question answered */
            List<surveyQuestionAnswers> updatedquestionAnswers = (List<surveyQuestionAnswers>) session
                    .getAttribute("questionAnswers");
            Iterator<surveyQuestionAnswers> itr = updatedquestionAnswers.iterator();

            while (itr.hasNext()) {
                surveyQuestionAnswers questionAnswer = itr.next();

                if (questionAnswer.getqNum() > lastQuestionSaved) {
                    itr.remove();
                }
            }

        }

        survey NextPage = new survey();
        NextPage.setClientId(survey.getClientId());
        NextPage.setSurveyId(survey.getSurveyId());
        NextPage.setSurveyTitle(survey.getSurveyTitle());
        NextPage.setPrevButton(survey.getPrevButton());
        NextPage.setNextButton(survey.getNextButton());
        NextPage.setSaveButton(survey.getSaveButton());
        NextPage.setSubmittedSurveyId(survey.getSubmittedSurveyId());
        NextPage.setEntityIds(survey.getEntityIds());

        SurveyPages currentPage = null;
        Integer qNum = 1;
        Integer nextPage = 1;

        /* Get the pages */
        Integer selEntityId = 0;
        if (entityIdList != null) {
            if (entityIdList.size() > 0) {
                selEntityId = entityIdList.get(0);
            }
        }
        List<SurveyPages> surveyPages = surveyManager.getSurveyPages(survey.getSurveyId(), false, 0, 0, 0,
                selEntityId);

        if ("prev".equals(action)) {
            mav.setViewName("/takeSurvey");

            currPageNum--;
            mav.addObject("currPageNum", currPageNum);

            List<Integer> seenPages = (List<Integer>) session.getAttribute("seenPages");

            nextPage = seenPages.get(seenPages.size() - 1);
            /* Remove this page from array */
            seenPages.remove(seenPages.size() - 1);

            currentPage = surveyManager.getSurveyPage(survey.getSurveyId(), true, nextPage, survey.getClientId(), 0,
                    goToQuestion, survey.getSubmittedSurveyId(), lastQuestionSavedId, selEntityId);

            Integer totalPageQuestions = 0;

            List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                    .getAttribute("questionAnswers");

            for (SurveyQuestions question : currentPage.getSurveyQuestions()) {
                question.setQuestionValue("");
                if (questionAnswers != null && questionAnswers.size() > 0) {

                    Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                    while (it.hasNext()) {
                        surveyQuestionAnswers questionAnswer = it.next();

                        if (questionAnswer.getQuestionId() == question.getId()) {
                            if (question.getMultipleFieldsFromTable() != null
                                    && question.getMultipleFieldsFromTable().size() > 0) {
                                if (questionAnswer.getAnswerText().contains(",")) {
                                    List<String> multiFieldValue = Arrays
                                            .asList(questionAnswer.getAnswerText().split(","));

                                    for (multipleFieldsFromTable multipleField : question
                                            .getMultipleFieldsFromTable()) {
                                        if (multiFieldValue != null && multiFieldValue.size() > 0) {
                                            for (int i = 0; i < multiFieldValue.size(); i++) {
                                                if (multiFieldValue.get(i).contains("-")) {
                                                    List<String> value = Arrays
                                                            .asList(multiFieldValue.get(i).split("-"));
                                                    if (multipleField.getDisplayId() == Integer
                                                            .parseInt(value.get(0))) {
                                                        multipleField.setDisplayValue(value.get(1));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else if ("".equals(question.getQuestionValue())) {
                                question.setQuestionValue(questionAnswer.getAnswerText());
                                if (!"".equals(questionAnswer.getAnswerOther())) {
                                    question.setQuestionOtherValue(questionAnswer.getAnswerOther());
                                }
                            } else {
                                String currValue = question.getQuestionValue();
                                currValue += ",";
                                currValue += questionAnswer.getAnswerText();
                                question.setQuestionValue(currValue);
                            }
                        }
                    }
                }

                if (question.getAnswerTypeId() != 7) {
                    totalPageQuestions += 1;
                }
            }

            surveys surveyDetails = surveyManager.getSurveyDetails(survey.getSurveyId());
            mav.addObject("surveyTag", surveyDetails.getSurveyTag());

            qNum = (survey.getLastQNumAnswered() - totalPageQuestions) - 1;
        } else if ("next".equals(action)) {
            mav.setViewName("/takeSurvey");

            currPageNum++;
            mav.addObject("currPageNum", currPageNum);

            if (goToPage > 0) {
                nextPage = goToPage;
            } else {

                /* Check to see if page has any skip logic */
                SurveyPages currentPageDetails = surveyManager.getSurveyPageDetails(survey.getPageId());
                if (currentPageDetails.getSkipToPage() > 0) {
                    SurveyPages skiptoPageDetails = surveyManager
                            .getSurveyPageDetails(currentPageDetails.getSkipToPage());
                    nextPage = skiptoPageDetails.getPageNum();
                } else if (currentPageDetails.getSkipToPage() == -1) {
                    skipToEnd = true;
                    submitted = true;
                } else {
                    nextPage = survey.getCurrentPage() + 1;
                }
            }

            List<Integer> seenPages = (List<Integer>) session.getAttribute("seenPages");
            seenPages.add(survey.getCurrentPage());

            currentPage = surveyManager.getSurveyPage(survey.getSurveyId(), true, nextPage, survey.getClientId(), 0,
                    goToQuestion, survey.getSubmittedSurveyId(), lastQuestionSavedId, selEntityId);

            List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                    .getAttribute("questionAnswers");

            for (SurveyQuestions question : currentPage.getSurveyQuestions()) {
                String currDBValue = question.getQuestionValue();
                String currDBOtherValue = question.getQuestionOtherValue();
                question.setQuestionValue("");
                question.setQuestionOtherValue("");
                if (questionAnswers != null && questionAnswers.size() > 0) {

                    Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

                    while (it.hasNext()) {
                        surveyQuestionAnswers questionAnswer = it.next();

                        if (questionAnswer.getQuestionId() == question.getId()) {
                            if ("".equals(question.getQuestionValue())) {
                                question.setQuestionValue(questionAnswer.getAnswerText());
                                if (!"".equals(questionAnswer.getAnswerOther())) {
                                    question.setQuestionOtherValue(questionAnswer.getAnswerOther());
                                }
                            } else {
                                String currValue = question.getQuestionValue();
                                currValue += ",";
                                currValue += questionAnswer.getAnswerText();
                                question.setQuestionValue(currValue);
                            }
                        }
                    }
                }

                if ("".equals(question.getQuestionValue())) {
                    question.setQuestionValue(currDBValue);
                    if (!"".equals(question.getQuestionOtherValue())) {
                        question.setQuestionOtherValue(currDBOtherValue);
                    }
                }
            }

            qNum = survey.getLastQNumAnswered();

            surveys surveyDetails = surveyManager.getSurveyDetails(survey.getSurveyId());
            mav.addObject("surveyTag", surveyDetails.getSurveyTag());

        } else if ("save".equals(action)) {
            submitted = false;
        } else if ("done".equals(action)) {
            skipToEnd = true;
            submitted = true;
        }

        /**
         * If saving the survey, save and redirect to the survey list page *
         */
        if ("save".equals(action)) {
            User userDetails = (User) session.getAttribute("userDetails");

            /**
             * Submit answers to DB *
             */
            List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                    .getAttribute("questionAnswers");
            Integer submittedSurveyId = surveyManager.submitSurvey(userDetails.getId(), programId, survey,
                    questionAnswers, submitted, selectedEntities);

            if (session.getAttribute("selectedProgramProfiles") != null) {
                List<surveyProgramProfiles> selectedProgramProfile = (List<surveyProgramProfiles>) session
                        .getAttribute("selectedProgramProfiles");

                Iterator<surveyProgramProfiles> it = selectedProgramProfile.iterator();

                /* Delete existing code sets */
                surveyManager.deleteSurveyPrograms(submittedSurveyId);

                while (it.hasNext()) {

                    surveyProgramProfiles criteria = it.next();

                    if (criteria.isChecked()) {
                        submittedsurveyprogramprofiles savedProgramProfile = new submittedsurveyprogramprofiles();
                        savedProgramProfile.setProgramProfileId(criteria.getProgramProfileId());
                        savedProgramProfile.setEntityId(criteria.getEntityId());
                        savedProgramProfile.setSubmittedSurveyId(submittedSurveyId);

                        surveyManager.submitSurveyPrograms(savedProgramProfile);
                    }
                }
            }

            if (session.getAttribute("selectedExtras") != null) {
                List<surveyExtraInformation> selectedExtraInformation = (List<surveyExtraInformation>) session
                        .getAttribute("selectedExtras");

                Iterator<surveyExtraInformation> it = selectedExtraInformation.iterator();

                /* Delete existing code sets */
                surveyManager.deleteSurveyCoordinators(submittedSurveyId);

                while (it.hasNext()) {

                    surveyExtraInformation criteria = it.next();

                    if (criteria.isChecked()) {
                        submittedsurveycoordinators savedCoordinator = new submittedsurveycoordinators();
                        savedCoordinator.setPartnerProfileId(criteria.getExtraId());
                        savedCoordinator.setEntityId(criteria.getEntityId());
                        savedCoordinator.setSubmittedSurveyId(submittedSurveyId);

                        surveyManager.submitSurveyCoordinators(savedCoordinator);
                    }
                }
            }

            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(survey.getSurveyId()));
            map.put("topSecret", topSecret);

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

            mav = new ModelAndView(new RedirectView("/surveys?i=" + encrypted[0] + "&v=" + encrypted[1]));
        } /**
          * If reached the last page or an option was selected to skip to the end *
          */
        else if (currentPage == null || skipToEnd == true) {

            if (disabled == false) {
                User userDetails = (User) session.getAttribute("userDetails");

                /* If skipToEnd == true && submitted == true we need to remove any questions that 
                appear after the last saved page
                */
                if (skipToEnd == true && submitted == true && lastPageSaved > 0
                        && survey.getSubmittedSurveyId() > 0) {
                    surveyManager.removeOldAnswers(survey.getSubmittedSurveyId(), lastPageSaved);
                }

                /**
                 * Submit answers to DB *
                 */
                List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                        .getAttribute("questionAnswers");
                Integer submittedSurveyId = surveyManager.submitSurvey(userDetails.getId(), programId, survey,
                        questionAnswers, submitted, selectedEntities);

                if (session.getAttribute("selectedProgramProfiles") != null) {
                    List<surveyProgramProfiles> selectedProgramProfile = (List<surveyProgramProfiles>) session
                            .getAttribute("selectedProgramProfiles");

                    Iterator<surveyProgramProfiles> it = selectedProgramProfile.iterator();

                    /* Delete existing code sets */
                    surveyManager.deleteSurveyPrograms(submittedSurveyId);

                    while (it.hasNext()) {

                        surveyProgramProfiles criteria = it.next();

                        if (criteria.isChecked()) {
                            submittedsurveyprogramprofiles savedProgramProfile = new submittedsurveyprogramprofiles();

                            savedProgramProfile.setProgramProfileId(criteria.getProgramProfileId());
                            savedProgramProfile.setEntityId(criteria.getEntityId());
                            savedProgramProfile.setSubmittedSurveyId(submittedSurveyId);

                            surveyManager.submitSurveyPrograms(savedProgramProfile);
                        }
                    }
                }

                if (session.getAttribute("selectedExtras") != null) {
                    List<surveyExtraInformation> selectedExtraInformation = (List<surveyExtraInformation>) session
                            .getAttribute("selectedExtras");

                    Iterator<surveyExtraInformation> it = selectedExtraInformation.iterator();

                    /* Delete existing code sets */
                    surveyManager.deleteSurveyCoordinators(submittedSurveyId);

                    while (it.hasNext()) {

                        surveyExtraInformation criteria = it.next();

                        if (criteria.isChecked()) {
                            submittedsurveycoordinators savedCoordinator = new submittedsurveycoordinators();
                            savedCoordinator.setPartnerProfileId(criteria.getExtraId());
                            savedCoordinator.setEntityId(criteria.getEntityId());
                            savedCoordinator.setSubmittedSurveyId(submittedSurveyId);

                            surveyManager.submitSurveyCoordinators(savedCoordinator);
                        }
                    }
                }

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

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

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

                String[] encrypted = encrypt.encryptObject(map1);
                String[] encrypted2 = encrypt.encryptObject(map2);

                /** Check to see if this program has access to the document && client module **/
                boolean hasDocumentModule = false;
                boolean hasClientModule = false;
                String[][] availablePrograms = (String[][]) session.getAttribute("availModules");

                for (int p = 0; p < availablePrograms.length; p++) {
                    if (Integer.parseInt(availablePrograms[p][3]) == 10) {
                        hasDocumentModule = true;
                    }
                    if (Integer.parseInt(availablePrograms[p][3]) == 1) {
                        hasClientModule = true;
                    }
                }

                mav.addObject("hasDocumentModule", hasDocumentModule);
                mav.addObject("hasClientModule", hasClientModule);

                /* Find out if activity log needs to be tracked at the client level */
                List<surveyProgramProfiles> selectedProgramProfile = (List<surveyProgramProfiles>) session
                        .getAttribute("selectedProgramProfiles");
                surveys surveyDetails = surveyManager.getSurveyDetails(survey.getSurveyId());

                if (showPrograms && selectedProgramProfile != null && selectedProgramProfile.size() > 0) {
                    if ("ActivityReporting".equals(surveyDetails.getSurveyTag())) {
                        mav.addObject("trackIndividuals", true);
                        mav.addObject("programProfileId", selectedProgramProfile.get(0).getProgramProfileId());
                    }
                }

                mav.setViewName("/completedSurvey");
                mav.addObject("surveyDetails", surveyDetails);

                List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session
                        .getAttribute("secondTierEntities");
                mav.addObject("seltier2EntityList", tier2EntityList);
                mav.addObject("surveys", surveys);
                mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", ""));

                mav.addObject("i", encrypted[0]);
                mav.addObject("v", encrypted[1]);
                mav.addObject("i2", encrypted2[0]);
                mav.addObject("v2", encrypted2[1]);

                mav.addObject("submittedSurveyId", submittedSurveyId);

                /* Get a list of survey documents */
                List<submittedSurveyDocuments> surveyDocuments = surveyManager
                        .getSubmittedSurveyDocuments(submittedSurveyId);

                if (surveyDocuments != null && surveyDocuments.size() > 0) {
                    for (submittedSurveyDocuments document : surveyDocuments) {
                        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"));

                        }
                    }
                }

                mav.addObject("surveyDocuments", surveyDocuments);

                /* Check to see if this survey is tied to a participant and session */
                if (survey.getClientId() > 0 && survey.getSessionId() > 0) {
                    submittedsurveyforsessionparticipant surveySessionParticipantEntry = new submittedsurveyforsessionparticipant();
                    surveySessionParticipantEntry.setSubmittedSurveyId(submittedSurveyId);
                    surveySessionParticipantEntry.setParticipantId(survey.getClientId());
                    surveySessionParticipantEntry.setSessionId(survey.getSessionId());
                    surveySessionParticipantEntry.setSystemUserId(userDetails.getId());

                    surveyManager.saveSurveyForSessionParticipant(surveySessionParticipantEntry);

                    mav.addObject("participantSessionSurvey", true);
                } else if (survey.getSessionId() > 0) {
                    mav.addObject("participantSessionSurvey", true);
                }

            } else {

            }

        } else {

            NextPage.setPageTitle(currentPage.getPageTitle());
            NextPage.setSurveyPageQuestions(currentPage.getSurveyQuestions());
            NextPage.setPageId(currentPage.getId());

            /* Loop through to get actually question answers */

            List<surveyQuestionAnswers> questionAnswers = (List<surveyQuestionAnswers>) session
                    .getAttribute("questionAnswers");
            Iterator<surveyQuestionAnswers> it = questionAnswers.iterator();

            for (SurveyQuestions question : currentPage.getSurveyQuestions()) {

                String questionValue = "";

                while (it.hasNext()) {
                    surveyQuestionAnswers questionAnswer = it.next();

                    if (questionAnswer.getQuestionId() == question.getId()) {

                        if (questionAnswer != null) {
                            if (questionAnswer.getAnswerId() > 0) {
                                questionValue += String.valueOf(questionAnswer.getAnswerId());
                            } else {
                                questionValue += questionAnswer.getAnswerText();
                            }

                            questionValue += ",";
                        }
                    }
                }

                if (!"".equals(questionValue)) {
                    question.setQuestionValue(StringEscapeUtils.escapeHtml3(questionValue.replaceAll("(,)*$", "")));
                }
            }

            NextPage.setTotalPages(surveyPages.size());
            NextPage.setCurrentPage(nextPage);
            NextPage.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId());

            mav.addObject("survey", NextPage);
            mav.addObject("surveyPages", surveyPages);
            mav.addObject("selectedEntities", selectedEntities);
            List<secondTierEntities> tier2EntityList = (List<secondTierEntities>) session
                    .getAttribute("secondTierEntities");
            mav.addObject("seltier2EntityList", tier2EntityList);
            mav.addObject("qNum", qNum);
            mav.addObject("surveys", surveys);
            mav.addObject("disabled", disabled);
            mav.addObject("selSurvey", survey.getSurveyId());
        }

        return mav;
    }

    /**
     * The 'getEntityPrograms' GET request will get all the program profiles for the selected entity.
     *
     * @param entityId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getEntityPrograms", method = RequestMethod.GET)
    public @ResponseBody ModelAndView getEntityPrograms(
            @RequestParam(value = "entityId", required = true) List<Integer> entityIdList,
            @RequestParam(value = "surveyId", required = true) Integer surveyId,
            @RequestParam(value = "disabled", required = true) Boolean disabled, HttpSession session)
            throws Exception {

        List<surveyProgramProfiles> selectedProgramProfile = (List<surveyProgramProfiles>) session
                .getAttribute("selectedProgramProfiles");

        if (selectedProgramProfile != null) {

            Iterator<surveyProgramProfiles> it = selectedProgramProfile.iterator();

            List<surveyProgramProfiles> toRemove = new ArrayList<surveyProgramProfiles>();

            while (it.hasNext()) {

                surveyProgramProfiles criteria = it.next();

                if (!Objects.equals(criteria.getEntityId(), entityIdList.get(0))) {
                    toRemove.add(criteria);
                }
            }

            if (toRemove != null && !toRemove.isEmpty()) {
                selectedProgramProfile.removeAll(toRemove);
            }
        }

        for (Integer entityId : entityIdList) {
            programHierarchyDetails entityDetails = hierarchymanager.getProgramHierarchyItemDetails(entityId);

            /* Get the associated program profiles for the passed in entity */
            List<Integer> programProfiles = programprofilemanager.getProgramProfilesForEntity(entityId);

            if (programProfiles != null && !programProfiles.isEmpty()) {

                for (Integer programProfile : programProfiles) {
                    boolean programProfileFound = false;

                    if (selectedProgramProfile != null) {
                        Iterator<surveyProgramProfiles> it = selectedProgramProfile.iterator();

                        while (it.hasNext()) {

                            surveyProgramProfiles criteria = it.next();

                            if (Objects.equals(criteria.getEntityId(), entityId)
                                    && Objects.equals(criteria.getProgramProfileId(), programProfile)) {
                                programProfileFound = true;
                            }
                        }
                    }

                    if (programProfileFound == false) {

                        programprofile programProfileDetails = programprofilemanager
                                .getProgramsDetails(programProfile);
                        if (programProfileDetails != null && programProfileDetails.isStatus()) {
                            surveyProgramProfiles newSelProgramProfile = new surveyProgramProfiles();
                            newSelProgramProfile.setProgramProfileId(programProfile);
                            newSelProgramProfile.setProgramProfileName(programProfileDetails.getName());
                            newSelProgramProfile.setEntityId(entityId);
                            newSelProgramProfile.setEntityName(entityDetails.getName());

                            if (surveyId > 0) {
                                submittedsurveyprogramprofiles codesetFound = surveyManager
                                        .getSurveySelectedPrograms(surveyId, entityId, programProfile);

                                if (codesetFound != null && codesetFound.getId() > 0) {
                                    newSelProgramProfile.setChecked(true);
                                }
                            }

                            selectedProgramProfile.add(newSelProgramProfile);
                        }
                    }

                }
            }
        }

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/survey/programProfileTable");

        /* Sort surveyContentCriterias */
        List<surveyProgramProfiles> currentselectedProgramProfiles = (List<surveyProgramProfiles>) session
                .getAttribute("selectedProgramProfiles");
        mav.addObject("programProfiles", currentselectedProgramProfiles);
        mav.addObject("disabled", disabled);

        return mav;

    }

    /**
     *
     * @param entityId
     * @param codeId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saveSelEntityProgram", method = RequestMethod.POST)
    public @ResponseBody Integer saveSelEntityProgram(
            @RequestParam(value = "entityId", required = true) Integer entityId,
            @RequestParam(value = "programProfileId", required = true) Integer programProfileId,
            HttpSession session) throws Exception {

        List<surveyProgramProfiles> selectedProgramProfiles = (List<surveyProgramProfiles>) session
                .getAttribute("selectedProgramProfiles");

        Iterator<surveyProgramProfiles> it = selectedProgramProfiles.iterator();

        while (it.hasNext()) {

            surveyProgramProfiles criteria = it.next();
            criteria.setChecked(false);

            if (Objects.equals(criteria.getEntityId(), entityId)
                    && Objects.equals(criteria.getProgramProfileId(), programProfileId)) {
                criteria.setChecked(true);
            }
        }

        return (Integer) 1;
    }

    /**
     * The 'removeEntry' POST request will mark the survey submission as deleted.
     * 
     * @param surveyId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/removeEntry", method = RequestMethod.POST)
    public @ResponseBody Integer removeEntry(@RequestParam(value = "i", required = true) Integer surveyId)
            throws Exception {

        /* Get the submitted surveys for the selected survey type */
        if (!"".equals(surveyId) && surveyId != null) {

            submittedSurveys survey = surveyManager.getSubmittedSurvey(surveyId);

            survey.setDeleted(true);

            surveyManager.deleteSurveyEntry(survey);
        }

        return (Integer) 1;
    }

    /**
     * The 'getSurveyDocuments' GET request will return a list of submitted survey documents.
     *
     * @param surveyId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSurveyDocuments.do", method = RequestMethod.GET)
    public @ResponseBody ModelAndView getSurveyDocuments(
            @RequestParam(value = "surveyId", required = true) Integer surveyId) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/survey/uploadedDocs");
        mav.addObject("surveyId", surveyId);

        /* Get a list of survey documents */
        List<submittedSurveyDocuments> surveyDocuments = surveyManager.getSubmittedSurveyDocuments(surveyId);

        if (surveyDocuments != null && surveyDocuments.size() > 0) {
            for (submittedSurveyDocuments document : surveyDocuments) {
                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"));
                }
            }
        }

        mav.addObject("surveyDocuments", surveyDocuments);

        return mav;

    }

    /**
     * The 'saveDocumentForm' POST request will handle saving the new/updated document
     * message.
     *
     * @param surveyDocuments
     * @param redirectAttr
     * @param session
     * @param surveyId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saveDocumentForm.do", method = RequestMethod.POST)
    public @ResponseBody ModelAndView saveDocumentForm(
            @RequestParam(value = "surveyDocuments", required = false) List<MultipartFile> surveyDocuments,
            RedirectAttributes redirectAttr, HttpSession session,
            @RequestParam(value = "surveyId", required = true) Integer surveyId,
            @RequestParam(value = "completed", required = true) Integer completed) throws Exception {

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

        if (surveyDocuments != null) {

            for (MultipartFile uploadedFile : surveyDocuments) {

                submittedSurveyDocuments surveyDocument = new submittedSurveyDocuments();
                surveyDocument.setSystemUserId(userDetails.getId());
                surveyDocument.setSubmittedSurveyId(surveyId);

                surveyManager.saveSurveyDocument(surveyDocument, uploadedFile, programId, 0);
            }
        }

        if ("1".equals(completed.toString())) {
            submittedSurveys submittedSurveyDetails = surveyManager.getSubmittedSurvey(surveyId);

            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(submittedSurveyDetails.getSurveyId()));
            map.put("topSecret", topSecret);

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

            surveys surveyDetails = surveyManager.getSurveyDetails(submittedSurveyDetails.getSurveyId());
            redirectAttr.addFlashAttribute("surveyDetails", surveyDetails);
            redirectAttr.addFlashAttribute("surveys", surveys);
            redirectAttr.addFlashAttribute("i", encrypted[0]);
            redirectAttr.addFlashAttribute("v", encrypted[1]);
            redirectAttr.addFlashAttribute("submittedSurveyId", surveyId);

            /* Get a list of survey documents */
            List<submittedSurveyDocuments> uploadedsurveyDocuments = surveyManager
                    .getSubmittedSurveyDocuments(surveyId);

            if (uploadedsurveyDocuments != null && uploadedsurveyDocuments.size() > 0) {
                for (submittedSurveyDocuments document : uploadedsurveyDocuments) {
                    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"));

                    }
                }
            }

            redirectAttr.addFlashAttribute("surveyDocuments", uploadedsurveyDocuments);

            ModelAndView mav = new ModelAndView(new RedirectView("/surveys/completedSurvey"));
            return mav;

        } else {
            redirectAttr.addFlashAttribute("message", "fileUploaded");
            ModelAndView mav = new ModelAndView(new RedirectView("/surveys"));
            return mav;
        }

    }

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

        submittedSurveyDocuments documentDetails = surveyManager.getDocumentById(documentId);
        documentDetails.setStatus(false);
        surveyManager.saveSurveyDocument(documentDetails, null, programId, 0);
        return 1;
    }

    /**
     * 
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/completedSurvey", method = RequestMethod.GET)
    public ModelAndView completedSurvey() throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/completedSurvey");

        return mav;
    }

    /**
     * The '/viewSurveyDocuments' GET request will display the detail survey document page.
     *
     * @param i The encrypted survey id
     * @param v The encrypted decryption key
     *
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/viewSurveyDocuments", method = RequestMethod.GET)
    public ModelAndView surveyDocuments(@RequestParam String i, @RequestParam String v, HttpSession session,
            HttpServletRequest request) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/surveyDocuments");
        mav.addObject("surveys", surveys);

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

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

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

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

        submittedSurveys submittedSurveyDetails = surveyManager.getSubmittedSurvey(surveyId);

        surveys surveyDetails = surveyManager.getSurveyDetails(submittedSurveyDetails.getSurveyId());
        mav.addObject("surveyDetails", surveyDetails);
        mav.addObject("selSurvey", submittedSurveyDetails.getSurveyId());

        /* Get a list of survey documents */
        List<submittedSurveyDocuments> surveyDocuments = surveyManager.getSubmittedSurveyDocuments(surveyId);

        if (surveyDocuments != null && surveyDocuments.size() > 0) {
            for (submittedSurveyDocuments document : surveyDocuments) {
                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"));
                }
            }
        }

        List<document> documents = documentmanager.getDocumentBySurveyId(surveyId);
        String[][] uploadedPaths = null;
        if (documents != null) {
            uploadedPaths = new String[documents.size()][2];
            int index = 0;
            for (document documentDetails : documents) {
                String uploadedPath = "";
                documentFolder folderDetails = documentmanager.getFolderById(documentDetails.getFolderId());

                Integer folderCount = 1;

                /* Get a list of folders  */
                Integer parentFolderId = 0;
                if (folderDetails.getParentFolderId() > 0) {

                    parentFolderId = folderDetails.getParentFolderId();

                    documentFolder parentFolderDetails = documentmanager.getFolderById(parentFolderId);

                    if (parentFolderDetails.getParentFolderId() > 0) {
                        folderCount += 1;

                        documentFolder superParentFolderDetails = documentmanager
                                .getFolderById(parentFolderDetails.getParentFolderId());

                        uploadedPath = superParentFolderDetails.getFolderName() + "/";
                    }

                    uploadedPath += parentFolderDetails.getFolderName() + "/" + folderDetails.getFolderName();

                } else {
                    uploadedPath = folderDetails.getFolderName();
                }

                uploadedPaths[index][0] = Integer.toString(documentDetails.getId());
                uploadedPaths[index][1] = uploadedPath;
                index++;
            }
            mav.addObject("uploadedPaths", uploadedPaths);
        }
        mav.addObject("surveyDocuments", surveyDocuments);

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

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

        mav.addObject("i", encrypted[0]);
        mav.addObject("v", encrypted[1]);

        return mav;
    }

    /**
     * The '/surveyDocuments' POST request will submit the document form for surveys.
     *
     * @param i The encrypted survey id
     * @param v The encrypted decryption key
     *
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/viewSurveyDocuments", method = RequestMethod.POST)
    public ModelAndView submitSurveyDocuments(@RequestParam String i, @RequestParam String v, HttpSession session,
            HttpServletRequest request,
            @RequestParam(value = "surveyDocuments", required = false) List<MultipartFile> surveyDocuments,
            @RequestParam(value = "otherFolder", required = true) Integer otherFolder,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "docDesc", required = false) String docDesc, RedirectAttributes redirectAttr)
            throws Exception {

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

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

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

        int surveyId = 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");

        if (surveyDocuments != null) {

            Integer documentId = 0;

            if (otherFolder > 0) {
                document documentDetails = new document();
                documentDetails.setAdminOnly(false);
                documentDetails.setCountyFolder(false);
                documentDetails.setProgramId(programId);
                documentDetails.setFolderId(otherFolder);
                documentDetails.setTitle(title);
                documentDetails.setDocDesc(docDesc);
                documentDetails.setSystemUserId(userDetails.getId());
                documentDetails.setStatus(true);
                documentDetails.setPrivateDoc(false);
                documentDetails.setSubmittedSurveyId(surveyId);
                documentId = documentmanager.saveDocument(documentDetails);
                documentmanager.saveUploadedDocument(documentDetails, surveyDocuments);
            }

            for (MultipartFile uploadedFile : surveyDocuments) {

                submittedSurveyDocuments surveyDocument = new submittedSurveyDocuments();
                surveyDocument.setSystemUserId(userDetails.getId());
                surveyDocument.setSubmittedSurveyId(surveyId);

                surveyManager.saveSurveyDocument(surveyDocument, uploadedFile, programId, documentId);
            }
        }

        redirectAttr.addFlashAttribute("message", "fileUploaded");
        ModelAndView mav = new ModelAndView(new RedirectView("/surveys/viewSurveyDocuments?i="
                + URLEncoder.encode(i, "UTF-8") + "&v=" + URLEncoder.encode(v, "UTF-8")));
        return mav;

    }

    /**
     * @param filter START for start date of month e.g. Nov 01, 2013 END for end date of month e.g. Nov 30, 2013
     * @return
     */
    public Date getMonthDate(String filter) {

        String MM_DD_YYYY = "yyyy-mm-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(MM_DD_YYYY);
        sdf.setTimeZone(TimeZone.getTimeZone("EST"));
        sdf.format(GregorianCalendar.getInstance().getTime());

        Calendar cal = GregorianCalendar.getInstance();
        int date = cal.getActualMinimum(Calendar.DATE);
        if ("END".equalsIgnoreCase(filter)) {
            date = cal.getActualMaximum(Calendar.DATE);
            cal.set(Calendar.DATE, date);
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            cal.set(Calendar.MILLISECOND, 0);
        } else {
            cal.set(Calendar.DATE, date);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
        }

        return cal.getTime();
    }

    /**
     * The 'isQuestionValueNumeric' will test if the selected question value is a numeric value;
     * @param questionValue
     * @return 
     */
    public static boolean isQuestionValueNumeric(String questionValue) {

        try {
            int d = Integer.parseInt(questionValue);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;

    }

    /**
     * The '/startSessionSurvey' GET request will build out the survey and display the first page of the survey.
     *
     * @param i The encrypted client id
     * @param v The encrypted decryption key
     * @param s The id of the selected survey
     *
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/startSessionSurvey", method = RequestMethod.GET)
    public ModelAndView startSessionSurvey(@RequestParam(value = "i", required = true) String i,
            @RequestParam(value = "v", required = true) String v,
            @RequestParam(value = "j", required = true) String j,
            @RequestParam(value = "x", required = true) String x,
            @RequestParam(value = "z", required = true) Integer z, HttpSession session) throws Exception {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/takeSurvey");
        mav.addObject("surveys", surveys);

        //Set the survey answer array to get ready to hold data
        if (session.getAttribute("questionAnswers") != null) {
            session.removeAttribute("questionAnswers");
        }
        session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>());

        if (session.getAttribute("selectedProgramProfiles") != null) {
            session.removeAttribute("selectedProgramProfiles");
        }
        session.setAttribute("selectedProgramProfiles", new ArrayList<surveyProgramProfiles>());

        if (session.getAttribute("secondTierEntities") != null) {
            session.removeAttribute("secondTierEntities");
        }
        session.setAttribute("secondTierEntities", new ArrayList<secondTierEntities>());

        if (session.getAttribute("seenPages") != null) {
            session.removeAttribute("seenPages");
        }
        session.setAttribute("seenPages", new ArrayList<Integer>());

        int clientId = 0;
        int surveyId = 0;

        /* Get the submitted surveys for the selected survey type */
        if (!"".equals(i) && i != null && !"".equals(v) && v != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

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

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

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

        }

        if (!"".equals(j) && j != null && !"".equals(x) && x != null) {
            /* Decrypt the url */
            decryptObject decrypt = new decryptObject();

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

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

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

        if (surveyId > 0) {

            surveys surveyDetails = surveyManager.getSurveyDetails(surveyId);

            /* Make sure the survey is part of this program and active */
            if (surveyDetails.getProgramId() != programId || surveyDetails.getStatus() == false) {

                /* Redirect back to the survey list page */
            } /* Set up the survey */ else {
                survey survey = new survey();
                survey.setClientId(clientId);
                survey.setSurveyId(surveyId);
                survey.setSurveyTitle(surveyDetails.getTitle());
                survey.setPrevButton(surveyDetails.getPrevButtonText());
                survey.setNextButton(surveyDetails.getNextButtonText());
                survey.setSaveButton(surveyDetails.getDoneButtonText());
                survey.setSubmittedSurveyId(0);
                survey.setSessionId(z);

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

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

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

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

                /* Get the pages */
                List<SurveyPages> surveyPages = surveyManager.getSurveyPages(surveyId, false, 0, 0, 0, 0);
                SurveyPages currentPage = surveyManager.getSurveyPage(surveyId, true, 1, clientId, 0, 0, 0, 0, 0);
                survey.setPageTitle(currentPage.getPageTitle());
                survey.setSurveyPageQuestions(currentPage.getSurveyQuestions());
                survey.setTotalPages(surveyPages.size());
                survey.setPageId(currentPage.getId());
                survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId());

                mav.addObject("survey", survey);
                mav.addObject("surveyPages", surveyPages);

                if (surveyDetails.isAssociateToProgram()) {
                    mav.addObject("showPrograms", true);
                } else {
                    mav.addObject("showPrograms", false);
                }
            }
        } else {
            /* Redirect back to the survey list page */

        }

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

        mav.addObject("selSurvey", surveyId);
        mav.addObject("currentPage", 1);
        mav.addObject("currPageNum", 1);

        mav.addObject("qNum", 0);
        mav.addObject("disabled", false);

        return mav;
    }

    /**
     * The 'getEntityCoordinators' GET request will get all the community coordinator profiles for the selected entity.
     *
     * @param entityId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getEntityCoordinators", method = RequestMethod.GET)
    public @ResponseBody ModelAndView getEntityCoordinators(
            @RequestParam(value = "entityId", required = true) List<Integer> entityIdList,
            @RequestParam(value = "surveyId", required = true) Integer surveyId,
            @RequestParam(value = "disabled", required = true) Boolean disabled, HttpSession session)
            throws Exception {

        List<surveyExtraInformation> selectedExtraInformation = (List<surveyExtraInformation>) session
                .getAttribute("selectedExtras");

        if (selectedExtraInformation != null) {

            Iterator<surveyExtraInformation> it = selectedExtraInformation.iterator();

            List<surveyExtraInformation> toRemove = new ArrayList<surveyExtraInformation>();

            while (it.hasNext()) {

                surveyExtraInformation criteria = it.next();

                if (!Objects.equals(criteria.getEntityId(), entityIdList.get(0))) {
                    toRemove.add(criteria);
                }
            }

            if (toRemove != null && !toRemove.isEmpty()) {
                selectedExtraInformation.removeAll(toRemove);
            }
        }

        for (Integer entityId : entityIdList) {
            programHierarchyDetails entityDetails = hierarchymanager.getProgramHierarchyItemDetails(entityId);

            /* Get the associated program profiles for the passed in entity */
            List<partnerprofile> coalitionCoordinators = partnerprofilemanager
                    .getCoalitionCoordinatorsByEntity(programId, entityId);

            if (coalitionCoordinators != null && !coalitionCoordinators.isEmpty()) {

                for (partnerprofile coalitionCoordinator : coalitionCoordinators) {
                    boolean coalitionCoordinatorFound = false;

                    if (selectedExtraInformation != null) {
                        Iterator<surveyExtraInformation> it = selectedExtraInformation.iterator();

                        while (it.hasNext()) {

                            surveyExtraInformation criteria = it.next();

                            if (Objects.equals(criteria.getEntityId(), entityId)
                                    && Objects.equals(criteria.hashCode(), coalitionCoordinator.getId())) {
                                coalitionCoordinatorFound = true;
                            }
                        }
                    }

                    if (coalitionCoordinatorFound == false) {

                        surveyExtraInformation newSelExtraInformation = new surveyExtraInformation();
                        newSelExtraInformation.setEntityId(entityId);
                        newSelExtraInformation.setEntityName(entityDetails.getName());
                        newSelExtraInformation.setExtraId(coalitionCoordinator.getId());
                        newSelExtraInformation.setExtraName(coalitionCoordinator.getPartnerFirstName() + " "
                                + coalitionCoordinator.getPartnerLastName());

                        if (surveyId > 0) {
                            submittedsurveycoordinators codesetFound = surveyManager.getSurveySelectedCoordinators(
                                    surveyId, entityId, coalitionCoordinator.getId());

                            if (codesetFound != null && codesetFound.getId() > 0) {
                                newSelExtraInformation.setChecked(true);
                            }
                        }

                        selectedExtraInformation.add(newSelExtraInformation);
                    }

                }
            }
        }

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/survey/coordinators");

        /* Sort surveyContentCriterias */
        List<surveyExtraInformation> currentselectedExtraInformation = (List<surveyExtraInformation>) session
                .getAttribute("selectedExtras");
        mav.addObject("coordinators", currentselectedExtraInformation);
        mav.addObject("disabled", disabled);

        return mav;

    }

    /**
     *
     * @param entityId
     * @param codeId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saveSelEntityCoordinator", method = RequestMethod.POST)
    public @ResponseBody Integer saveSelEntityCoordinator(
            @RequestParam(value = "entityId", required = true) Integer entityId,
            @RequestParam(value = "coordinatorId", required = true) Integer coordinatorId, HttpSession session)
            throws Exception {

        List<surveyExtraInformation> selectedExtraInformation = (List<surveyExtraInformation>) session
                .getAttribute("selectedExtras");

        Iterator<surveyExtraInformation> it = selectedExtraInformation.iterator();

        while (it.hasNext()) {

            surveyExtraInformation criteria = it.next();
            criteria.setChecked(false);

            if (Objects.equals(criteria.getEntityId(), entityId)
                    && Objects.equals(criteria.getExtraId(), coordinatorId)) {
                criteria.setChecked(true);
            }
        }

        return (Integer) 1;
    }

    /**
     * The 'checkForDuplicateSurveys' GET request will query the system to make sure their is not a same contract number
     * in the system.
     * 
     * @param i
     * @param v
     * @param enteredDate
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/checkForDuplicateSurveys", method = RequestMethod.GET, produces = {
            MediaType.TEXT_PLAIN_VALUE })
    @ResponseBody
    public String checkForDuplicateSurveys(@RequestParam Integer surveyId, @RequestParam Integer submittedSurveyId,
            @RequestParam Integer entityId, @RequestParam(value = "otherId", required = false) Integer otherId,
            @RequestParam String surveyTag,
            @RequestParam(value = "answerValues", required = false) List<String> answerValues) throws Exception {

        boolean duplicateFound = false;

        if ("Coordinator Hours".equals(surveyTag)) {
            List<String> questionTags = Arrays.asList("reportMonth", "reportYear");
            duplicateFound = surveyManager.checkForDuplicateSurvey(programId, surveyId, submittedSurveyId, entityId,
                    otherId, questionTags, "submittedsurveycoordinators", answerValues);
        } else if ("CPWI".equals(surveyTag)) {
            List<String> questionTags = Arrays.asList("reportingYear", "reportingQuarter");
            duplicateFound = surveyManager.checkForDuplicateSurvey(programId, surveyId, submittedSurveyId, entityId,
                    otherId, questionTags, "submittedsurveyprogramprofiles", answerValues);
        } else if ("TribalAnnualReport".equals(surveyTag)) {
            List<String> questionTags = Arrays.asList("reportingYear");
            duplicateFound = surveyManager.checkForDuplicateSurvey(programId, surveyId, submittedSurveyId, entityId,
                    otherId, questionTags, "", answerValues);
        } else if ("ActivityReporting".equals(surveyTag)) {
            List<String> questionTags = Arrays.asList("logName");
            duplicateFound = surveyManager.checkForDuplicateSurvey(programId, surveyId, submittedSurveyId, entityId,
                    otherId, questionTags, "submittedsurveyprogramprofiles", answerValues);
        }

        if (duplicateFound == true) {
            return "1";
        } else {
            return "0";
        }

    }

}