/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/nursingadmission/Logic.java
//#############################################################################
//#                                                                           #
//#  Copyright (C) <2015>  <IMS MAXIMS>                                       #
//#                                                                           #
//#  This program is free software: you can redistribute it and/or modify     #
//#  it under the terms of the GNU Affero General Public License as           #
//#  published by the Free Software Foundation, either version 3 of the       #
//#  License, or (at your option) any later version.                          # 
//#                                                                           #
//#  This program is distributed in the hope that it will be useful,          #
//#  but WITHOUT ANY WARRANTY; without even the implied warranty of           #
//#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
//#  GNU Affero General Public License for more details.                      #
//#                                                                           #
//#  You should have received a copy of the GNU Affero General Public License #
//#  along with this program.  If not, see <http://www.gnu.org/licenses/>.    #
//#                                                                           #
//#  IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of    #
//#  this program.  Users of this software do so entirely at their own risk.  #
//#  IMS MAXIMS only ensures the Clinical Safety of unaltered run-time        #
//#  software that it builds, deploys and maintains.                          #
//#                                                                           #
//#############################################################################
//#EOH
// This code was generated by Billy Mahon using IMS Development Environment (version 1.45 build 2382.21900)
// Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved.

package ims.nursing.forms.nursingadmission;

import ims.nursing.forms.nursingadmission.GenForm;
import ims.nursing.forms.nursingadmission.GenForm.grdFamilyRow;
import ims.configuration.gen.ConfigFlag;
import ims.core.vo.PatientDiagnosisShortVo;
import ims.core.vo.PatientDiagnosisShortVoCollection;
import ims.core.vo.PatientProcedureShortVo;
import ims.core.vo.PatientProcedureShortVoCollection;
import ims.core.vo.SupportNetworkFamily;
import ims.core.vo.SupportNetworkFamilyCollection;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.Control;
import ims.framework.FormName;
import ims.framework.controls.DynamicGridCell;
import ims.framework.controls.DynamicGridColumn;
import ims.framework.controls.DynamicGridRow;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.DynamicCellType;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.CodingRuntimeException;
import ims.framework.exceptions.PresentationLogicException;
import ims.nursing.vo.AdmissionDetailsQuestionsVo;
import ims.nursing.vo.AdmissionDetailsQuestionsVoCollection;
import ims.nursing.vo.AdmissionDetailsVo;
import ims.vo.ValueObject;
import ims.core.vo.lookups.PatientProcedureStatus;
import ims.core.vo.lookups.YesNo;
import ims.nursing.vo.lookups.AdmissionQuestion;
import ims.nursing.vo.lookups.AdmissionQuestionCollection;
import ims.nursing.vo.lookups.LookupHelper;

public class Logic extends BaseLogic
{
	private static final long	serialVersionUID	= 1L;

	private static final String	QUESTIONS_COLUMN	= "0";
	private static final String	ANSWERS_COLUMN		= "1";

	protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException
	{
		initialize();
		open();
	}

	public void initialize() throws PresentationLogicException
	{
		StringBuffer exceptions = new StringBuffer();	
		if (ims.core.vo.lookups.LookupHelper.getResuscitationStatus(domain.getLookupService()).size() == 0)
		{
			exceptions.append("Please configure ResuscitationStatus lookup");
			exceptions.append("\n");
		}
		
		if(exceptions.length() > 0)
			throw new PresentationLogicException(exceptions.toString());
		//WDEV-7356
		form.customControlAuthoringInfo().setIsRequiredPropertyToControls(true);
	}
	
