/FileExtraction/Java_unseen/IMS-MAXIMS_openMAXIMS/Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/skinbodychart/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 Callum Wells using IMS Development Environment (version 1.20 build 40805.900)
// Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.

package ims.nursing.forms.skinbodychart;

import ims.admin.vo.AppImageVo;
import ims.core.vo.DrawingAreaVo;
import ims.core.vo.DrawingGroupVo;
import ims.core.vo.DrawingImageVo;
import ims.core.vo.DrawingImageVersionVo;
import ims.core.vo.HcpLiteVo;
import ims.core.vo.MemberOfStaffShortVo;
import ims.nursing.vo.AssessmentComponent;
import ims.nursing.vo.SkinAssessment;
import ims.nursing.vo.SkinAssessmentFindings;
import ims.nursing.vo.SkinAssessmentFindingsCollection;
import ims.nursing.vo.SkinAssessmentReview;
import ims.nursing.vo.SkinAssessmentReviewCollection;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.FormName;
import ims.framework.controls.DrawingControlArea;
import ims.framework.controls.DrawingControlAreaCollection;
import ims.framework.controls.DrawingControlGroup;
import ims.framework.controls.DrawingControlGroupCollection;
import ims.framework.controls.DrawingControlShape;
import ims.framework.enumerations.DialogResult;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.PresentationLogicException;
import ims.framework.utils.Date;
import ims.framework.utils.DateFormat;
import ims.framework.utils.DateTime;
import ims.framework.utils.Time;
import ims.framework.utils.TimeFormat;
import ims.nursing.vo.lookups.SkinWoundType;
import ims.coe.vo.AssessmentSkin;
import ims.nursing.vo.AssessmentHeaderInfo;
import ims.nursing.vo.lookups.PainStatus;
import ims.spinalinjuries.vo.NurAssessmentSkinVo;