	private void initializeDynamicGrdMotor()
	{
		form.dynQuestions().clear();
		
		DynamicGridColumn column = form.dynQuestions().getColumns().newColumn("Questions", QUESTIONS_COLUMN);
		column.setWidth(350);
		column.setReadOnly(true);

		DynamicGridColumn column2 = form.dynQuestions().getColumns().newColumn("Answers", ANSWERS_COLUMN);
		column2.setWidth(-1);
		column2.setReadOnly(false);
		
		AdmissionQuestionCollection admQuestions = new AdmissionQuestionCollection();
		admQuestions = LookupHelper.getAdmissionQuestion(domain.getLookupService());
		
		for (int i = 0; i < admQuestions.size(); i++)
		{
			AdmissionQuestion ar = admQuestions.get(i);
			DynamicGridRow row = form.dynQuestions().getRows().newRow();
			row.setValue(ar);
			row.setSelectable(false);
			
			DynamicGridCell cell = row.getCells().newCell(getColumn(QUESTIONS_COLUMN), DynamicCellType.WRAPTEXT);
			cell.setValue(ar.getText());
			cell.setTooltip(ar.getText());
			cell.setAutoPostBack(false);
			cell.setReadOnly(true);
			 
			DynamicGridCell cell2 = row.getCells().newCell(getColumn(ANSWERS_COLUMN), DynamicCellType.ANSWER);
			cell2.getItems().newItem(YesNo.NO,YesNo.NO.getImage());
			cell2.getItems().newItem(YesNo.YES,YesNo.YES.getImage());
			cell2.setValue(null);
			cell2.setAutoPostBack(false);			
 		}		
		
	}

	private DynamicGridColumn getColumn(String identifier)
	{
		return form.dynQuestions().getColumns().getByIdentifier(identifier);
	}

	private void open()
	{
		clearScreen();
		setLocalContexts();

		if (form.getLocalContext().getvoAdmissionDetailsIsNotNull())
		{
			form.btnNew().setEnabled(false);
			form.btnUpdate().setEnabled(true);
		}
		else
		{
			form.btnNew().setEnabled(true);
			form.btnUpdate().setEnabled(false);
		}
		populateScreenFromData();
	}

	private void setLocalContexts()
	{
		form.getLocalContext().setvoAdmissionDetails(domain.getNursingAdmission(form.getGlobalContext().Core.getCurrentCareContext()));
	}

	private void populateScreenFromData()
	{
		if(form.getLocalContext().getvoAdmissionDetailsIsNotNull())
		{
			//populate questios grid - WDEV-7145 
			initializeDynamicGrdMotor();
			
			// Populate Family support grid
			populateFamilySupportGrid();
	
			// Populate Diagnosis/procedure grid
			populateDiagProcedureGrid();
		}
		
		AdmissionDetailsVo voAdmissionDetails = form.getLocalContext().getvoAdmissionDetails();
		if (voAdmissionDetails == null)
			return;

		form.customControlAuthoringInfo().setValue(voAdmissionDetails.getAuthoringInformation());

		// Populate reason for admission data
		if (voAdmissionDetails.getPatientAdmReasonIsNotNull())
			form.txtPatient().setValue(voAdmissionDetails.getPatientAdmReason());
		if (voAdmissionDetails.getNursingAdmReasonIsNotNull())
			form.txtNursing().setValue(voAdmissionDetails.getNursingAdmReason());
		if (voAdmissionDetails.getResusStatusIsNotNull())
			form.cmbResusStatus2().setValue(voAdmissionDetails.getResusStatus());
		if (voAdmissionDetails.getIsDnrFormCompletedIsNotNull())
		{
			if (voAdmissionDetails.getIsDnrFormCompleted().equals(Boolean.TRUE))
				form.ansDNRComplete().setValue(YesNo.YES);
			else
				form.ansDNRComplete().setValue(YesNo.NO);
		}

		//communication
		form.txtCommunication().setValue(voAdmissionDetails.getCommunicationNeeds());
		
		//preferred language
		form.cmbPreferredLang().setValue(voAdmissionDetails.getPreferredLang());
		
		// Populate questions grid		
		populateQuestionsGrid(voAdmissionDetails.getAdmQuestionsAns());

		// Populate diag discussed answer box.
		if (voAdmissionDetails.getWasDiagnosisDiscussedIsNotNull())
		{
			if (voAdmissionDetails.getWasDiagnosisDiscussed().equals(Boolean.TRUE))
				form.ansDiagDiscussed().setValue(YesNo.YES);
			else
				form.ansDiagDiscussed().setValue(YesNo.NO);
		}

	}

	private void populateQuestionsGrid(AdmissionDetailsQuestionsVoCollection vocoll)
	{
		if (vocoll != null)
		{
			for (int j=0; j<vocoll.size();j++)
			{
				for (int i=0; i<form.dynQuestions().getRows().size();i++)
				{
					DynamicGridRow dyrow = form.dynQuestions().getRows().get(i);
					if (dyrow.getValue().equals(vocoll.get(j).getQuestion()))
					{
						dyrow.getCells().get(getColumn(ANSWERS_COLUMN)).setValue(vocoll.get(j).getAnswer());
					}					
				}
			}
		}
	}
	
	private void populateDiagProcedureGrid()
	{
		form.grdDiagnosis().getRows().clear();

		getDiagnosisRecords();
		getProcedureRecords();
	}

	private void getProcedureRecords()
	{
		PatientProcedureShortVoCollection voCollProcedure = null;
		voCollProcedure = domain.listProceduresByEpisodeOfCare(form.getGlobalContext().Core.getEpisodeofCareShort());
		if (voCollProcedure == null || voCollProcedure.size() == 0)
		{
			// engine.showMessage("No procedures found!");
			return;
		}
		displayProcedureCollection(voCollProcedure);
	}

	private void getDiagnosisRecords()
	{
		PatientDiagnosisShortVoCollection voCollDiagnosis = domain.listEpisodeOfCareDiagnoses(form.getGlobalContext().Core.getEpisodeofCareShort());
		if (voCollDiagnosis == null || voCollDiagnosis.size() == 0)
		{
			// engine.showMessage("No diagnosis found!");
			return;
		}
		displayDiagnosisCollection(voCollDiagnosis);
	}

	private void displayProcedureCollection(PatientProcedureShortVoCollection voCollProcedure)
	{
		if (voCollProcedure != null)
		{
			for (int i = 0; i < voCollProcedure.size(); i++)
			{
				if(PatientProcedureStatus.PERFORMED.equals(voCollProcedure.get(i).getProcedureStatus())
						|| (PatientProcedureStatus.PLANNED.equals(voCollProcedure.get(i).getProcedureStatus()) && voCollProcedure.get(i).getProcedureOutcome()==null)){
					GenForm.grdDiagnosisRow pRow = form.grdDiagnosis().getRows().newRow();
					pRow.setColDiagnosis(voCollProcedure.get(i).getProcedureDescription());
					pRow.setValue(voCollProcedure.get(i));
				}
			}
		}
	}

	private void displayDiagnosisCollection(PatientDiagnosisShortVoCollection voCollDiagnosis)
	{
		if (voCollDiagnosis != null)
		{
			GenForm.grdDiagnosisRow dRow = null;
			for (int i = 0; i < voCollDiagnosis.size(); i++)
			{
				dRow = form.grdDiagnosis().getRows().newRow();
				dRow.setColDiagnosis(voCollDiagnosis.get(i).getDiagnosisDescription());
				dRow.setValue(voCollDiagnosis.get(i));
			}
		}
	}

	private void populateFamilySupportGrid()
	{
		SupportNetworkFamilyCollection voCollFamily = domain.listSupportNetworkFamily(Boolean.TRUE, form.getGlobalContext().Core.getPatientShort());
		form.getLocalContext().setvoFamilySupportColl(voCollFamily);
		form.getLocalContext().setvoFamilySupportRemovedColl(new SupportNetworkFamilyCollection());
		
		SupportNetworkFamily voFamily = null;

		GenForm.grdFamilyRow row = null;
		if (voCollFamily == null)
			return;

		for (int i = 0; i < voCollFamily.size(); i++)
		{
			voFamily = voCollFamily.get(i);
			row = form.grdFamily().getRows().newRow();
			row.setColName(voFamily.getCarerName());
			row.setColContact(voFamily.getCarerHomePhone());
			
			if (voFamily.getCarerRelationship() != null)
				row.setColRelationship(voFamily.getCarerRelationship());
			 
				
			if (voFamily.getDiscussProgress() == null)
				row.setColProgress(YesNo.NO);				
			else if (voFamily.getDiscussProgress().equals(Boolean.FALSE))
				row.setColProgress(YesNo.NO);
			else if (voFamily.getDiscussProgress().equals(Boolean.TRUE))
				row.setColProgress(YesNo.YES);

			row.setValue(voFamily);
		}
	}