public class Logic extends BaseLogic
{
	protected void onFormOpen() throws ims.framework.exceptions.FormOpenException
	{
		clearContext();
		
		if(isSkinBodyChartDialog())
		{
			form.setMode(FormMode.VIEW);
		}
		
		if(open(true))
		{
			form.drawingBodyChart().setPrintSubTitle("Skin - Body Chart");
			if(form.getGlobalContext().Core.getPatientShortIsNotNull())
			{
				form.drawingBodyChart().setPrintTitle(form.getGlobalContext().Core.getPatientShort().getPatientInfo());
			}
			if(form.getGlobalContext().Nursing.getAssessmentComponent() != null)
			{
				AssessmentComponent comp = null;
				if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentSkin)
				{
					comp = (AssessmentSkin)form.getGlobalContext().Nursing.getAssessmentComponent();
					if (((AssessmentSkin)comp).getSkinAssessment() == null)
					{
						try 
						{
							onBNewClick();
						} 
						catch (PresentationLogicException e){displayError(e.getMessage());}
					}
				}	
				else if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof NurAssessmentSkinVo)
				{
					comp = (NurAssessmentSkinVo)form.getGlobalContext().Nursing.getAssessmentComponent();
					if (((NurAssessmentSkinVo)comp).getSkinAssessment() == null)
					{
						try 
						{
							onBNewClick();
						} 
						catch (PresentationLogicException e){displayError(e.getMessage());}
					}
				}
			}
			else
				form.setMode(FormMode.VIEW);
		}
		else
		{
			form.setMode(FormMode.VIEW);
			form.bNew().setEnabled(false);
		}
		if( form.getGlobalContext().Core.getAssessmentIsReadOnly() != null && form.getGlobalContext().Core.getAssessmentIsReadOnly() == true )
		{
			form.setMode(FormMode.VIEW);
			form.drawingBodyChart().setEnabled(false);
			form.bNew().setVisible(false);
			form.btnClose().setVisible(true);
			form.btnClose().setEnabled(true);
			
		}
	}

	protected void onBSkinReviewClick()
	{
		engine.open(form.getForms().Nursing.SkinReview);
	}
	
	protected void onBSaveClick() throws ims.framework.exceptions.PresentationLogicException
	{
		SkinAssessment skinAssVO =  form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO();
		SkinAssessment skinAssVOBackup = skinAssVO != null?(SkinAssessment)skinAssVO.clone():null;
		try {
			if(form.dateAssess().getValue() == null)
			{
				displayError("Please enter Assessment date");
				return;
			}
			if(form.timeAssess().getValue() == null)
			{
				displayError("Please enter Assessment time");
				return;
			}
			
			//Set the Date, Time & the HCP
			skinAssVO.setDateTimeInitiated(new DateTime(form.dateAssess().getValue(), form.timeAssess().getValue()));
			
			Object hcpLite = domain.getHcpLiteUser();
			skinAssVO.setHcpInitiated(hcpLite != null ? ((HcpLiteVo)hcpLite) : null);
			
			skinAssVO.setIsSkinIntact(new Boolean(form.chkSkinIntact().getValue()));

			//Get the findings with no details on them
			getFindingsNoDetails(skinAssVO);
			
			//Don't allow to save if there are no findings
			if(!activeFindings(skinAssVO) && !form.chkSkinIntact().getValue())
			{
				displayError("Please enter at least one finding before saving");
				return;
			}
			
			//Clear the findingsID for the findings brought from the previous record
			for(int i=0; i<skinAssVO.getSkinAssessmentFindings().size(); i++)
			{
				skinAssVO.getSkinAssessmentFindings().get(i).setID_SkinAssessmentFindings(null);
				
				if(skinAssVO.getSkinAssessmentFindings().get(i).getSkinAssessmentReviewIsNotNull())
				{
					for (int j = 0; j < skinAssVO.getSkinAssessmentFindings().get(i).getSkinAssessmentReview().size(); j++)
					{
						skinAssVO.getSkinAssessmentFindings().get(i).getSkinAssessmentReview().get(j).setID_SkinAssessmentReview(null);
					}
				}
			}
			
			if (skinAssVO.getClinicalContact() == null)
				skinAssVO.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
			
			if (skinAssVO.getCareContext() == null)
				skinAssVO.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
			
			String[] errors = skinAssVO.validate();
			if(errors != null)
			{
				engine.showErrors(errors);
				//12/09/2005 - Restore the vo to the context if the validation fails
				form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(skinAssVOBackup);
				return;
			}
		
			// If there is an assesment component in the global context, we want to save that too!
			if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
			{
				if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentSkin)
				{ 
					AssessmentSkin comp = (AssessmentSkin)form.getGlobalContext().Nursing.getAssessmentComponent();
					comp.setSkinAssessment(skinAssVO);
					String[] arrErrors = comp.validate();
					if(arrErrors != null)
					{
						engine.showErrors("Validation Errors", arrErrors);
						return;
					}
					AssessmentHeaderInfo headerInfo = domain.saveRecord(skinAssVO, form.getGlobalContext().Nursing.getAssessmentHeaderInfo(), comp);
					// Go back to the mobility form
					form.getGlobalContext().Nursing.setAssessmentHeaderInfo(headerInfo);
					engine.open(form.getForms().COE.AssessSkin);
					return;
				}
				else if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof NurAssessmentSkinVo)
				{ 
					NurAssessmentSkinVo comp = (NurAssessmentSkinVo)form.getGlobalContext().Nursing.getAssessmentComponent();
					comp.setSkinAssessment(skinAssVO);
					String[] arrErrors = comp.validate();
					if(arrErrors != null)
					{
						engine.showErrors("Validation Errors", arrErrors);
						return;
					}
					AssessmentHeaderInfo headerInfo = domain.saveRecord(skinAssVO, form.getGlobalContext().Nursing.getAssessmentHeaderInfo(), comp);
					
					form.getGlobalContext().Nursing.setAssessmentHeaderInfo(headerInfo);
					
					if(isSkinBodyChartDialog())
					{
						engine.close(DialogResult.OK);
						return;
					}
					
					engine.open(form.getForms().SpinalInjuries.NurAssessmentSkin);
					return;
				}
			}
			else
				domain.saveRecord(skinAssVO, null, null);
		} 
		catch (StaleObjectException e) 
		{
			displayError(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
		}
		
		open();
		form.setMode(FormMode.VIEW);
	}
	
	private void getPreviousFindings(SkinAssessment skinAssVO)
	{
		if(form.getLocalContext().getPreviousSkinAssessment() != null && form.getLocalContext().getPreviousSkinAssessment().getSkinAssessmentFindings() != null)
		{
			SkinAssessmentFindings findingVO;
			for(int i=0; i<form.getLocalContext().getPreviousSkinAssessment().getSkinAssessmentFindings().size(); i++)
			{
				findingVO = (SkinAssessmentFindings)form.getLocalContext().getPreviousSkinAssessment().getSkinAssessmentFindings().get(i).clone();
				//Skip the discontinued
				if(findingVO.getIsDiscontinuedAssess() != null && 
						findingVO.getIsDiscontinuedAssess().booleanValue())
					continue;
				
				//Set the continued assessment
				findingVO.setIsContinuedAssessment(new Boolean(true));
				skinAssVO.getSkinAssessmentFindings().add(findingVO);				
			}		
		}
	}
	
	//adds having no details
	private void getFindingsNoDetails(SkinAssessment skinAssVO)
	{
		SkinAssessmentFindings findingVO;
		DrawingControlShape shape;
		boolean bShapeSaved;
		 
		for(int j=0; j<form.drawingBodyChart().getShapes().size(); j++)
		{
			bShapeSaved = false;
			shape = (DrawingControlShape) form.drawingBodyChart().getShapes().get(j);
			
			for(int k=0; k<skinAssVO.getSkinAssessmentFindings().size(); k++)
			{
				if(skinAssVO.getSkinAssessmentFindings().get(k).getID_SkinAssessmentFindingsIsNotNull() && 
				   skinAssVO.getSkinAssessmentFindings().get(k).getID_SkinAssessmentFindings().intValue() == shape.getIndex())
				{
					bShapeSaved = true;
					break;
				}
			}
			//Add a new finding with the sape which doesn't have details
			if(!bShapeSaved)
			{
				findingVO = new SkinAssessmentFindings();
				findingVO.setSiteName(getAreaName(shape.getTargetID()));
				findingVO.setWoundType(getWoundType(shape.getBrushID()));
//				findingVO.setSiteIndex(new Integer(shape.getIndex()));
				findingVO.setSiteImage(shape.getVML());
				findingVO.setIsDiscontinuedAssess(new Boolean(false));
				
				//create a new review from findings
				/*
				findingVO.setSkinAssessmentReview(new SkinAssessmentReviewCollection());
				SkinAssessmentReview sarVO = getReviewVOfromFindingVO(findingVO);
				sarVO.setDateTimeReview(new DateTime(form.dateAssess().getValue(), form.timeAssess().getValue()));
				if(domain.getHcpUser() != null)
					skinAssVO.setHcpInitiated((Hcp)domain.getHcpUser());
				findingVO.getSkinAssessmentReview().add(sarVO);

				skinAssVO.getSkinAssessmentFindings().add(findingVO);
				*/
			}
		}
	}
	
	protected void onBNewClick() throws ims.framework.exceptions.PresentationLogicException
	{	
		DateTime now = new DateTime(new Date(), new Time());
		
		if ((form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVOIsNotNull()) && form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO().getCareContext().equals(form.getGlobalContext().Core.getCurrentCareContext()))
		{
			
			SkinAssessment lastSkinAssessment = form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO();
			
			if(lastSkinAssessment.getDateTimeInitiatedIsNotNull() 
			&& lastSkinAssessment.getDateTimeInitiated().getDate().equals(now.getDate()) 
			&& lastSkinAssessment.getDateTimeInitiated().getTime().equals(now.getTime())) 
			{
				engine.showMessage("An assessment already exists for " + now);
				return;
			}
			else
				populateControls();
		}
		else if (form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVOIsNotNull())
		{ 
			form.getGlobalContext().Core.setYesNoDialogMessage("Do you wish to copy this assessment?");
			engine.open(form.getForms().Core.YesNoDialog,false);
		}
		else
		{
			populateControls();
		}
	}
	
	protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException 
	{
		if(formName.equals(form.getForms().Nursing.SkinReviewDialog))
		{
			if(result.equals(DialogResult.OK))
			{
				SkinAssessment skinAssVO = form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO();
				if(skinAssVO != null)
				{
					//we have to create a dummy SkinAssessmentReview to keep the DateTimeReview for SkinAssessmentFindings
					SkinAssessmentFindings safVO = form.getGlobalContext().COE.SkinBodyChart.getFindingsVO();
					
					if(safVO != null)
					{
						if(safVO.getSkinAssessmentReview() == null)
							safVO.setSkinAssessmentReview(new SkinAssessmentReviewCollection());
						
						if(safVO.getSkinAssessmentReview().size() == 0 || reviewEdited(safVO))
						{
							SkinAssessmentReview sarVO = getReviewVOfromFindingVO(safVO);
							
							sarVO.setDateTimeReview(new DateTime(form.dateAssess().getValue(), form.timeAssess().getValue()));
							
							MemberOfStaffShortVo memStaffShortVo = (MemberOfStaffShortVo)domain.getMosUser();
							if(memStaffShortVo != null && memStaffShortVo.getHcp() != null)
								sarVO.setHCPReview(memStaffShortVo.getHcp());
							
							int reviewIndex = safVO.getSkinAssessmentReview().indexOf(sarVO);
							if(reviewIndex >= 0)
								safVO.getSkinAssessmentReview().set(reviewIndex, sarVO);
							else
								safVO.getSkinAssessmentReview().add(sarVO);
								
							form.getGlobalContext().COE.SkinBodyChart.setFindingsVO(safVO);
						}
					}
					
					int index = skinAssVO.getSkinAssessmentFindings().indexOf(form.getGlobalContext().COE.SkinBodyChart.getFindingsVO());
					if(index >=0)
					{
						skinAssVO.getSkinAssessmentFindings().remove(index);
						if(skinAssVO.getSkinAssessmentFindings() == null)
							skinAssVO.setSkinAssessmentFindings(new SkinAssessmentFindingsCollection());
						skinAssVO.getSkinAssessmentFindings().add(form.getGlobalContext().COE.SkinBodyChart.getFindingsVO());
					}
					else
						skinAssVO.getSkinAssessmentFindings().add(form.getGlobalContext().COE.SkinBodyChart.getFindingsVO());
					
					form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(skinAssVO);
				}
			}
			else if(result.equals(DialogResult.CANCEL))
			{
				//Find if the user clicked Cancel for the first Time (was changing his mind)
				//and warn the user to clear the drawing
				SkinAssessment skinAssVO = form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO();
				if(skinAssVO != null)
				{
					int index = skinAssVO.getSkinAssessmentFindings().indexOf(form.getGlobalContext().COE.SkinBodyChart.getFindingsVO());
					if(index < 0)
					{
						displayError("Please select the previous image and remove it.");
					}
				}
			}
		}
		else if(formName.equals(form.getForms().Core.YesNoDialog))
		{
			if(result.equals(DialogResult.YES))
				//copy previous assessment
				copyLastAssessment();
			else
			{
				form.getGlobalContext().COE.SkinBodyChart.setAreas(null);
				form.getGlobalContext().COE.SkinBodyChart.setFindingsVO(null);
				form.getGlobalContext().COE.SkinBodyChart.setGroups(null);
				form.getGlobalContext().COE.SkinBodyChart.setSelectedSkinAssessment(null);
				form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(null);
				
				clearControls();
			}
			
			populateControls();
			
		}

	}
	private void populateControls()
	{		
		//Prepopulate Controls
		if(domain.getMosUser() != null)
			form.textBoxHCP().setValue(((MemberOfStaffShortVo)domain.getMosUser()).toString());
				
		form.dateAssess().setValue(new Date());
		form.timeAssess().setValue(new Time());
		form.chkSkinIntact().setValue(false);
		
		//Save the previous Assessment
		form.getLocalContext().setPreviousSkinAssessment(form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO());
		
		SkinAssessment skinAssVO = new SkinAssessment();
		DrawingImageVersionVo drawingVO =  new DrawingImageVersionVo();
		//Set the Current Image Name & Version No
		drawingVO.setImageName(getCurrentImageName());
		if(getCurrentVersionNumber() != null)
			drawingVO.setVersionNumber(getCurrentVersionNumber());
		skinAssVO.setImageVersion(drawingVO);
		
		skinAssVO.setSkinAssessmentFindings(new SkinAssessmentFindingsCollection());
		//Copy the previous Findings
		getPreviousFindings(skinAssVO);
		
		//Set back to the context the SkinAssVO
		form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(skinAssVO);
		form.bNew().setEnabled(false);
		form.setMode(FormMode.EDIT);
		
	}
	private void copyLastAssessment()
	{
		SkinAssessment voSkinAssessment = form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO();
		SkinAssessment newSkinAssessment = new SkinAssessment();
		
		if (newSkinAssessment.getClinicalContact() == null)
			newSkinAssessment.setClinicalContact(form.getGlobalContext().Core.getCurrentClinicalContact());
		
		if (newSkinAssessment.getCareContext() == null)
			newSkinAssessment.setCareContext(form.getGlobalContext().Core.getCurrentCareContext());
		
		if (voSkinAssessment.getSkinAssessmentFindingsIsNotNull())
		{
			SkinAssessmentFindingsCollection voCollFindings = new SkinAssessmentFindingsCollection();
			
			for (int i = 0; i < voSkinAssessment.getSkinAssessmentFindings().size(); i++)
			{
				if (voSkinAssessment.getSkinAssessmentFindings().get(i).getIsDiscontinuedAssessIsNotNull() && !voSkinAssessment.getSkinAssessmentFindings().get(i).getIsDiscontinuedAssess().booleanValue())
				{					
					SkinAssessmentFindings voFinding = voSkinAssessment.getSkinAssessmentFindings().get(i);
					
					//force copy of finding
					voFinding.setID_SkinAssessmentFindings(null);
					
					if (voFinding.getSkinAssessmentReviewIsNotNull())
					{
						//force copy of reviews
						for(int j = 0; j < voFinding.getSkinAssessmentReview().size(); j++)
							voFinding.getSkinAssessmentReview().get(j).setID_SkinAssessmentReview(null);							
					}			
					
					voCollFindings.add(voFinding);
				}
			}
			
			newSkinAssessment.setSkinAssessmentFindings(voCollFindings);
		}
		else
			newSkinAssessment.setSkinAssessmentFindings(null);
		
		
		form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(newSkinAssessment);
	}
	protected void onDrawingBodyChartNote(DrawingControlShape shape) throws PresentationLogicException 
	{
		//Create a new Finding
		SkinAssessment skinAssVO = form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO();
		boolean siteFound = false;
		SkinAssessmentFindings findingVO = null;
		
		if(skinAssVO != null)
		{
			for(int i=0; i<skinAssVO.getSkinAssessmentFindings().size(); i++)
			{
				//check if it has the same shape
				if(skinAssVO.getSkinAssessmentFindings().get(i).getID_SkinAssessmentFindingsIsNotNull() &&
				   skinAssVO.getSkinAssessmentFindings().get(i).getID_SkinAssessmentFindings().intValue() == shape.getIndex() )
				{
					if(shape.getTargetID() == savedTargetID)					
					{
						displayError("You are not allowed to update an existing finding");
						return;
					}
					else
					{
						findingVO = skinAssVO.getSkinAssessmentFindings().get(i);
						//02/11/2005 - Update the drawing (uml) as it might have been edited
						findingVO.setSiteImage(shape.getVML());
						skinAssVO.getSkinAssessmentFindings().set(i,findingVO);
						siteFound = true;
						break;
					}
				}
			}
		}
		
		//Obsolete check - only if the spec changes and allows updating an existing finding
		if(!siteFound)
		{
			findingVO = new SkinAssessmentFindings();
			findingVO.setSiteName(getAreaName(shape.getTargetID()));
			findingVO.setWoundType(getWoundType(shape.getBrushID()));
			findingVO.setID_SkinAssessmentFindings(new Integer(shape.getIndex()));
			findingVO.setSiteImage(shape.getVML());
			findingVO.setIsDiscontinuedAssess(new Boolean(false));
		}
								
		//Set back to the context the SkinAssVO and the assFindingVO
		form.getGlobalContext().COE.SkinBodyChart.setFindingsVO(findingVO);
		if(form.dateAssess().getValue() != null && form.timeAssess().getValue() != null)
			skinAssVO.setDateTimeInitiated(new DateTime(form.dateAssess().getValue(), form.timeAssess().getValue()));	
		
		Object hcpLite = domain.getHcpLiteUser();
		skinAssVO.setHcpInitiated(hcpLite != null ? ((HcpLiteVo)hcpLite) : null);

		form.getGlobalContext().COE.SkinBodyChart.setSelectedSkinAssessment(skinAssVO);
		engine.open(form.getForms().Nursing.SkinReviewDialog);
	}
	
	protected void onDrawingBodyChartRemoved(int index) throws PresentationLogicException 
	{
		SkinAssessment skinAssVO = form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO();
		SkinAssessmentFindings findingVO;
		if(skinAssVO != null)
		{
			for(int i=0; i<skinAssVO.getSkinAssessmentFindings().size(); i++)
			{
				findingVO = skinAssVO.getSkinAssessmentFindings().get(i);
				if(findingVO.getID_SkinAssessmentFindingsIsNotNull() && findingVO.getID_SkinAssessmentFindings().intValue() == index)
				{
					if(recordSaved(findingVO.getID_SkinAssessmentFindings()))
					{
						displayError("Previous saved Findings cannot be updated");
						//Redraw the shape
						DrawingControlShape shape = new DrawingControlShape(findingVO.getID_SkinAssessmentFindings().intValue(), savedTargetID, findingVO.getSiteImage(), findingVO.getWoundType().getId(), true);
						form.drawingBodyChart().addShape(shape);
						return;
					}
					else
					{
						skinAssVO.getSkinAssessmentFindings().remove(i);
						form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(skinAssVO);
						return;
					}
				}
			}
		}
	}
	
	private void initialiseDrawingControl(boolean bInitCtrl)
	{
		if(bInitCtrl)
		{
			form.drawingBodyChart().setImage(form.getImages().COE.BodyChart);
			for(int i=0; i<SkinWoundType.getNegativeInstances().length; i++)
				form.drawingBodyChart().addBrush(SkinWoundType.getNegativeInstances()[i].getId(), SkinWoundType.getNegativeInstances()[i].getText(), SkinWoundType.getNegativeInstances()[i].getColor());
			
			//load the image associated image to this Form				
			AppImageVo voAppImage = new AppImageVo();
			voAppImage.setID_AppImage(new Integer(form.getImages().COE.BodyChart.getImageId()));
			
			
			DrawingImageVo voImage = new DrawingImageVo();
			//TODO: Leave till COE release of 03/03/05 has gone
			voImage.setImage(voAppImage);

			voImage.setImageName(getCurrentImageName());
			//When no version no - the domain will return getLast()
			if(getCurrentVersionNumber() != null)
				voImage.setVersionNumber(getCurrentVersionNumber());
			
			DrawingImageVo voImageRetrieved = domain.getDrawingImage(voImage);
			
			if (voImageRetrieved != null)
			{
				DrawingControlGroup rootNode = new DrawingControlGroup(voImageRetrieved.getRootGroup().getGroupID().intValue(), voImageRetrieved.getRootGroup().getGroupName());
				convertAllAreasToNode(voImageRetrieved.getRootGroup(), rootNode);
				form.drawingBodyChart().setAreas(rootNode);
				form.getGlobalContext().COE.SkinBodyChart.setAreas(rootNode.getAllAreas());
				form.getGlobalContext().COE.SkinBodyChart.setGroups(getAllGroups(rootNode));
				form.getLocalContext().setImageLoaded(new Boolean(true));
				form.getLocalContext().setCurrentVersionNo(voImageRetrieved.getVersionNumber());
				
				form.getLocalContext().setImageLoaded(new Boolean(true));
			
			}
			else
			{
				DrawingControlGroup root = new DrawingControlGroup(-1, "Body Chart");
				form.drawingBodyChart().setAreas(root);
				form.getLocalContext().setImageLoaded(new Boolean(false));
				engine.showMessage("No active image available");
			}
		}
	}
	
	private String getCurrentImageName()
	{
		if(form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO() != null && 
		   form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO().getImageVersion() != null)
			return form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO().getImageVersion().getImageName();
		
		//TODO - change this hard code to get the last Image when will be available
		return "Body Chart Assessment";
	}
	
	//Returns the saved version number or the getLast version
	private Integer getCurrentVersionNumber()
	{
		if(form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO() != null && 
		   form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO().getImageVersion() != null)
			return form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO().getImageVersion().getVersionNumber();
		
		return form.getLocalContext().getCurrentVersionNo(); 
	}
	
	private void convertAllAreasToNode(DrawingGroupVo voGroup,DrawingControlGroup node)
	{
		node.setName(voGroup.getGroupName());
		//convert all areas to controlgroup
		int i;
		for(i=0;i<voGroup.getAreaCollection().size();i++)
		{
			node.add(createDrawingControlArea(voGroup.getAreaCollection().get(i)));
		}
		
		for(int j=0;j<voGroup.getChildGroups().size();j++)
		{
			DrawingGroupVo  childGroup = voGroup.getChildGroups().get(j);
			node.add(createDrawingControlGroup(childGroup));
			convertAllAreasToNode(childGroup, node.getGroup(i+j));
		}	
	}
	
	private DrawingControlGroup createDrawingControlGroup(DrawingGroupVo voGroup) 
	{
		DrawingControlGroup group = new DrawingControlGroup(voGroup.getGroupID().intValue(),voGroup.getGroupName());
		return group;
	}

	private DrawingControlArea createDrawingControlArea(DrawingAreaVo voArea) 
	{
		DrawingControlArea area = new DrawingControlArea(voArea.getAreaID().intValue(),voArea.getAreaName(),voArea.getAreaVectors());
		return area;
	}
	private boolean open()
	{
		return open(false);
	}
	private boolean open(boolean bInitDrawingCtrl)
	{
		clearControls();
		boolean bDisplayInactive = false, bImageLoaded;
		if(form.getGlobalContext().COE.SkinBodyChart.getReadOnlyAssessment() != null)
		{
	 		form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(form.getGlobalContext().COE.SkinBodyChart.getReadOnlyAssessment());
	 		form.getGlobalContext().COE.SkinBodyChart.setReadOnlyAssessment(null);
	 		form.bNew().setEnabled(false);
	 		bDisplayInactive = true;
	 	}
		else if (form.getGlobalContext().Nursing.getAssessmentComponent() != null && form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentSkin) // Came from the Pain Assessment screen
		{
			AssessmentSkin comp = (AssessmentSkin)form.getGlobalContext().Nursing.getAssessmentComponent();
			if (comp.getSkinAssessment() != null)
			{
				form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(comp.getSkinAssessment());
				//Clear Context
				form.getGlobalContext().COE.SkinBodyChart.setReadOnlyAssessment(null);
				form.bNew().setEnabled(false);
				bDisplayInactive = true;
			}
			else
			{
				form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(domain.getLastSkinAssessmentByCareContext(form.getGlobalContext().Core.getCurrentCareContext()));
				form.bNew().setEnabled(true);
			}
		}
		else if (form.getGlobalContext().Nursing.getAssessmentComponent() != null && form.getGlobalContext().Nursing.getAssessmentComponent() instanceof NurAssessmentSkinVo) // Came from the Pain Assessment screen
		{
			NurAssessmentSkinVo comp = (NurAssessmentSkinVo)form.getGlobalContext().Nursing.getAssessmentComponent();
			if (comp.getSkinAssessment() != null)
			{
				form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(comp.getSkinAssessment());
				//Clear Context
				form.getGlobalContext().COE.SkinBodyChart.setReadOnlyAssessment(null);
				form.bNew().setEnabled(false);
				bDisplayInactive = true;
			}
			else
			{
				form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(domain.getLastSkinAssessmentByCareContext(form.getGlobalContext().Core.getCurrentCareContext()));	
				form.bNew().setEnabled(true);
			}
		}
		else
		{
			form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(domain.getLastSkinAssessmentByPatient(form.getGlobalContext().Core.getPatientShort().getID_Patient()));
			form.bNew().setEnabled(true);
		}
		
		initialiseDrawingControl(bInitDrawingCtrl);
		bImageLoaded = form.getLocalContext().getImageLoaded() != null && form.getLocalContext().getImageLoaded().booleanValue()?true:false;
		if(bImageLoaded)
		{
			populateControls(bDisplayInactive);
		}
		else
		{
			//displayError("No area defined.");
			return false;
		}
		
		return true;
	}
	
	private void populateControls(boolean bDisplayInactive)
	{
		SkinAssessment skinAssVO = form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO();
		form.drawingBodyChart().clearShapes();
		if(skinAssVO != null)
		{
			//Populate Drawing Chart
			DrawingControlShape shape;
			
			for(int i=0; i<skinAssVO.getSkinAssessmentFindings().size(); i++)
			{
				//Skip the discontinued assessments
				if(!bDisplayInactive && skinAssVO.getSkinAssessmentFindings().get(i).getIsDiscontinuedAssess() != null && 
				   skinAssVO.getSkinAssessmentFindings().get(i).getIsDiscontinuedAssess().booleanValue())
					continue;

				if(skinAssVO.getSkinAssessmentFindings().get(i).getWoundTypeIsNotNull() && 
				   skinAssVO.getSkinAssessmentFindings().get(i).getID_SkinAssessmentFindingsIsNotNull())
				{
					shape = new DrawingControlShape(
					skinAssVO.getSkinAssessmentFindings().get(i).getID_SkinAssessmentFindings().intValue(),
					savedTargetID,
					skinAssVO.getSkinAssessmentFindings().get(i).getSiteImage(), 
					skinAssVO.getSkinAssessmentFindings().get(i).getWoundType().getId(),
					true,
					getTooltip(skinAssVO, skinAssVO.getSkinAssessmentFindings().get(i)));
				
					form.drawingBodyChart().addShape(shape);
				}
			}
			
			//Populate the rest of the controls
			if(skinAssVO.getDateTimeInitiated() != null)
			{
				if(skinAssVO.getDateTimeInitiated().getDate() != null)
					form.dateAssess().setValue(skinAssVO.getDateTimeInitiated().getDate());
				if(skinAssVO.getDateTimeInitiated().getTime() != null)
					form.timeAssess().setValue(skinAssVO.getDateTimeInitiated().getTime());
			}
			if(skinAssVO.getHcpInitiated() != null)
				form.textBoxHCP().setValue(skinAssVO.getHcpInitiated().toString());
			if(skinAssVO.getIsSkinIntact() != null)
			{
				form.chkSkinIntact().setValue(skinAssVO.getIsSkinIntact().booleanValue());
				form.drawingBodyChart().setEnabled(false);
			}
		}
	}
	
	private SkinWoundType getWoundType(int brushID)
	{
		for(int i=0; i<SkinWoundType.getNegativeInstances().length; i++)
			if(SkinWoundType.getNegativeInstances()[i].getId() == brushID)
				return SkinWoundType.getNegativeInstances()[i];
			
		return SkinWoundType.PRESSURESORE;
	}
	
	private void displayError(String error)
	{
		engine.showMessage(error);
	}

	protected void onBtnCancelClick() throws PresentationLogicException 
	{
		if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
		{
			if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentSkin)
			{
				engine.open(form.getForms().COE.AssessSkin);
				return;
			}
			else if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof NurAssessmentSkinVo)
			{
				if(isSkinBodyChartDialog())
				{
					engine.close(DialogResult.CANCEL);
					return;
				}
				
				engine.open(form.getForms().SpinalInjuries.NurAssessmentSkin);
				return;
			}
		}
		open();
		form.setMode(FormMode.VIEW);
	}
	private void clearControls()
	{
		form.textBoxHCP().setValue("");
		form.timeAssess().setValue(null);
		form.dateAssess().setValue(null);
		form.chkSkinIntact().setValue(false);
		form.drawingBodyChart().clearShapes();
	}

	protected void onFormModeChanged() 
	{
		if(form.getMode().equals(FormMode.EDIT))
		{
			if(form.chkSkinIntact().getValue())
				form.drawingBodyChart().setReadOnly(true);
			else
				form.drawingBodyChart().setReadOnly(false);
			
			form.btnClose().setVisible(false);
		}
		else
		{
			form.drawingBodyChart().setReadOnly(true);
			if(isAssementComponent())
				form.btnClose().setVisible(true);
			else
				form.btnClose().setVisible(false);
			
			if( form.getGlobalContext().Core.getAssessmentIsReadOnly() != null && form.getGlobalContext().Core.getAssessmentIsReadOnly() == true )
				form.btnClose().setVisible(true);	
		}
		
		form.bNew().setVisible(form.getMode().equals(FormMode.VIEW)); //WDEV-15195
	}
	
	private boolean activeFindings(SkinAssessment skinAssVO)
	{
		if(skinAssVO != null && 
		   skinAssVO.getSkinAssessmentFindings() != null)
		{
			for(int i=0; i<skinAssVO.getSkinAssessmentFindings().size(); i++)
				if(skinAssVO.getSkinAssessmentFindings().get(i).getIsDiscontinuedAssess() != null && 
				   skinAssVO.getSkinAssessmentFindings().get(i).getIsDiscontinuedAssess().booleanValue())
					continue;
				else
					return true;
		}
		
		return false;
	}
	
	private String getTooltip(SkinAssessment skinAssessment, SkinAssessmentFindings findingVO)
	{
		StringBuffer tooltip = new StringBuffer();
		String cr = "<br>";
		String lastHcp = "";
		
		SkinAssessmentReview lastReviewVo = null;

		//check if the finding was reviewed
		if(findingVO != null && findingVO.getSkinAssessmentReviewIsNotNull() && findingVO.getSkinAssessmentReview().size() > 1)
		{
			tooltip.append("<b>Last Review</b>");
			tooltip.append(cr);
			tooltip.append("-----------------------------------------------------------");
			tooltip.append(cr);
		}
		
		tooltip.append(label[0]);
		
		//Date/Time
		if(findingVO != null && findingVO.getSkinAssessmentReviewIsNotNull())
		{
			DateTime lastdt = null;
			int nCount = findingVO.getSkinAssessmentReview().size();
			
			findingVO.getSkinAssessmentReview().sort();
			
			if(nCount > 0)
			{
				lastdt = findingVO.getSkinAssessmentReview().get(nCount - 1).getDateTimeReview();
				lastHcp = findingVO.getSkinAssessmentReview().get(nCount - 1).getHCPReviewIsNotNull() == false ? "" : findingVO.getSkinAssessmentReview().get(nCount - 1).getHCPReview().toString();
				
				lastReviewVo = findingVO.getSkinAssessmentReview().get(nCount - 1);
			}
			
			if(lastdt != null)
			{
				tooltip.append(lastdt.getDate().toString(DateFormat.STANDARD));
				tooltip.append("; ");
				tooltip.append(lastdt.getTime().toString(TimeFormat.DEFAULT));
				tooltip.append("hrs");
			}
			
			/*
			if(skinAssessment.getDateTimeInitiated() != null)
			{
				tooltip.append(skinAssessment.getDateTimeInitiated().getDate().toString(DateFormat.STANDARD));
				tooltip.append("; ");
				tooltip.append(skinAssessment.getDateTimeInitiated().getTime().toString(TimeFormat.DEFAULT));
				tooltip.append("hrs");
			}
			*/
		}
		tooltip.append(cr);

		if(lastReviewVo == null)
		{
			//HCP
			tooltip.append(label[1]);
			if(skinAssessment.getHcpInitiated() != null)
				tooltip.append(lastHcp != null ? lastHcp : "");
				//tooltip.append(skinAssessment.getHcpInitiated().toString());
			tooltip.append(cr);
			
			//Finding
			tooltip.append(label[2]);
			if(findingVO.getWoundType() != null)
				tooltip.append(findingVO.getWoundType().getText());
			tooltip.append(findingVO.getIsContinuedAssessment() != null && findingVO.getIsContinuedAssessment().booleanValue()? " <font color=\"#FF0000\">(Copied)</font>":"");
			tooltip.append(cr);
			
			//Site
			tooltip.append(label[3]);
			tooltip.append(findingVO.getSiteNameIsNotNull()?findingVO.getSiteName():"");
			tooltip.append(cr);
			
			//Site Details
			tooltip.append(label[4]);
			if(findingVO.getSiteDetails() != null)
				tooltip.append(findingVO.getSiteDetails());
			tooltip.append(cr);
			
			//How Long
			tooltip.append(label[5]);
			if(findingVO.getHowLongIsItPresent() != null)
				tooltip.append(findingVO.getHowLongIsItPresent());
			tooltip.append(cr);
			
			//Pressure Sore Grade
			tooltip.append(label[6]);
			if(findingVO.getPressureSoreGrade() != null)
				tooltip.append(findingVO.getPressureSoreGrade().getText());
			tooltip.append(cr);
	
			tooltip.append(label[7]);
			//Size: Length, Width, Depth: 
			if(findingVO.getLength() != null || findingVO.getWidth() != null || findingVO.getDepth() != null)
			{
				//Length
				if(findingVO.getLength() != null)
					tooltip.append(findingVO.getLength());
				tooltip.append(", ");
				//Width
				if(findingVO.getWidth() != null)
					tooltip.append(findingVO.getWidth());
				tooltip.append(", ");
				//Depth
				if(findingVO.getDepth() != null)
					tooltip.append(findingVO.getDepth());
			}
			
			tooltip.append(cr);
			
			//Wound Bed
			tooltip.append(label[8]);
			if(findingVO.getWoundBed() != null)
				tooltip.append(findingVO.getWoundBed().getText());
			tooltip.append(cr);
			
			//Surrounding Skin
			tooltip.append(label[9]);
			if(findingVO.getSurroundingSkin() != null)
				tooltip.append(findingVO.getSurroundingSkin().getText());
			tooltip.append(cr);
			
			//Exudate Amount
			tooltip.append(label[10]);
			if(findingVO.getExudateAmount() != null)
				tooltip.append(findingVO.getExudateAmount().getText());
			tooltip.append(cr);
			
			//Exudate Type
			tooltip.append(label[11]);
			if(findingVO.getExudateType() != null)
				tooltip.append(findingVO.getExudateType().getText());
			tooltip.append(cr);
			
			//Odour
			tooltip.append(label[12]);
			if(findingVO.getOdour() != null)
				tooltip.append(findingVO.getOdour().getText());
			tooltip.append(cr);
			
			//Pain
			tooltip.append(label[13]);
			if(findingVO.getPain() != null)
				tooltip.append(findingVO.getPain().getText());
			tooltip.append(cr);
			
			//Infection Suspected
			tooltip.append(label[14]);
			if(findingVO.getInfectionSuspected() != null)
			{
				if(findingVO.getInfectionSuspected().booleanValue())
					tooltip.append(yes);
				else
					tooltip.append(no);
			}
			tooltip.append(cr);
			
			//Swab taken
			tooltip.append(label[15]);
			if(findingVO.getSwabTaken() != null)
			{
				if(findingVO.getSwabTaken().booleanValue())
					tooltip.append(yes);
				else
					tooltip.append(no);
			}
			tooltip.append(cr);
					
			//Wound Traced
			tooltip.append(label[16]);
			if(findingVO.getWoundTraced() != null)
			{
				if(findingVO.getWoundTraced().booleanValue())
					tooltip.append(yes);
				else
					tooltip.append(no);
			}
			tooltip.append(cr);
			
			//Cleansed With
			tooltip.append(label[17]);
			if(findingVO.getCleansedWith() != null)
				tooltip.append(findingVO.getCleansedWith().getText());
			tooltip.append(cr);
			
			//Primary Dressing
			tooltip.append(label[18]);
			if(findingVO.getPrimaryDressing() != null)
				tooltip.append(findingVO.getPrimaryDressing().getText());
			tooltip.append(cr);
			
			//Secondary Dressing
			tooltip.append(label[19]);
			if(findingVO.getSecondaryDressing() != null)
				tooltip.append(findingVO.getSecondaryDressing().getText());
			tooltip.append(cr);
			
			//Frequency of Change
			tooltip.append(label[20]);
			if(findingVO.getFrequencyOfChange() != null)
				tooltip.append(findingVO.getFrequencyOfChange().getText());
			tooltip.append(cr);
			
			//Continued Assessment
			//tooltip.append(label[21]);
			//tooltip.append(findingVO.getIsContinuedAssessment() != null && findingVO.getIsContinuedAssessment().booleanValue()?yes:no);
			//tooltip.append(cr);
			
	//		//Comment
	//		tooltip.append(label[20]);
	//		tooltip.append(findingVO.getComment());
	//		tooltip.append(cr);
			
			//Discontinue
			tooltip.append(label[22]);
			tooltip.append(findingVO.getIsDiscontinuedAssess() == null || !findingVO.getIsDiscontinuedAssess().booleanValue()?no:yes);
		}
		else
		{
			//HCP
			tooltip.append(label[1]);
			if(lastReviewVo.getHCPReview() != null)
				tooltip.append(lastHcp != null ? lastHcp : "");
				//tooltip.append(skinAssessment.getHcpInitiated().toString());
			tooltip.append(cr);
			
			//Finding
			tooltip.append(label[2]);
			if(findingVO.getWoundType() != null)
				tooltip.append(findingVO.getWoundType().getText());
			tooltip.append(findingVO.getIsContinuedAssessment() != null && findingVO.getIsContinuedAssessment().booleanValue()? " <font color=\"#FF0000\">(Copied)</font>":"");
			tooltip.append(cr);
			
			//Site
			tooltip.append(label[3]);
			tooltip.append(findingVO.getSiteNameIsNotNull()?findingVO.getSiteName():"");
			tooltip.append(cr);
			
			//Site Details
			tooltip.append(label[4]);
			if(lastReviewVo.getSiteDetails() != null)
				tooltip.append(lastReviewVo.getSiteDetails());
			tooltip.append(cr);
			
			//How Long
			tooltip.append(label[5]);
			if(lastReviewVo.getHowLongIsItPresent() != null)
				tooltip.append(lastReviewVo.getHowLongIsItPresent());
			tooltip.append(cr);
			
			//Pressure Sore Grade
			tooltip.append(label[6]);
			if(lastReviewVo.getPressureSoreGrade() != null)
				tooltip.append(lastReviewVo.getPressureSoreGrade().getText());
			tooltip.append(cr);
	
			tooltip.append(label[7]);
			//Size: Length, Width, Depth: 
			if(lastReviewVo.getLength() != null || lastReviewVo.getWidth() != null || lastReviewVo.getDepth() != null)
			{
				//Length
				if(lastReviewVo.getLength() != null)
					tooltip.append(lastReviewVo.getLength());
				tooltip.append(", ");
				//Width
				if(lastReviewVo.getWidth() != null)
					tooltip.append(lastReviewVo.getWidth());
				tooltip.append(", ");
				//Depth
				if(lastReviewVo.getDepth() != null)
					tooltip.append(lastReviewVo.getDepth());
			}
			
			tooltip.append(cr);
			
			//Wound Bed
			tooltip.append(label[8]);
			if(lastReviewVo.getWoundBed() != null)
				tooltip.append(lastReviewVo.getWoundBed().getText());
			tooltip.append(cr);
			
			//Surrounding Skin
			tooltip.append(label[9]);
			if(lastReviewVo.getSurroundingSkin() != null)
				tooltip.append(lastReviewVo.getSurroundingSkin().getText());
			tooltip.append(cr);
			
			//Exudate Amount
			tooltip.append(label[10]);
			if(lastReviewVo.getExudateAmount() != null)
				tooltip.append(lastReviewVo.getExudateAmount().getText());
			tooltip.append(cr);
			
			//Exudate Type
			tooltip.append(label[11]);
			if(lastReviewVo.getExudateType() != null)
				tooltip.append(lastReviewVo.getExudateType().getText());
			tooltip.append(cr);
			
			//Odour
			tooltip.append(label[12]);
			if(lastReviewVo.getOdour() != null)
				tooltip.append(lastReviewVo.getOdour().getText());
			tooltip.append(cr);
			
			//Pain
			tooltip.append(label[13]);
			if(lastReviewVo.getPain() != null)
				tooltip.append(lastReviewVo.getPain().getText());
			tooltip.append(cr);
			
			//Infection Suspected
			tooltip.append(label[14]);
			if(lastReviewVo.getInfectionSuspected() != null)
			{
				if(lastReviewVo.getInfectionSuspected().booleanValue())
					tooltip.append(yes);
				else
					tooltip.append(no);
			}
			tooltip.append(cr);
			
			//Swab taken
			tooltip.append(label[15]);
			if(lastReviewVo.getSwabTaken() != null)
			{
				if(lastReviewVo.getSwabTaken().booleanValue())
					tooltip.append(yes);
				else
					tooltip.append(no);
			}
			tooltip.append(cr);
					
			//Wound Traced
			tooltip.append(label[16]);
			if(lastReviewVo.getWoundTraced() != null)
			{
				if(lastReviewVo.getWoundTraced().booleanValue())
					tooltip.append(yes);
				else
					tooltip.append(no);
			}
			tooltip.append(cr);
			
			//Cleansed With
			tooltip.append(label[17]);
			if(lastReviewVo.getCleansedWith() != null)
				tooltip.append(lastReviewVo.getCleansedWith().getText());
			tooltip.append(cr);
			
			//Primary Dressing
			tooltip.append(label[18]);
			if(lastReviewVo.getPrimaryDressing() != null)
				tooltip.append(lastReviewVo.getPrimaryDressing().getText());
			tooltip.append(cr);
			
			//Secondary Dressing
			tooltip.append(label[19]);
			if(lastReviewVo.getSecondaryDressing() != null)
				tooltip.append(lastReviewVo.getSecondaryDressing().getText());
			tooltip.append(cr);
			
			//Frequency of Change
			tooltip.append(label[20]);
			if(lastReviewVo.getFrequencyOfChange() != null)
				tooltip.append(lastReviewVo.getFrequencyOfChange().getText());
			tooltip.append(cr);
			
			//Continued Assessment
			//tooltip.append(label[21]);
			//tooltip.append(findingVO.getIsContinuedAssessment() != null && findingVO.getIsContinuedAssessment().booleanValue()?yes:no);
			//tooltip.append(cr);
			
	//		//Comment
	//		tooltip.append(label[20]);
	//		tooltip.append(findingVO.getComment());
	//		tooltip.append(cr);
			
			//Discontinue
			tooltip.append(label[22]);
			tooltip.append(findingVO.getIsDiscontinuedAssess() == null || !findingVO.getIsDiscontinuedAssess().booleanValue()?no:yes);
		}
		
		return tooltip.toString();
	}
	
	protected void onChkSkinIntactValueChanged() throws PresentationLogicException 
	{
		//Check for existing drawing
		if(form.chkSkinIntact().getValue())
		{
			if(form.drawingBodyChart().getShapes() != null && form.drawingBodyChart().getShapes().size() > 0)
			{
				DrawingControlShape shape;
				boolean skinStillIntact = true;
				for(int i=0; i<form.drawingBodyChart().getShapes().size(); i++)
				{
					shape = (DrawingControlShape)form.drawingBodyChart().getShapes().get(i);
					if(shape.getBrushID()==SkinWoundType.PURPURA.getId() || shape.getBrushID()==(SkinWoundType.SCAR.getId()))
					{
						skinStillIntact = false;
					}
					else
					{
						skinStillIntact = true;
						break;
					}
				}
			
				
				if(skinStillIntact)
				{
					form.chkSkinIntact().setValue(false);
					displayError("All findings must be discontinued before 'Skin Intact' can be checked");
					return;
				}
			}

			form.drawingBodyChart().clearBrushes();
			
			for(int i=0; i<SkinWoundType.getNegativeInstances().length; i++)
				if(SkinWoundType.getNegativeInstances()[i].equals(SkinWoundType.PURPURA)||SkinWoundType.getNegativeInstances()[i].equals(SkinWoundType.SCAR))
					form.drawingBodyChart().addBrush(SkinWoundType.getNegativeInstances()[i].getId(), SkinWoundType.getNegativeInstances()[i].getText(), SkinWoundType.getNegativeInstances()[i].getColor());	
		}
		else
		{
			form.drawingBodyChart().clearBrushes();
			initialiseDrawingControl(true);
		}
	}
	

	protected void onDrawingBodyChartEdited(int index) throws PresentationLogicException 
	{
		SkinAssessment skinAssVO = form.getGlobalContext().COE.SkinBodyChart.getSkinAssessmentVO();
		boolean siteFound = false;
		SkinAssessmentFindings findingVO = null;
		
		if(skinAssVO != null)
		{
			for(int i=0; i<skinAssVO.getSkinAssessmentFindings().size(); i++)
			{
				//check if it has the same shape
				if(skinAssVO.getSkinAssessmentFindings().get(i).getID_SkinAssessmentFindingsIsNotNull() &&
				   skinAssVO.getSkinAssessmentFindings().get(i).getID_SkinAssessmentFindings().intValue() == index )
				{
					findingVO = (SkinAssessmentFindings)skinAssVO.getSkinAssessmentFindings().get(i).clone();
					findingVO.setSiteImage(getVMLfromIndex(index));
					//Remove it and add the new one
					skinAssVO.getSkinAssessmentFindings().remove(i);
					skinAssVO.getSkinAssessmentFindings().add(findingVO);
					siteFound = true;
					break;
				}
			}
			
			if(!siteFound)
			{
				DrawingControlShape shape = getEditedShape(index);
				if(shape != null)
				{
					findingVO = new SkinAssessmentFindings();
					findingVO.setSiteName(getAreaName(shape.getTargetID()));
					findingVO.setWoundType(getWoundType(shape.getBrushID())); //Brushid here is 0
					findingVO.setID_SkinAssessmentFindings(new Integer(shape.getIndex()));
					findingVO.setSiteImage(shape.getVML());
					findingVO.setIsDiscontinuedAssess(new Boolean(false));
					//skinAssVO.getSkinAssessmentFindings().add(findingVO);
					siteFound = true;
					
					//create a new review from findings
					
					findingVO.setSkinAssessmentReview(new SkinAssessmentReviewCollection());
					SkinAssessmentReview sarVO = getReviewVOfromFindingVO(findingVO);
					sarVO.setDateTimeReview(new DateTime(form.dateAssess().getValue(), form.timeAssess().getValue()));
					
					MemberOfStaffShortVo memStaffShortVo = (MemberOfStaffShortVo)domain.getMosUser();
					if(memStaffShortVo != null && memStaffShortVo.getHcp() != null)
						sarVO.setHCPReview(memStaffShortVo.getHcp());
					
					findingVO.getSkinAssessmentReview().add(sarVO);
					
					skinAssVO.getSkinAssessmentFindings().add(findingVO);
					
				}
				else
					displayError("No drawing details found.");
			}
		}

		if(siteFound)
		{
			//Set back to the context the SkinAssVO and the assFindingVO
			form.getGlobalContext().COE.SkinBodyChart.setFindingsVO(findingVO);
			form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(skinAssVO);
		}
	}
	
	private String getVMLfromIndex(int index)
	{
		DrawingControlShape shape;
		for(int i=0; i<form.drawingBodyChart().getShapes().size(); i++)
		{
			shape = (DrawingControlShape)form.drawingBodyChart().getShapes().get(i);
			if(shape.getIndex() == index)
				return shape.getVML();
		}
		
		return "";
	}
	
	private DrawingControlShape getEditedShape(int index)
	{
		for(int i=0; i<form.drawingBodyChart().getShapes().size(); i++)
		{
			DrawingControlShape shape = (DrawingControlShape)form.drawingBodyChart().getShapes().get(i);
			if(shape.getIndex() == index)
				return shape;
		}
		return null;
	}
	
	private void clearContext()
	{
		form.getGlobalContext().COE.SkinBodyChart.setFindingsVO(null);
		form.getGlobalContext().COE.SkinBodyChart.setSkinAssessmentVO(null);
	}
	
	protected void onBtnCloseClick() throws PresentationLogicException 
	{
	
		
		if (form.getGlobalContext().Nursing.getAssessmentComponent() != null)
		{
			if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentSkin)
			{ 
				engine.open(form.getForms().COE.AssessSkin);	
			}
			else if(form.getGlobalContext().Nursing.getAssessmentComponent() instanceof NurAssessmentSkinVo)
			{ 
				if(isSkinBodyChartDialog())
				{
					engine.close(DialogResult.OK);
					return;
				}
				
				engine.open(form.getForms().SpinalInjuries.NurAssessmentSkin);	
			}
		}
		
			
	}
	
	private boolean isAssementComponent()
	{
		if(form.getGlobalContext().Nursing.getAssessmentComponent() != null && form.getGlobalContext().Nursing.getAssessmentComponent() instanceof AssessmentSkin)
		{
			AssessmentSkin comp = (AssessmentSkin)form.getGlobalContext().Nursing.getAssessmentComponent();
			if (comp.getSkinAssessment() != null)
				return true;
		}
		else if(form.getGlobalContext().Nursing.getAssessmentComponent() != null && form.getGlobalContext().Nursing.getAssessmentComponent() instanceof NurAssessmentSkinVo)
		{
			NurAssessmentSkinVo comp = (NurAssessmentSkinVo)form.getGlobalContext().Nursing.getAssessmentComponent();
			if (comp.getSkinAssessment() != null)
				return true;
		}
		
		return false;
	}
	// WDEV-1023
	// Drawing Control - Body chart - sitename is null is some cases. 
	// Appears blank on the review records and appears as null on the tooltip.
	private String getAreaName(int targetId)
	{
		String areaName = form.drawingBodyChart().getGroupOrAreaName(targetId);
		if(areaName == null || areaName.equals(""))
		{
			DrawingControlGroup areaGroup = form.drawingBodyChart().getAreas();
					
			if(areaGroup != null)
			{
				DrawingControlAreaCollection coll = areaGroup.getAllAreas();
				for (int i = 0; i < coll.size(); i++)
				{
					if(coll.get(i).getID() == targetId)
					{
						areaName = coll.get(i).getName();
						break;
					}
				}
			}
		}
		
		return areaName;
	}
	
	//Get all the Groups
	private DrawingControlGroupCollection getAllGroups(DrawingControlGroup rootNode)
	{
		DrawingControlGroupCollection groupColl = new DrawingControlGroupCollection();
		if(rootNode.getGroups() != null)
		{
			//Add the parent root
			groupColl.add(rootNode);
			for(int i=0; i<rootNode.getGroups().size(); i++)
			{
				groupColl.add(rootNode.getGroups().get(i));
				getGroups(groupColl, rootNode.getGroups().get(i)); 
			}
		}

		return groupColl;
	}
	
	private void getGroups(DrawingControlGroupCollection groupColl, DrawingControlGroup node)
	{
		if(node.getGroups().size() > 0)
		{
			for(int i=0; i<node.getGroups().size(); i++)
				getGroups(groupColl, node.getGroups().get(i)); 
		}
		else
			groupColl.add(node);
	}
	
	private boolean recordSaved(Integer skinAssFindingID)
	{
		for(int i=0; i<form.drawingBodyChart().getShapes().size(); i++)
		{
			if(((DrawingControlShape)form.drawingBodyChart().getShapes().get(i)).getIndex()    == skinAssFindingID.intValue() && 
			   ((DrawingControlShape)form.drawingBodyChart().getShapes().get(i)).getTargetID() == savedTargetID)
				return true;
		}
		return false;
	}
	
	private ims.nursing.vo.SkinAssessmentReview getReviewVOfromFindingVO(SkinAssessmentFindings findingVO)
	{
		SkinAssessmentReview skinReviewVO = getReviewRecord(findingVO);
		if(skinReviewVO.getID_SkinAssessmentReview() == null)
			skinReviewVO.setID_SkinAssessmentReview(findingVO.getID_SkinAssessmentFindings());
		//SkinAssessment assessment 		  = form.comboBoxAssessment().getValue();
		
		//DateTime - from skinAssessment
		//skinReviewVO.setDateTimeReview(assessment.getDateTimeInitiated());

		//DateTime from a dummy SkinAssessmentReview
		if(findingVO.getSkinAssessmentReviewIsNotNull())
		{
			if(findingVO.getSkinAssessmentReview().size() > 0)
			{
				skinReviewVO.setDateTimeReview(findingVO.getSkinAssessmentReview().get(0).getDateTimeReview());
			}
		}
		//HCP - from skinAssessment
		//skinReviewVO.setHCPReview(assessment.getHcpInitiated());
		skinReviewVO.setComment(findingVO.getComment());
		skinReviewVO.setDepth(findingVO.getDepth());
		skinReviewVO.setExudateAmount(findingVO.getExudateAmount());
		skinReviewVO.setExudateType(findingVO.getExudateType());
		skinReviewVO.setFrequencyOfChange(findingVO.getFrequencyOfChange());
		skinReviewVO.setHowLongIsItPresent(findingVO.getHowLongIsItPresent());
		skinReviewVO.setCleansedWith(findingVO.getCleansedWith());
		skinReviewVO.setInfectionSuspected(findingVO.getInfectionSuspected());
		skinReviewVO.setLength(findingVO.getLength());
		skinReviewVO.setOdour(findingVO.getOdour());
		skinReviewVO.setPain(findingVO.getPain());
		skinReviewVO.setPressureSoreGrade(findingVO.getPressureSoreGrade());
		skinReviewVO.setPrimaryDressing(findingVO.getPrimaryDressing());
		skinReviewVO.setSecondaryDressing(findingVO.getSecondaryDressing());
		skinReviewVO.setSiteDetails(findingVO.getSiteDetails());
		skinReviewVO.setSurroundingSkin(findingVO.getSurroundingSkin());
		skinReviewVO.setSwabTaken(findingVO.getSwabTaken());
		skinReviewVO.setWidth(findingVO.getWidth());
		skinReviewVO.setWoundBed(findingVO.getWoundBed());
		skinReviewVO.setWoundTraced(findingVO.getWoundTraced());
		
		return skinReviewVO;
	}
	
	//Get the already edited or a new one - fixes a bug when clicking Finish before clicking Note which created a blank review 
	private SkinAssessmentReview getReviewRecord(SkinAssessmentFindings findingVo)
	{
		if(findingVo.getSkinAssessmentReviewIsNotNull())
		{
			for(int i=0; i<findingVo.getSkinAssessmentReview().size(); i++)
			{
				if(findingVo.getSkinAssessmentReview().get(i).getID_SkinAssessmentReviewIsNotNull() && 
				   findingVo.getSkinAssessmentReview().get(i).getID_SkinAssessmentReview().intValue() == findingVo.getID_SkinAssessmentFindings().intValue())
					return findingVo.getSkinAssessmentReview().get(i); 
			}
		}
		return new SkinAssessmentReview();
	}
	
	//Check if a review was added (e.g. as it might be created after clickining Finished)
	private boolean reviewEdited(SkinAssessmentFindings findingVo)
	{
		if(findingVo.getSkinAssessmentReviewIsNotNull())
		{
			//Only when having one review - (e.g. when the review was created from the finding)
			if(findingVo.getSkinAssessmentReview().size() == 1 && findingVo.getSkinAssessmentReview().get(0).getID_SkinAssessmentReviewIsNotNull() &&
			   findingVo.getSkinAssessmentReview().get(0).getID_SkinAssessmentReview().intValue() == findingVo.getID_SkinAssessmentFindings().intValue())
					return true; 
		}
		return false;
	}
	
	private boolean isSkinBodyChartDialog() 
	{
		if(engine.getFormName().equals(form.getForms().Nursing.SkinBodyChartDialog))
			return true;
		
		return false;
	}

	private String[] label = new String[]{"<b>" + "Recording Date/Time: " + "</b>", 
										  "<b>" + "HCP: " + "</b>",
										  "<b>" + "Finding: " + "</b>",
										  "<b>" + "Site: " + "</b>",
										  "<b>" + "Site Details: " + "</b>",
										  "<b>" + "How long is it present: " + "</b>",
										  "<b>" + "Pressure Sore Grade: " + "</b>",
										  "<b>" + "Size: Length, Width, Depth: " + "</b>",
										  "<b>" + "Wound Bed: " + "</b>",
										  "<b>" + "Surrounding Skin: " + "</b>",
										  "<b>" + "Exudate Amount: " + "</b>",
										  "<b>" + "Exudate Type: " + "</b>",
										  "<b>" + "Odour: " + "</b>",
										  "<b>" + "Pain: " + "</b>",
										  "<b>" + "Infection Suspected: " + "</b>",
										  "<b>" + "Swab Taken: " + "</b>",
										  "<b>" + "Wound Traced: " + "</b>",
										  "<b>" + "Cleansed With: " + "</b>",
										  "<b>" + "Primary Dressing: " + "</b>",
										  "<b>" + "Secondary Dressing: " + "</b>",
										  "<b>" + "Frequency of Change: " + "</b>",
										  "<b>" + PainStatus.CONTINUED + ": " + "</b>",
//										  "<b>" + "Comment: " + "</b>",
										  "<b>" + "Discontinued: " + "</b>"};
	private String yes = new String("Yes");
	private String no  = new String("No");
	private int savedTargetID =-1;
	}