	private void clearScreen()
	{
		form.ansDiagDiscussed().setValue(null);
		form.ansDNRComplete().setValue(null);
		form.txtNursing().setValue(null);
		form.txtPatient().setValue(null);
		form.txtCommunication().setValue(null);
		form.cmbResusStatus2().setValue(null);
		form.customControlAuthoringInfo().setValue(null);
		form.grdDiagnosis().getRows().clear();
		form.grdFamily().getRows().clear();
		form.cmbPreferredLang().setValue(null);
		form.dynQuestions().clear();
		
		//clearQuestions();
	}

	private void clearQuestions()
	{
		for(int i=0;i<form.dynQuestions().getRows().size();i++)
		{			
			form.dynQuestions().getRows().get(i).getCells().get(getColumn(ANSWERS_COLUMN)).setValue(null);				
			form.dynQuestions().getRows().get(i).getCells().get(getColumn(ANSWERS_COLUMN)).setReadOnly(false);
		}
	}
	protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.EDIT);

		updateContextMenus();
		enableDiagnosisProcedureGridContextMenu();

		form.btnNew().setVisible(false);
		form.btnUpdate().setVisible(false);

		form.customControlAuthoringInfo().initializeComponent();
		
		//populate questions grid - WDEV-7145 
		initializeDynamicGrdMotor();
		
		// Populate Family support grid
		populateFamilySupportGrid();

		// Populate Diagnosis/procedure grid
		populateDiagProcedureGrid();
	}

	protected void onBtnUpdateClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.EDIT);
		updateContextMenus();
		enableDiagnosisProcedureGridContextMenu();
		form.btnNew().setVisible(false);
		form.btnUpdate().setVisible(false);

	}

	protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		AdmissionDetailsVo voAdmissionDetails = form.getLocalContext().getvoAdmissionDetails();
		if (voAdmissionDetails == null)
			voAdmissionDetails = new AdmissionDetailsVo();
		
		if(voAdmissionDetails.getID_AdmissionDetails() == null)
		{
			AdmissionDetailsVo oldRec = domain.getNursingAdmission(form.getGlobalContext().Core.getCurrentCareContext());
			
			if(oldRec != null)
			{
				engine.showMessage("A record exists for this care context, the screen will be refreshed.");
				
				form.setMode(FormMode.VIEW);
				updateContextMenus();
				enableDiagnosisProcedureGridContextMenu();
				form.getContextMenus().getGenericGridAddItem().setVisible(false);
				form.btnNew().setVisible(true);
				form.btnUpdate().setVisible(true);
				open();

				return;
			}
		}

		populateDataFromScreen(voAdmissionDetails);

		voAdmissionDetails.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
		voAdmissionDetails.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());

		getFamilySupportGridData(voAdmissionDetails);

		// Check THE SUPPORT FAMILY NETWORK COLECTION
		String[] messages = form.getLocalContext().getvoFamilySupportColl().validate();
		if (messages != null)
		{
			engine.showErrors("Validation Errors", messages);
			return;
		}
		
		// CHeck the admission details record
		String[] arrErrors = voAdmissionDetails.validate();
		if (arrErrors != null)
		{
			engine.showErrors(arrErrors);
			return;
		}
		
		// Save THE SUPPORT FAMILY NETWORK COLECTION		
		try
		{
			domain.saveSupportNetworkFamily(form.getLocalContext().getvoFamilySupportColl());
		}
		catch (StaleObjectException e)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			form.setMode(FormMode.VIEW);
			updateContextMenus();
			enableDiagnosisProcedureGridContextMenu();
			form.getContextMenus().getGenericGridAddItem().setVisible(false);
			open();
			form.btnNew().setVisible(true);
			form.btnUpdate().setVisible(true);
			return;
		}

		// Save the admission details record
		try
		{
			form.getLocalContext().setvoAdmissionDetails(domain.saveNursingAdmission(voAdmissionDetails));
		}
		catch (StaleObjectException e)
		{
			engine.showMessage(ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
			form.setMode(FormMode.VIEW);
			updateContextMenus();
			enableDiagnosisProcedureGridContextMenu();
			form.getContextMenus().getGenericGridAddItem().setVisible(false);
			form.btnNew().setVisible(true);
			form.btnUpdate().setVisible(true);
			open();
			return;
		}
		form.setMode(FormMode.VIEW);
		updateContextMenus();
		enableDiagnosisProcedureGridContextMenu();
		form.getContextMenus().getGenericGridAddItem().setVisible(false);
		form.btnNew().setVisible(true);
		form.btnUpdate().setVisible(true);
		open();
	}

	private void getFamilySupportGridData(AdmissionDetailsVo voAdmissionDetails)
	{
		GenForm.grdFamilyRowCollection familyRows = form.grdFamily().getRows();
		GenForm.grdFamilyRow familyRow = null;
		SupportNetworkFamilyCollection voFamSupportNetColl = new SupportNetworkFamilyCollection();
		SupportNetworkFamily voFamSupportNet = null;
		for (int i = 0; i < familyRows.size(); i++)
		{
			familyRow = form.grdFamily().getRows().get(i);
			voFamSupportNet = familyRow.getValue();
			if (familyRow.getValue() == null)
			{
				voFamSupportNet = new SupportNetworkFamily();
				voFamSupportNet.setAuthoringInfo(voAdmissionDetails.getAuthoringInformation());
				voFamSupportNet.setIsCurrentlyActiveFamilySupport(Boolean.TRUE);
				voFamSupportNet.setPatient(form.getGlobalContext().Core.getPatientShort());
			}
			voFamSupportNet.setCarerName(familyRow.getColName());
			voFamSupportNet.setCarerRelationship(familyRow.getColRelationship());
			voFamSupportNet.setCarerHomePhone(familyRow.getColContact());
			if (familyRow.getColProgress() != null)
				voFamSupportNet.setDiscussProgress(new Boolean(familyRow.getColProgress().equals(YesNo.YES)));
			else
				voFamSupportNet.setDiscussProgress(Boolean.FALSE);

			voFamSupportNetColl.add(voFamSupportNet);
		}
		
		if(form.getLocalContext().getvoFamilySupportRemovedCollIsNotNull())
		{
			for(int i=0; i<form.getLocalContext().getvoFamilySupportRemovedColl().size(); i++)
			{
				voFamSupportNetColl.add(form.getLocalContext().getvoFamilySupportRemovedColl().get(i));
			}
		}
		
		form.getLocalContext().setvoFamilySupportColl(voFamSupportNetColl);
	}

	private void populateDataFromScreen(AdmissionDetailsVo voAdmissionDetails)
	{
	
		if(form.customControlAuthoringInfo().getValue()!=null && form.customControlAuthoringInfo().getValue().getAuthoringDateTimeIsNotNull()&& form.customControlAuthoringInfo().getValue().getAuthoringHcpIsNotNull())
		{
			voAdmissionDetails.setAuthoringInformation(form.customControlAuthoringInfo().getValue());
		}
		else
			voAdmissionDetails.setAuthoringInformation(null);
		if (form.ansDiagDiscussed().getValue() != null)
		{
			if (form.ansDiagDiscussed().getValue().getId() == YesNo.YES.getId())
				voAdmissionDetails.setWasDiagnosisDiscussed(Boolean.TRUE);
			else
				voAdmissionDetails.setWasDiagnosisDiscussed(Boolean.FALSE);
		}
		else
		{
			voAdmissionDetails.setWasDiagnosisDiscussed(null);
		}

		if (form.ansDNRComplete().getValue() != null)
		{
			if (form.ansDNRComplete().getValue().getId() == YesNo.YES.getId())
				voAdmissionDetails.setIsDnrFormCompleted(Boolean.TRUE);
			else
				voAdmissionDetails.setIsDnrFormCompleted(Boolean.FALSE);
		}
		else
		{
			voAdmissionDetails.setIsDnrFormCompleted(null);
		}
		voAdmissionDetails.setPatientAdmReason(form.txtPatient().getValue());
		voAdmissionDetails.setNursingAdmReason(form.txtNursing().getValue());
		voAdmissionDetails.setResusStatus(form.cmbResusStatus2().getValue());
		
		// communicaation needs
		voAdmissionDetails.setCommunicationNeeds(form.txtCommunication().getValue());
		
		//preferred language
		voAdmissionDetails.setPreferredLang(form.cmbPreferredLang().getValue());
		
		//Questions
		AdmissionDetailsQuestionsVoCollection voQuestions = voAdmissionDetails.getAdmQuestionsAns();
		
		if (voQuestions == null)
			voQuestions = new AdmissionDetailsQuestionsVoCollection();

		if (form.dynQuestions().getRows().size()>0)
		{
			for (int i=0; i<form.dynQuestions().getRows().size();i++)
			{				
				DynamicGridRow row = form.dynQuestions().getRows().get(i);
				
				boolean l_new = false;
				AdmissionDetailsQuestionsVo vo = questionRecorded(voQuestions,(AdmissionQuestion)row.getValue());
				int l_index = -1;
				
				if (vo == null)
				{
					vo = new AdmissionDetailsQuestionsVo();
					l_new = true;
				}
				else
				{
					l_index = questionRecordedIndex(voQuestions,(AdmissionQuestion)row.getValue());					
				}

				if (row.getValue() instanceof AdmissionQuestion)
					vo.setQuestion((AdmissionQuestion)row.getValue());

				if (row.getCells().get(form.dynQuestions().getColumns().get(1)).getValue() != null)
				{
					if (row.getCells().get(form.dynQuestions().getColumns().get(1)).getValue() instanceof YesNo)
					{
						vo.setAnswer((YesNo)row.getCells().get(form.dynQuestions().getColumns().get(1)).getValue());
					}
				}
				else
					vo.setAnswer(null);
				
				if (l_new)
				{
					if (vo.getQuestionIsNotNull())
						voQuestions.add(vo);
				}
				else
					voQuestions.set(l_index,vo);
				}
		}
		
		if (voQuestions.size() > 0)
			voAdmissionDetails.setAdmQuestionsAns(voQuestions);
		else
			voAdmissionDetails.setAdmQuestionsAns(null);
	}

	private AdmissionDetailsQuestionsVo questionRecorded(AdmissionDetailsQuestionsVoCollection voCol,AdmissionQuestion voLkup)
	{
		if (voCol == null)
			return null;
		
		for(int i=0;i<voCol.size();i++)
		{			
			if ((voCol.get(i).getQuestionIsNotNull() && voCol.get(i).getQuestion().equals(voLkup)))
				return voCol.get(i);
		}
		
		return null;
	}
	
	private int questionRecordedIndex(AdmissionDetailsQuestionsVoCollection voCol,AdmissionQuestion voLkup)
	{
		for(int i=0;i<voCol.size();i++)
		{
			if (voCol.get(i).getQuestion().equals(voLkup))
				return i;
		}		
		return -1;
	}
	
	protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
	{
		form.setMode(FormMode.VIEW);
		form.btnNew().setVisible(true);
		form.btnUpdate().setVisible(true);
		open();
		updateContextMenus();					//wdev-18694
	}

	protected void onContextMenuItemClick(int menuItemID, ims.framework.Control sender) throws ims.framework.exceptions.PresentationLogicException
	{
		if (sender == null)
			throw new CodingRuntimeException("sender is null : onContextMenuItemClick");

		if (sender.equals(form.grdFamily()))
		{
			switch (menuItemID)
			{
				case GenForm.ContextMenus.GenericGrid.Add :
					form.grdFamily().getRows().newRow();
					break;
				case GenForm.ContextMenus.GenericGrid.Remove :
					removeFamilySupport();
					break;
			}
		}
		else if (sender.equals(form.grdDiagnosis()))
		{
			switch (menuItemID)
			{
				case GenForm.ContextMenus.AdmissionSummaryMenu.VIEWDIAGNOSIS :
					viewDiagnosisItem(sender);
				break;

				case GenForm.ContextMenus.AdmissionSummaryMenu.VIEWPROCEDURE :
					viewProcedureItem(sender);
				break;

				case GenForm.ContextMenus.AdmissionSummaryMenu.NEWDIAGNOSIS :
					newDiagnosis();
				break;

				case GenForm.ContextMenus.AdmissionSummaryMenu.NEWPROCEDURE :
					newProcedure();
				break;
				default :
			}
		}
		updateContextMenus();
		enableDiagnosisProcedureGridContextMenu();
	}

	private void removeFamilySupport() 
	{
		if(form.getLocalContext().getvoFamilySupportCollIsNotNull() && form.grdFamily().getValue() != null)
		{
			for(int i =0; i<form.getLocalContext().getvoFamilySupportColl().size(); i++)
			{
				SupportNetworkFamily tempSupportNetworkFamily = form.getLocalContext().getvoFamilySupportColl().get(i);
				if(tempSupportNetworkFamily.equals(form.grdFamily().getValue()))
				{
					tempSupportNetworkFamily.setIsCurrentlyActiveFamilySupport(Boolean.FALSE);
					form.getLocalContext().getvoFamilySupportRemovedColl().add(tempSupportNetworkFamily);
				}
			}
		}
		
		form.grdFamily().getRows().remove(form.grdFamily().getSelectedRowIndex());
	}

	private void newProcedure()
	{
		setNewItemContextData();
		engine.open(form.getForms().Clinical.Procedures_Dialog);
	}

	private void newDiagnosis()
	{
		setNewItemContextData();
		engine.open(form.getForms().Clinical.DiagnosisComplications_Dialog);
	}

	private void setNewItemContextData()
	{
		form.getGlobalContext().Clinical.setReturnToFormName(engine.getFormName());
		form.getGlobalContext().Clinical.setReturnToFormMode(FormMode.EDIT);
	}

	private void viewProcedureItem(Control sender)
	{
		form.getGlobalContext().Clinical.setReturnToFormName(engine.getFormName());
		if (form.grdDiagnosis().getSelectedRow() != null && sender.equals(form.grdDiagnosis()))
		{
			ValueObject voVal = (ValueObject) form.grdDiagnosis().getValue();
			if (voVal != null)
			{
				if (voVal instanceof PatientProcedureShortVo)
				{
					form.getGlobalContext().Clinical.setSelectedPatientProcedureFromNursingAdmission((PatientProcedureShortVo)voVal);
					engine.open(form.getForms().Clinical.Procedures_Dialog);
					form.getGlobalContext().Clinical.setReturnToFormMode(FormMode.VIEW);
				}
			}
		}
	}

	private void viewDiagnosisItem(Control sender)
	{
		form.getGlobalContext().Clinical.setReturnToFormName(engine.getFormName());
		if (form.grdDiagnosis().getSelectedRow() != null && sender.equals(form.grdDiagnosis()))
		{
			ValueObject voVal = (ValueObject) form.grdDiagnosis().getValue();
			if (voVal != null)
			{
				if (voVal instanceof PatientDiagnosisShortVo)
				{
					form.getGlobalContext().Clinical.setSelectedPatientDiagnosisFromNursingAdmission((PatientDiagnosisShortVo)voVal);
					engine.open(form.getForms().Clinical.DiagnosisComplications_Dialog);
					form.getGlobalContext().Clinical.setReturnToFormMode(FormMode.VIEW);
				}
			}
		}
	}

	protected void onGrdFamilySelectionChanged() throws PresentationLogicException
	{
		updateContextMenus();
	}

	private void updateContextMenus()
	{
		if (form.getMode().equals(FormMode.EDIT))
		{
			form.getContextMenus().getGenericGridAddItem().setVisible(true);
			form.getContextMenus().getGenericGridRemoveItem().setVisible(form.grdFamily().getSelectedRowIndex() >= 0);	
		}
		else
		{
			form.getContextMenus().getGenericGridAddItem().setVisible(false);
			form.getContextMenus().getGenericGridRemoveItem().setVisible(false);
		}
	}

	protected void onGrdFamilyGridCheckBoxClicked(int column, grdFamilyRow row, boolean isChecked) throws PresentationLogicException
	{
	}

	protected void onGrdFamilyGridComboBoxSelectionChanged(int column, grdFamilyRow row, Object value) throws PresentationLogicException
	{
	}

	protected void onGrdDiagnosisSelectionChanged() throws PresentationLogicException
	{
		enableDiagnosisProcedureGridContextMenu();
	}

	
	private void enableDiagnosisProcedureGridContextMenu()
	{
		boolean canViewItem = canViewItem();
		boolean isEpisodeOfCare = form.getGlobalContext().Core.getEpisodeofCareShortIsNotNull();

		if (form.getMode().equals(FormMode.EDIT))
		{
			if (form.grdDiagnosis().getSelectedRow() != null)
			{
				
				ims.nursing.forms.nursingadmission.GenForm.grdDiagnosisRow row = form.grdDiagnosis().getSelectedRow();
				
				if (row.getValue() instanceof PatientDiagnosisShortVo)
				{				
					form.getContextMenus().getAdmissionSummaryMenuVIEWDIAGNOSISItem().setVisible(canViewItem);
					form.getContextMenus().getAdmissionSummaryMenuVIEWPROCEDUREItem().setVisible(false);
					form.getContextMenus().getAdmissionSummaryMenuNEWDIAGNOSISItem().setVisible(isEpisodeOfCare);
					form.getContextMenus().getAdmissionSummaryMenuNEWPROCEDUREItem().setVisible(isEpisodeOfCare);
				}
				
				if (row.getValue() instanceof PatientProcedureShortVo)
				{				
					form.getContextMenus().getAdmissionSummaryMenuVIEWDIAGNOSISItem().setVisible(false);
					form.getContextMenus().getAdmissionSummaryMenuVIEWPROCEDUREItem().setVisible(canViewItem);
					form.getContextMenus().getAdmissionSummaryMenuNEWDIAGNOSISItem().setVisible(isEpisodeOfCare);
					form.getContextMenus().getAdmissionSummaryMenuNEWPROCEDUREItem().setVisible(isEpisodeOfCare);
				}
				
			}
			else
			{
				form.getContextMenus().getAdmissionSummaryMenuVIEWDIAGNOSISItem().setVisible(false);
				form.getContextMenus().getAdmissionSummaryMenuVIEWPROCEDUREItem().setVisible(false);
				form.getContextMenus().getAdmissionSummaryMenuNEWDIAGNOSISItem().setVisible(isEpisodeOfCare);
				form.getContextMenus().getAdmissionSummaryMenuNEWPROCEDUREItem().setVisible(isEpisodeOfCare);
			}
		}
		else
		{
			form.getContextMenus().getAdmissionSummaryMenuVIEWDIAGNOSISItem().setVisible(false);
			form.getContextMenus().getAdmissionSummaryMenuVIEWPROCEDUREItem().setVisible(false);
			form.getContextMenus().getAdmissionSummaryMenuNEWDIAGNOSISItem().setVisible(false);
			form.getContextMenus().getAdmissionSummaryMenuNEWPROCEDUREItem().setVisible(false);
		}
	}

	private boolean canViewItem()
	{
		return form.getGlobalContext().Core.getCurrentClinicalContactIsNotNull() || form.getGlobalContext().Core.getCurrentCareContextIsNotNull() || form.getGlobalContext().Core.getEpisodeofCareShortIsNotNull();
	}

	protected void onFormModeChanged()
	{
		if(form.getMode().equals(FormMode.EDIT))
		{
			if (form.getLocalContext().getvoAdmissionDetailsIsNotNull() && 
					form.getLocalContext().getvoAdmissionDetails().getID_AdmissionDetails() == null)					
				form.setcustomControlAuthoringInfoEnabled(true);
			else if (form.getLocalContext().getvoAdmissionDetails() == null)
				form.setcustomControlAuthoringInfoEnabled(true);
			else
				form.setcustomControlAuthoringInfoEnabled(false);
		}
		
		for (int i=0;i<form.grdFamily().getRows().size();i++)
		{
			form.grdFamily().getRows().get(i).setColContactReadOnly(true);
			form.grdFamily().getRows().get(i).setColNameReadOnly(true);
			form.grdFamily().getRows().get(i).setColRelationshipReadOnly(true);
		}
		enableDiagnosisProcedureGridContextMenu();
	}

	//WDEV-2503 
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException
	{
		form.getGlobalContext().Clinical.setReturnToFormMode(FormMode.VIEW);
		
		populateDiagProcedureGrid();
		
		enableDiagnosisProcedureGridContextMenu();
	}
}
