/*****************************************************************************
 *                                                                           *
 *  Copyright (c) 2010 by SANTEC/TUDOR www.santec.tudor.lu                   *
 *                                                                           *
 *                                                                           *
 *  This library is free software; you can redistribute it and/or modify it  *
 *  under the terms of the GNU Lesser General Public License as published    *
 *  by the Free Software Foundation; either version 2 of the License, or     *
 *  (at your option) any later version.                                      *
 *                                                                           *
 *  This software 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        *
 *  Lesser General Public License for more details.                          *
 *                                                                           *
 *  You should have received a copy of the GNU Lesser General Public         *
 *  License along with this library; if not, write to the Free Software      *
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  *
 *                                                                           *
 *****************************************************************************/
package lu.tudor.santec.gecamed.patient.gui.incident;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FocusTraversalPolicy;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.undo.UndoManager;

import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.GECAMedTab;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.utils.GradientFactory;
import lu.tudor.santec.gecamed.core.gui.utils.IChangeListener;
import lu.tudor.santec.gecamed.core.gui.utils.UndoTextArea;
import lu.tudor.santec.gecamed.core.gui.utils.UndoTextField;
import lu.tudor.santec.gecamed.core.gui.widgets.NumberField;
import lu.tudor.santec.gecamed.core.gui.widgets.autocompletion.GECAMedAutoCompletionHandler;
import lu.tudor.santec.gecamed.core.gui.widgets.autocompletion.GECAMedAutoCompletionTextComponent;
import lu.tudor.santec.gecamed.core.utils.GECAMedUtils;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.MeasurementType;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.gecamed.patient.gui.PatientManagerModule;
import lu.tudor.santec.gecamed.patient.gui.PatientPanel;
import lu.tudor.santec.gecamed.patient.gui.history.ImportantDataPanel;
import lu.tudor.santec.gecamed.patient.gui.settings.ConsultationEntryConfig;
import lu.tudor.santec.gecamed.patient.gui.settings.PatientModuleSettings;
import lu.tudor.santec.gecamed.prescription.gui.editor.PrescriptionDataModel;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.org.fife.ui.autocomplete.AutoCompletionTextComponent;
import bizcal.util.DateUtil;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JSpinnerDateEditor;

/**
 * The main panel for a consultation/incident. Will be placed in tabs, if there
 * are more than one
 *
 * it has a borderlayout and the main content is in the center
 *
 *
 * @author martin.heinemann@tudor.lu
 *
 *
 * @version <br>
 *          $Log: IncidentPanel.java,v $ Revision 1.57 2013-12-03 16:29:45 troth
 *          Redesign consultation config dialog.
 *
 *          Revision 1.56 2013-11-29 15:16:17 troth Fix some bugs: Consultation
 *          view if first panel is empty History view sickleave date
 *
 *          Revision 1.55 2013-11-29 09:16:31 troth Redesign consultation config
 *          dialog.
 *
 *          Revision 1.54 2013-11-28 10:38:26 ferring GECAMedUtils split into
 *          utils and GUI utils classes
 *
 *          Revision 1.53 2013-11-22 13:51:25 troth Fix some small bugs in the
 *          consultation view. Add new gui function the patient setting to
 *          config the consultation view.
 *
 *          Revision 1.52 2013-11-15 13:20:54 troth Little GUI fix.
 *
 *          Revision 1.51 2013-11-08 09:48:07 troth Fix Bug: Text content field
 *          of entry now can be disable.
 *
 *          Revision 1.50 2013-10-30 15:01:03 troth Code clear up.
 *
 *          Revision 1.49 2013-10-29 16:13:44 troth Add the auto completion
 *          context menu consultation field.
 *
 *          Revision 1.48 2013-10-29 15:39:51 troth Add scrollpane the the right
 *          side of consultation view.
 *
 *          Revision 1.47 2013-10-29 14:05:25 troth Fix some null pointer
 *          exceptions.
 *
 *          Revision 1.46 2013-10-29 09:45:27 troth The new consultation view
 *          with more entries and the sickleave version 3 fix several bugs.
 *
 *          Revision 1.45 2013-10-28 16:55:13 ferring consultation panels bug
 *          fixes
 *
 *          Revision 1.44 2013-09-11 11:00:28 troth Add global settings for the
 *          ImportantDataPanel to enable / disable and set the position of a
 *          Panel.
 *
 *          Revision 1.43 2013-09-04 15:33:26 troth The new consultation view
 *          with more entries and the sickleave version 2 history view work now.
 *
 *          Revision 1.42 2013-09-03 16:32:38 troth The new consultation view
 *          with more entries and the sickleave version 1 save entries work now.
 *
 *          Revision 1.41 2013-09-03 11:17:11 troth The new consultation view
 *          with more entries and the sickleave (GUI only work).
 *
 *          Revision 1.40 2013-03-14 07:38:03 kutscheid bugfixes for the import
 *          of measurements and incident entries
 *
 *          Revision 1.39 2011-05-11 09:43:44 ferring AutoCompletion added for
 *          SOAP
 *
 *          Revision 1.38 2010-11-30 13:26:27 troth Complete - # 642:
 *          Unregelm�ssige Formatierung der Measurment Eintr�ge in der
 *          Historie http://santec.tudor.lu/trac/gecamed/ticket/642
 *
 *          Revision 1.37 2010-10-11 08:47:38 troth add revised
 *          UndoTextArea/UndoTextField to the text fields in consultations view
 *
 *          Revision 1.36 2010-09-30 13:03:37 troth Complete - #667
 *          http://santec.tudor.lu/trac/gecamed/ticket/667
 *
 *          Revision 1.35 2010-09-07 16:48:32 troth Incomplete - # 631: Fehler
 *          beim Patienten-Abspeichern nach L�schen eines Unfalls
 *          http://santec.tudor.lu/trac/gecamed/ticket/631
 *
 *          Revision 1.34 2010-09-06 14:29:22 troth Incomplete - # 625:
 *          Unfalldatum nicht angezeigt in Dialog-Verschreibungsfenster
 *          http://santec.tudor.lu/trac/gecamed/ticket/625
 *
 *          Revision 1.33 2010-09-02 16:16:40 troth Incomplete - # 619: Probleme
 *          mit neuer Unfall-Implementierung
 *          http://santec.tudor.lu/trac/gecamed/ticket/619
 *
 *          Revision 1.32 2010-08-31 13:35:56 troth Incomplete - # 495: Mehrere
 *          Unstimmigkeiten mit Unfallnummer (auch #529)
 *          http://santec.tudor.lu/trac/gecamed/ticket/495 and Tickets 529, 613
 *          and new/redesign of AccidentPanel
 *
 *          Revision 1.31 2010-05-17 08:44:23 troth small bugfix - add special
 *          character Incomplete - # 497: Seltsame Mengenbezeichnungen "½" und
 *          "¼" im Posologie-Fenster
 *          http://santec.tudor.lu/trac/gecamed/ticket/497
 *
 *          Revision 1.30 2010-05-05 11:23:13 ferring *** empty log message ***
 *
 *          Revision 1.29 2010-04-26 16:38:13 troth Redesign of the prescription
 *          view
 *
 *          Revision 1.28 2009-04-15 13:30:16 heinemann replaced accident icon
 *          with a button to open the accident chooser dialog
 *
 *          Revision 1.27 2009-02-27 09:03:20 heinemann huups. Import cefip
 *          action was .... absent
 *
 *          Revision 1.26 2009-01-19 15:57:57 heinemann *** empty log message
 *          ***
 *
 *          Revision 1.25 2008-12-17 15:23:06 heinemann initial commit after
 *          merging of branch new prescription
 *
 *          Revision 1.24.2.1 2008-12-15 14:08:21 heinemann *** empty log
 *          message ***
 *
 *          Revision 1.24 2008-10-21 09:53:34 hermen fixed patient slot bug
 *          enhanced logging code cleanup
 *
 *          Revision 1.23 2008-09-25 09:43:07 heinemann fixed copyrights
 *
 *          Revision 1.22 2008-08-19 10:25:08 heinemann cleanup
 *
 *          Revision 1.21 2008-04-15 12:40:51 heinemann select accident number
 *          when the date is choosen in consultation view
 *
 *          Revision 1.20 2008-04-14 14:37:07 heinemann fixed problem with
 *          patient accident that was not transfered to the billing module when
 *          the current consultation, including the accident, was not saved
 *          before the creation of the invoice.
 *
 *          Revision 1.19 2008-03-20 16:08:14 heinemann *** empty log message
 *          ***
 *
 *          Revision 1.18 2008-02-11 16:49:13 heinemann moved IChangeListener to
 *          core
 *
 *          Revision 1.17 2008-01-22 13:51:51 heinemann code cleanup and java
 *          doc
 *
 *          Revision 1.16 2008-01-02 13:45:46 heinemann added nice gradient
 *          panels
 *
 *          Revision 1.13 2007/07/03 12:35:29 heinemann system.out removed
 *
 *          Revision 1.12 2007/06/18 11:31:36 hermen cleanup of old stuff and
 *          moved some beans
 *
 *          Revision 1.11 2007/04/18 09:04:35 heinemann removed obsolete imports
 *          Revision 1.8 2007/03/15 12:01:56 heinemann bugfix for saving height
 *          and weight fields
 *
 *          Revision 1.7 2007/03/14 09:06:58 heinemann best practise fixes
 *
 *          Revision 1.6 2007/03/12 14:32:10 heinemann Complete - # 46: make
 *          printed prescriptions editable
 *          http://santec.tudor.lu:8888/gecamed/ticket/46
 *
 *          Revision 1.5 2007/03/12 08:41:09 heinemann update generic fields
 *
 *          fixed bug while loading diagnosis data
 *
 *          Revision 1.4 2007/03/07 09:59:36 heinemann fixed accident icon
 *          enabling
 *
 *          Revision 1.3 2007/03/06 06:48:05 heinemann Incomplete - # 8: Closing
 *          of consultation tabs http://santec.tudor.lu:8888/gecamed/ticket/8
 *
 *          Revision 1.2 2007/03/02 08:28:43 hermen initial checkin after the
 *          merge of PatientModuleRebuild with the main HEAD
 *
 *          Revision 1.1.2.5 2007/02/22 12:46:27 heinemann Incomplete - # 24:
 *          Add generic measurement fields to the incident panel
 *          http://santec.tudor.lu:8888/gecamed/ticket/24
 *
 *          Revision 1.1.2.4 2007/02/22 12:01:22 heinemann *** empty log message
 *          ***
 *
 *          Revision 1.1.2.3 2007/02/08 16:45:12 heinemann many changes
 *
 *          Revision 1.1.2.2 2007/01/12 13:04:06 heinemann Incomplete - # 51:
 *          Create preview for prescription templates
 *          http://santec.tudor.lu:8888/gecamed/ticket/51 Incomplete - # 21:
 *          Context Menu -> create new prescription
 *          http://santec.tudor.lu:8888/gecamed/ticket/21
 *
 *          Revision 1.1.2.1 2007/01/04 13:48:42 heinemann The great space
 *          cleaning lady has done a big bunch of refactoring
 *
 *          Revision 1.1.2.17 2007/01/04 12:13:53 heinemann Incomplete - # 22:
 *          Save consultation after a prescription was printed does not work
 *          http://santec.tudor.lu:8888/gecamed/ticket/22
 *
 *          fixed and some other changes like the behaviour of the prescription
 *          editor in case of printing and afterwards saving the consultation
 *          etc
 *
 *          Revision 1.1.2.16 2006/12/28 15:47:15 heinemann *** empty log
 *          message ***
 *
 *          Revision 1.1.2.15 2006/12/28 12:09:47 heinemann added a scrollpane
 *          under the main panel.
 *
 *          Revision 1.1.2.14 2006/12/28 10:31:37 heinemann bug fixing
 *
 *          Revision 1.1.2.13 2006/12/21 14:25:13 heinemann sysouts removed
 *
 *          Revision 1.1.2.12 2006/12/19 14:51:13 heinemann printing etc
 *
 *          Revision 1.1.2.11 2006/12/15 15:58:03 heinemann presc
 *
 *          Revision 1.1.2.7 2006/12/14 12:25:18 heinemann smaller Textfields
 *          for measurements
 *
 *
 *          Revision 1.1.2.3 2006/12/06 13:47:22 heinemann insets adapted
 *
 *          Revision 1.1.2.2 2006/12/06 12:38:22 heinemann fixed tab cycle in
 *          measurement panel
 *
 *          Revision 1.1 2006/12/01 14:38:35 heinemann initial checkin
 *
 */
public class IncidentPanel extends GECAMedTab implements IChangeListener, DocumentListener, PropertyChangeListener {

	/*
	 * Class members -----------------------------------------------------------
	 */

	private static final long serialVersionUID = 1L;

	private final boolean OPAQUE = false;

	public static final String name = "INCIDENT_PANEL";

	private DateFormat formater = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);

	private IncidentModel model;

	private JPanel centerPanel;

	private CellConstraints cc;

	private JPanel soapPanel;

	private JPanel rightPanel;

	private boolean listenersActivated;

	// private KeyAdapter focusKeyListener;

	private KeyListener focusKeyListener;

	private IncidentControler controler;

	private JScrollPane scroll;

	private UndoTextField measField1;

	private UndoTextField measField2;

	private UndoTextField measField3;

	private boolean isFirstTimeShowing = true;

	private PatientPanel patientPanel;

	private AccidentPanel accidentPanel;

	private ImportantDataPanel importantDataPanel;

	// entrie settings
	private ConsultationEntryConfig soapS = null;
	private ConsultationEntryConfig soapO = null;
	private ConsultationEntryConfig soapA = null;
	private ConsultationEntryConfig soapP = null;
	private ConsultationEntryConfig cons1 = null;
	private ConsultationEntryConfig cons2 = null;
	private ConsultationEntryConfig cons3 = null;
	private ConsultationEntryConfig measurement = null;
	private ConsultationEntryConfig sickLeave = null;
	private ConsultationEntryConfig newColumn = null;
	private ConsultationEntryConfig[] consultationEntriesLeft = null;
	private ConsultationEntryConfig[] consultationEntriesRight = null;
	private int enabledEntriesLeft;
	private int enabledEntriesRight;

	private ConsultationEntryPanel soapSPanel = null;
	private ConsultationEntryPanel soapOPanel = null;
	private ConsultationEntryPanel soapAPanel = null;
	private ConsultationEntryPanel soapPPanel = null;
	private ConsultationEntryPanel cons1Panel = null;
	private ConsultationEntryPanel cons2Panel = null;
	private ConsultationEntryPanel cons3Panel = null;
	private JPanel measurementPanel = null;

	private JTextField sysField;

	private JTextField diaField;

	private JTextField poulseField;

	private JTextField heightField;

	private JTextField weightField;

	private JTextField bmiField;

	private ArrayList<JTextField> mFields;

	private JPanel sickLeavePanel = null;

	private UndoTextField sickLeaveCodeField;

	private JDateChooser sickLeaveStartDateChooser;

	private JDateChooser sickLeaveEndDateChooser;

	private JLabel sickLeaveStartDateLabel;

	private JLabel sickLeaveEndDateLabel;

	private JPanel secondConsultationEntryPanel;

	/*
	 * End of class members
	 * ************************************************************
	 */

	/**
	 * Constructors
	 * 
	 * @param historyPanel
	 *
	 */
	public IncidentPanel(IncidentModel model, PatientPanel patientPanel, IncidentControler controler) {
		this.model = model;
		this.patientPanel = patientPanel;
		this.controler = controler;
		this.setName(name);

		Translatrix.addBundle("lu.tudor.santec.gecamed.patient.gui.resources.Translatrix");

		// set entrie settings
		PatientModuleSettings patientGlobalSettings = PatientManagerModule.getInstance().patientSettings;

		// set values or default values of consultation entries
		boolean setDefaultPosition = false;
		soapS = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(IncidentManager.SOAP_S));
		if (soapS.getId() == null) {
			soapS = new ConsultationEntryConfig(PatientModuleSettings.SOAPS_DEFAULTS);
			setDefaultPosition = true;
		}

		soapO = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(IncidentManager.SOAP_O));
		if (soapO.getId() == null) {
			soapO = new ConsultationEntryConfig(PatientModuleSettings.SOAPO_DEFAULTS);
			setDefaultPosition = true;
		}

		soapA = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(IncidentManager.SOAP_A));
		if (soapA.getId() == null) {
			soapA = new ConsultationEntryConfig(PatientModuleSettings.SOAPA_DEFAULTS);
			setDefaultPosition = true;
		}

		soapP = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(IncidentManager.SOAP_P));
		if (soapP.getId() == null) {
			soapP = new ConsultationEntryConfig(PatientModuleSettings.SOAPP_DEFAULTS);
			setDefaultPosition = true;
		}

		cons1 = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(IncidentManager.CONS_1));
		if (cons1.getId() == null) {
			cons1 = new ConsultationEntryConfig(PatientModuleSettings.CONS1_DEFAULTS);
			setDefaultPosition = true;
		}

		cons2 = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(IncidentManager.CONS_2));
		if (cons2.getId() == null) {
			cons2 = new ConsultationEntryConfig(PatientModuleSettings.CONS2_DEFAULTS);
			setDefaultPosition = true;
		}

		cons3 = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(IncidentManager.CONS_3));
		if (cons3.getId() == null) {
			cons3 = new ConsultationEntryConfig(PatientModuleSettings.CONS3_DEFAULTS);
			setDefaultPosition = true;
		}

		measurement = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(IncidentManager.MEASUREMENT));
		if (measurement.getId() == null) {
			measurement = new ConsultationEntryConfig(PatientModuleSettings.MEASUREMENT_DEFAULTS);
			setDefaultPosition = true;
		}

		sickLeave = new ConsultationEntryConfig((String) patientGlobalSettings.getValue(IncidentManager.SICK_LEAVE));
		if (sickLeave.getId() == null) {
			sickLeave = new ConsultationEntryConfig(PatientModuleSettings.SICKLEAVE_DEFAULTS);
			setDefaultPosition = true;
		}

		newColumn = new ConsultationEntryConfig(
				(String) patientGlobalSettings.getValue(patientGlobalSettings.NEW_COLUMN));
		if (newColumn.getId() == null) {
			newColumn = new ConsultationEntryConfig(PatientModuleSettings.NEW_COLUMN_DEFAULTS);
			setDefaultPosition = true;
		}

		if (setDefaultPosition) {
			soapS.setPosition(0);
			soapO.setPosition(1);
			soapA.setPosition(3);
			soapP.setPosition(4);
			cons1.setPosition(5);
			cons2.setPosition(6);
			cons3.setPosition(7);
			measurement.setPosition(2);
			sickLeave.setPosition(8);
			newColumn.setPosition(9);
		}

		// soapS = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(IncidentManager.SOAP_S));
		// soapO = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(IncidentManager.SOAP_O));
		// soapA = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(IncidentManager.SOAP_A));
		// soapP = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(IncidentManager.SOAP_P));
		// cons1 = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(IncidentManager.CONS_1));
		// cons2 = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(IncidentManager.CONS_2));
		// cons3 = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(IncidentManager.CONS_3));
		// measurement = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(IncidentManager.MEASUREMENT));
		// sickLeave = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(IncidentManager.SICK_LEAVE));
		// newColumn = new ConsultationEntryConfig((String)
		// patientGlobalSettings.getValue(PatientModuleSettings.NEW_COLUMN));

		if (newColumn.getPosition() == 0 || newColumn.getPosition() == 9) {
			int modi = 0;
			if (newColumn.getPosition() == 0)
				modi = -1;
			consultationEntriesLeft = new ConsultationEntryConfig[9];
			// all entries in first column
			GECAMedUtils.insertIntoArray(consultationEntriesLeft, soapS, soapS.getPosition() + modi);
			GECAMedUtils.insertIntoArray(consultationEntriesLeft, soapO, soapO.getPosition() + modi);
			GECAMedUtils.insertIntoArray(consultationEntriesLeft, soapA, soapA.getPosition() + modi);
			GECAMedUtils.insertIntoArray(consultationEntriesLeft, soapP, soapP.getPosition() + modi);
			GECAMedUtils.insertIntoArray(consultationEntriesLeft, cons1, cons1.getPosition() + modi);
			GECAMedUtils.insertIntoArray(consultationEntriesLeft, cons2, cons2.getPosition() + modi);
			GECAMedUtils.insertIntoArray(consultationEntriesLeft, cons3, cons3.getPosition() + modi);
			GECAMedUtils.insertIntoArray(consultationEntriesLeft, measurement, measurement.getPosition() + modi);
			GECAMedUtils.insertIntoArray(consultationEntriesLeft, sickLeave, sickLeave.getPosition() + modi);

			// count enabled entries
			enabledEntriesLeft = 0;
			if (soapS.getEnabled())
				enabledEntriesLeft++;
			if (soapO.getEnabled())
				enabledEntriesLeft++;
			if (soapA.getEnabled())
				enabledEntriesLeft++;
			if (soapP.getEnabled())
				enabledEntriesLeft++;
			if (cons1.getEnabled())
				enabledEntriesLeft++;
			if (cons2.getEnabled())
				enabledEntriesLeft++;
			if (cons3.getEnabled())
				enabledEntriesLeft++;
			if (measurement.getEnabled())
				enabledEntriesLeft++;
			if (sickLeave.getEnabled())
				enabledEntriesLeft++;
		} else {
			int newColumnPosition = newColumn.getPosition();
			int lengthLeft = newColumnPosition;
			int lengthRight = 10 - newColumnPosition - 1;

			enabledEntriesLeft = 0;
			enabledEntriesRight = 0;

			consultationEntriesLeft = new ConsultationEntryConfig[lengthLeft];
			consultationEntriesRight = new ConsultationEntryConfig[lengthRight];

			if (soapS.getPosition() < newColumnPosition) {
				GECAMedUtils.insertIntoArray(consultationEntriesLeft, soapS, soapS.getPosition());
				if (soapS.getEnabled())
					enabledEntriesLeft++;
			} else {
				GECAMedUtils.insertIntoArray(consultationEntriesRight, soapS,
						soapS.getPosition() - newColumnPosition - 1);
				if (soapS.getEnabled())
					enabledEntriesRight++;
			}

			if (soapO.getPosition() < newColumnPosition) {
				GECAMedUtils.insertIntoArray(consultationEntriesLeft, soapO, soapO.getPosition());
				if (soapO.getEnabled())
					enabledEntriesLeft++;
			} else {
				GECAMedUtils.insertIntoArray(consultationEntriesRight, soapO,
						soapO.getPosition() - newColumnPosition - 1);
				if (soapO.getEnabled())
					enabledEntriesRight++;
			}

			if (soapA.getPosition() < newColumnPosition) {
				GECAMedUtils.insertIntoArray(consultationEntriesLeft, soapA, soapA.getPosition());
				if (soapA.getEnabled())
					enabledEntriesLeft++;
			} else {
				GECAMedUtils.insertIntoArray(consultationEntriesRight, soapA,
						soapA.getPosition() - newColumnPosition - 1);
				if (soapA.getEnabled())
					enabledEntriesRight++;
			}

			if (soapP.getPosition() < newColumnPosition) {
				GECAMedUtils.insertIntoArray(consultationEntriesLeft, soapP, soapP.getPosition());
				if (soapP.getEnabled())
					enabledEntriesLeft++;
			} else {
				GECAMedUtils.insertIntoArray(consultationEntriesRight, soapP,
						soapP.getPosition() - newColumnPosition - 1);
				if (soapP.getEnabled())
					enabledEntriesRight++;
			}

			if (cons1.getPosition() < newColumnPosition) {
				GECAMedUtils.insertIntoArray(consultationEntriesLeft, cons1, cons1.getPosition());
				if (cons1.getEnabled())
					enabledEntriesLeft++;
			} else {
				GECAMedUtils.insertIntoArray(consultationEntriesRight, cons1,
						cons1.getPosition() - newColumnPosition - 1);
				if (cons1.getEnabled())
					enabledEntriesRight++;
			}

			if (cons2.getPosition() < newColumnPosition) {
				GECAMedUtils.insertIntoArray(consultationEntriesLeft, cons2, cons2.getPosition());
				if (cons2.getEnabled())
					enabledEntriesLeft++;
			} else {
				GECAMedUtils.insertIntoArray(consultationEntriesRight, cons2,
						cons2.getPosition() - newColumnPosition - 1);
				if (cons2.getEnabled())
					enabledEntriesRight++;
			}

			if (cons3.getPosition() < newColumnPosition) {
				GECAMedUtils.insertIntoArray(consultationEntriesLeft, cons3, cons3.getPosition());
				if (cons3.getEnabled())
					enabledEntriesLeft++;
			} else {
				GECAMedUtils.insertIntoArray(consultationEntriesRight, cons3,
						cons3.getPosition() - newColumnPosition - 1);
				if (cons3.getEnabled())
					enabledEntriesRight++;
			}

			if (measurement.getPosition() < newColumnPosition) {
				GECAMedUtils.insertIntoArray(consultationEntriesLeft, measurement, measurement.getPosition());
				if (measurement.getEnabled())
					enabledEntriesLeft++;
			} else {
				GECAMedUtils.insertIntoArray(consultationEntriesRight, measurement,
						measurement.getPosition() - newColumnPosition - 1);
				if (measurement.getEnabled())
					enabledEntriesRight++;
			}

			if (sickLeave.getPosition() < newColumnPosition) {
				GECAMedUtils.insertIntoArray(consultationEntriesLeft, sickLeave, sickLeave.getPosition());
				if (sickLeave.getEnabled())
					enabledEntriesLeft++;
			} else {
				GECAMedUtils.insertIntoArray(consultationEntriesRight, sickLeave,
						sickLeave.getPosition() - newColumnPosition - 1);
				if (sickLeave.getEnabled())
					enabledEntriesRight++;
			}
		}

		// consultationEntries[soapS.getPosition()] = soapS;
		// consultationEntries[soapO.getPosition()] = soapO;
		// consultationEntries[soapA.getPosition()] = soapA;
		// consultationEntries[soapP.getPosition()] = soapP;
		// consultationEntries[cons1.getPosition()] = cons1;
		// consultationEntries[cons2.getPosition()] = cons2;
		// consultationEntries[cons3.getPosition()] = cons3;
		// consultationEntries[measurement.getPosition()] = measurement;
		// consultationEntries[sickLeave.getPosition()] = sickLeave;

		// this.undoManager = new UndoManager();
		listenersActivated = false;
		try {
			initComponents();
			initGuiEffects();

			// add changelistener
			model.addChangeListener(this);
			this.setBackground(GECAMedColors.c_GECAMedBackground);

			// check if incident is a accident
			Incident incident = this.model.getPureIncident();

			if (incident != null) {
				if (incident.getIsAccident()) {
					this.accidentPanel.setAccident(true);
				} else {

					this.accidentPanel.setAccident(false);
				}
			} else {
				this.accidentPanel.setAccident(false);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public Incident getIncident() {
		/* ================================================== */
		return this.model.getIncident();
		/* ================================================== */
	}

	/**
	 * returns the incident even if there are no changes. For niternal use only!
	 *
	 * @return
	 */
	protected Incident getForcedIncident() {
		/* ================================================== */
		return this.model.getIncidentForPrescription();
		/* ================================================== */
	}

	/**
	 * @return
	 */
	public IncidentControler getControler() {
		/* ================================================== */
		return this.controler;
		/* ================================================== */
	}

	/***************************************************************************
	 * Controls
	 */

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * lu.tudor.santec.gecamed.prescription.gui.util.IChangeListener#fireEvent()
	 *
	 * called when the model has changed
	 */
	public void fireEvent() {
		/* ============================================= */
		listenersActivated = false;
		// accident
		if (model.getAccidentNr() != null)
			this.accidentPanel.setAccidentNumber(model.getAccidentNr());
		if (model.getAccidentDate() != null)
			this.accidentPanel.setAccidentDate(model.getAccidentDate());

		// update fields
		// anamnesis soapS
		if (this.soapSPanel != null) {
			this.soapSPanel.setCode(model.getEntryCode(IncidentManager.SOAP_S));
			this.soapSPanel.setText(model.getEntryTextContent(IncidentManager.SOAP_S));
		}

		// finding soapO
		if (this.soapOPanel != null) {
			this.soapOPanel.setCode(model.getEntryCode(IncidentManager.SOAP_O));
			this.soapOPanel.setText(model.getEntryTextContent(IncidentManager.SOAP_O));
		}

		// diagnostic soapA
		if (this.soapAPanel != null) {
			this.soapAPanel.setCode(model.getEntryCode(IncidentManager.SOAP_A));
			this.soapAPanel.setText(model.getEntryTextContent(IncidentManager.SOAP_A));
		}

		// treatement soapP
		if (this.soapPPanel != null) {
			this.soapPPanel.setCode(model.getEntryCode(IncidentManager.SOAP_P));
			this.soapPPanel.setText(model.getEntryTextContent(IncidentManager.SOAP_P));
		}

		// cons 1
		if (this.cons1Panel != null) {
			this.cons1Panel.setCode(model.getEntryCode(IncidentManager.CONS_1));
			this.cons1Panel.setText(model.getEntryTextContent(IncidentManager.CONS_1));
		}

		// cons 2
		if (this.cons2Panel != null) {
			this.cons2Panel.setCode(model.getEntryCode(IncidentManager.CONS_2));
			this.cons2Panel.setText(model.getEntryTextContent(IncidentManager.CONS_2));
		}

		// cons 3
		if (this.cons3Panel != null) {
			this.cons3Panel.setCode(model.getEntryCode(IncidentManager.CONS_3));
			this.cons3Panel.setText(model.getEntryTextContent(IncidentManager.CONS_3));
		}

		// measurement
		if (this.measurementPanel != null) {
			this.sysField.setText(model.getMeasurementValue(IncidentManager.SYS, true));
			this.diaField.setText(model.getMeasurementValue(IncidentManager.DIA, true));
			this.poulseField.setText(model.getMeasurementValue(IncidentManager.POULSE, true));

			if (!model.getMeasurementValue(IncidentManager.HEIGHT, true).isEmpty()) {
				Double tmpHeight = Double.parseDouble(model.getMeasurementValue(IncidentManager.HEIGHT, true));

				// To only show 2 digits
				DecimalFormat twoDecimals = new DecimalFormat("#.##");

				// Means we entered in meters
				if (tmpHeight < 3) {
					this.heightField.setText(twoDecimals.format((tmpHeight * 100)));
				} else {
					// If centimeters
					this.heightField.setText(twoDecimals.format(tmpHeight));
				}
			} else {
				this.heightField.setText(model.getMeasurementValue(IncidentManager.HEIGHT, true));
			}

			this.weightField.setText(model.getMeasurementValue(IncidentManager.WEIGHT, true));
			// update generic fields
			this.measField1.setText(model.getMeasurementValue(IncidentManager.MEAS_1));
			this.measField2.setText(model.getMeasurementValue(IncidentManager.MEAS_2));
			this.measField3.setText(model.getMeasurementValue(IncidentManager.MEAS_3));
		}

		// sickleave
		if (this.sickLeavePanel != null) {
			this.sickLeaveStartDateChooser.setDate(model.getSickLeaveStartDate(IncidentManager.SICK_LEAVE));
			this.sickLeaveEndDateChooser.setDate(model.getSickLeaveEndDate(IncidentManager.SICK_LEAVE));
			this.sickLeaveCodeField.setText(model.getEntryCode(IncidentManager.SICK_LEAVE));

			if (this.sickLeaveCodeField.getText().equals("")) {
				sickLeaveStartDateLabel.setEnabled(false);
				sickLeaveEndDateLabel.setEnabled(false);
				sickLeaveStartDateChooser.setEnabled(false);
				sickLeaveEndDateChooser.setEnabled(false);
			} else {
				sickLeaveStartDateLabel.setEnabled(true);
				sickLeaveEndDateLabel.setEnabled(true);
				sickLeaveStartDateChooser.setEnabled(true);
				sickLeaveEndDateChooser.setEnabled(true);
			}
		}
		startSetTitle();

		listenersActivated = true;
		/* ============================================= */
	}

	public void startSetTitle() {

		// try to get a title
		if (model.getIncidentForPrescription() != null
				&& model.getIncidentForPrescription().getIncidentDate() != null) {
			// make an asterisk if modified
			if (model.isModified())
				this.setTitle(formater.format(model.getIncidentForPrescription().getIncidentDate()) + " *");
			else
				this.setTitle(formater.format(model.getIncidentForPrescription().getIncidentDate()));
		} else if (model.isModified()) {
			this.setTitle(Translatrix.getTranslationString("patient.incident.new") + " *");
		} else
			this.setTitle(Translatrix.getTranslationString("patient.incident.new"));
	}

	/**
	 * Init the nice gui effects =)
	 */
	private void initGuiEffects() {
		/* ====================================================== */

		addFocusKeyListenerToPanels();

		/*
		 * fist, the accident icon If there is no entry for accident number or
		 * date, the accident icon will be diabled
		 */
		initAccidentIconEffect();

		// /*
		// * The BMI calculation
		// */
		// initBMIEffect();
		// /*
		// * Effects for the measurment fields like, selection on focus focus
		// * cycle
		// */
		// initMeasurementFieldEffects();
		/* ====================================================== */
	}

	/**
	 * Init the effects for the measurement fields
	 */
	private void initMeasurementFieldEffects() {
		/* ============================================= */

		// UndoManager
		// final UndoManager un = new UndoManager();
		// KeyListener k = new KeyAdapter() {
		//
		// /* (non-Javadoc)
		// * @see java.awt.event.KeyAdapter#keyTyped(java.awt.event.KeyEvent)
		// */
		// @Override
		// public void keyPressed(KeyEvent e) {
		// /* ============================================= */
		// if (e.isControlDown() && e.getKeyCode() == 90) { // Z
		//// un.end();
		// if (un.canUndo()) {
		// un.undo();
		// ((Component)e.getSource()).requestFocus();
		// }
		// }
		// /* ============================================= */
		// }
		// };

		// for (JTextField f : mFields) {
		// /* ------------------------------------------------------ */
		// // set the focus abdabter
		// f.addFocusListener(focusAdapter);
		// f.getDocument().addUndoableEditListener(un);
		// f.addKeyListener(k);
		// f.addKeyListener(focusKeyListener);
		/* ------------------------------------------------------ */
		// }

		bmiField.setFocusable(false);

		// MeasurementFocusTraversalPolicy mftp = new
		// MeasurementFocusTraversalPolicy();
		//
		// measurementPanel.setFocusCycleRoot(true);
		// measurementPanel.setFocusTraversalPolicy(mftp);

	}

	/**
	 * fist, the accident icon If there is no entry for accident number or date,
	 * the accident icon will be diabled
	 */
	private void initAccidentIconEffect() {

		// accident number field key listener
		if (this.accidentPanel != null) {
			this.accidentPanel.getAccidentNumberTextField().addKeyListener(new KeyListener() {
				public void keyTyped(KeyEvent e) {
				}

				public void keyReleased(KeyEvent e) {
					multiplePurposeDocumentListen();
				}

				public void keyPressed(KeyEvent e) {
				}
			});

			// date chooser accident panel action listener
			this.accidentPanel.getAccidentDateChooser().getCalendarButton().addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					multiplePurposeDocumentListen();
				}
			});

			// checkbox accident panel
			this.accidentPanel.getAccidentCheckBox().addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					if (accidentPanel.getAccidentCheckBox().isSelected()) {
						model.setAccidenNr(accidentPanel.getAccidentNumber());
						model.setAccidentDate(accidentPanel.getAccidentDate());

					} else {
						model.setAccidenNr(null);
						model.setAccidentDate(null);
					}
					multiplePurposeDocumentListen();
				}
			});
		}
	}

	/**
	 * Init the bmi calculation
	 */
	private void initBMIEffect() {
		/* ====================================================== */
		// create a document listener for the
		// height and weight field
		DocumentListener bmiListener = new DocumentListener() {

			private DecimalFormat dFormater = new DecimalFormat();

			public void changedUpdate(DocumentEvent e) {
				doCalc(e);
			}

			public void insertUpdate(DocumentEvent e) {
				doCalc(e);
			}

			public void removeUpdate(DocumentEvent e) {
				doCalc(e);
			}

			private void doCalc(@SuppressWarnings("unused") DocumentEvent e) {
				/* ====================================================== */
				Double height = null;
				Double weight = null;

				// try to get the height
				try {
					Double tmpHeight;
					tmpHeight = Double.parseDouble(heightField.getText().replaceAll(",", "."));

					// Means we entered in meters
					if (tmpHeight < 3) {
						height = tmpHeight;
					} else {
						// If centimeters -> Show in meters
						height = tmpHeight / 100;
					}

				} catch (Exception e1) {
					// height = null;
				}
				// try to get the weight
				try {
					weight = Double.parseDouble(weightField.getText().replaceAll(",", "."));
				} catch (Exception e2) {
					// weight = null;
				}
				/* ------------------------------------------------------ */
				// calc
				if (weight != null && height != null) {
					/* ------------------------------------------------------ */
					double bmi = ((weight / (height * height)));
					// set
					bmiField.setText("" + dFormater.format(bmi));
					/* ------------------------------------------------------ */
				} else
					// clear the bmi field
					bmiField.setText("");

				/* ====================================================== */
			}

		};

		heightField.getDocument().addDocumentListener(bmiListener);
		weightField.getDocument().addDocumentListener(bmiListener);

		/* ====================================================== */
	}

	private void initListeners() {
		/* ====================================================== */
		this.focusKeyListener = new KeyListener() {

			public void keyTyped(KeyEvent e) {
				if (e.getSource() instanceof JTextArea) {
					if (e.getKeyCode() == KeyEvent.VK_TAB) {
						e.consume();
					}
				}
			}

			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_TAB) {
					if (e.getSource() instanceof JTextArea) {
						UndoTextArea lastTextfield = null;
						for (int i = 0; i < consultationEntriesLeft.length; i++) {
							if (consultationEntriesLeft[i].getEnabled()) {
								String cecId = consultationEntriesLeft[i].getId();
								if (cecId.equals(IncidentManager.SOAP_S)) {
									lastTextfield = soapSPanel.getContentTextArea();
								}
								if (cecId.equals(IncidentManager.SOAP_O)) {
									lastTextfield = soapOPanel.getContentTextArea();
								}
								if (cecId.equals(IncidentManager.SOAP_A)) {
									lastTextfield = soapAPanel.getContentTextArea();
								}
								if (cecId.equals(IncidentManager.SOAP_P)) {
									lastTextfield = soapPPanel.getContentTextArea();
								}
								if (cecId.equals(IncidentManager.CONS_1)) {
									lastTextfield = cons1Panel.getContentTextArea();
								}
								if (cecId.equals(IncidentManager.CONS_1)) {
									lastTextfield = cons1Panel.getContentTextArea();
								}
								if (cecId.equals(IncidentManager.CONS_2)) {
									lastTextfield = cons2Panel.getContentTextArea();
								}
								if (cecId.equals(IncidentManager.CONS_3)) {
									lastTextfield = cons3Panel.getContentTextArea();
								}
							}
						}

						if (e.getSource().equals(lastTextfield)) {
							if (consultationEntriesRight != null && enabledEntriesRight > 0) {
								for (int i = 0; i < consultationEntriesRight.length; i++) {
									if (consultationEntriesRight[i].getEnabled()) {
										String cecId = consultationEntriesRight[i].getId();
										if (cecId.equals(IncidentManager.SOAP_S)) {
											soapSPanel.getContentTextArea().requestFocus();
										}
										if (cecId.equals(IncidentManager.SOAP_O)) {
											soapOPanel.getContentTextArea().requestFocus();
										}
										if (cecId.equals(IncidentManager.SOAP_A)) {
											soapAPanel.getContentTextArea().requestFocus();
										}
										if (cecId.equals(IncidentManager.SOAP_P)) {
											soapPPanel.getContentTextArea().requestFocus();
										}
										if (cecId.equals(IncidentManager.CONS_1)) {
											cons1Panel.getContentTextArea().requestFocus();
										}
										if (cecId.equals(IncidentManager.CONS_1)) {
											cons1Panel.getContentTextArea().requestFocus();
										}
										if (cecId.equals(IncidentManager.CONS_2)) {
											cons2Panel.getContentTextArea().requestFocus();
										}
										if (cecId.equals(IncidentManager.CONS_3)) {
											cons3Panel.getContentTextArea().requestFocus();
										}
										e.consume();
										break;
									}
								}
							}
							((JTextArea) e.getSource()).transferFocus();
							e.consume();
						} else {
							((JTextArea) e.getSource()).transferFocus();
							e.consume();
						}
					}
				}
			}

			public void keyReleased(KeyEvent e) {
				if (e.getSource() instanceof JTextArea) {
					if (e.getKeyCode() == KeyEvent.VK_TAB) {
						e.consume();
					}
				}
			}
		};
		// create a focus listener
		// this.focusKeyListener = new KeyAdapter() {
		//
		// /* (non-Javadoc)
		// * @see java.awt.event.KeyAdapter#keyTyped(java.awt.event.KeyEvent)
		// */
		// @Override
		// public void keyPressed(KeyEvent e) {
		// /* ============================================= */
		// if (e.getSource() instanceof JTextArea) {
		// if (e.getKeyCode() == KeyEvent.VK_TAB) {
		// /* ------------------------------------------------------ */
		//// e.consume();
		// ((JTextArea) e.getSource()).transferFocus();
		// /* ------------------------------------------------------ */
		// }
		// }
		//// if (e.getSource() instanceof JTextField) {
		// else {
		// if (e.getKeyCode() == KeyEvent.VK_ENTER) {
		// /* ------------------------------------------------------ */
		//// e.consume();
		// ((JComponent) e.getSource()).transferFocus();
		// /* ------------------------------------------------------ */
		// }
		// }
		// }
		// };
	}

	/*
	 * --------------------------------------------------------------- End of
	 * Constrols *************************************************************
	 */

	/***************************************************************************
	 * GUI stuff
	 */

	/**
	 * Init the gui components
	 */
	private void initComponents() {
		/* ============================================= */
		// set border layout
		this.setLayout(new BorderLayout());
		this.cc = new CellConstraints();
		// default columns layout
		String cols = "1dlu,fill:200dlu," + // consultation entries
				"1dlu,fill:100dlu:grow," + // consultation entries &
											// prescription & important data
											// panel
				"1dlu";

		/*
		 * The panel is build of one single center panel for the SOAP panels and
		 * the important,prescription panel We use formlayout for the center
		 * panel
		 */
		/* ------------------------------------------------------ */
		this.centerPanel = new JPanel(new FormLayout(cols,
				// rows
				"3dlu," + "fill:100dlu:grow," + "3dlu"));
		/* ------------------------------------------------------ */
		initListeners();

		centerPanel.setOpaque(OPAQUE);

		// check columns for the consultation entries and init the needed panels
		if (enabledEntriesLeft > 0 && enabledEntriesRight > 0) {
			initfirstConsultationEntryPanel(consultationEntriesLeft);
			initSecondConsultationEntryPanel(enabledEntriesRight);
		} else {
			if (enabledEntriesLeft > 0)
				initfirstConsultationEntryPanel(consultationEntriesLeft);
			else if (enabledEntriesRight > 0)
				initfirstConsultationEntryPanel(consultationEntriesRight);
		}
		initRightPanel();

		// add first consultationEntry panel
		if (soapPanel != null) {
			centerPanel.add(soapPanel, cc.xy(2, 2));
		}
		if (rightPanel != null) {
			centerPanel.add(rightPanel, cc.xy(4, 2));
		}
		/* ------------------------------------------------------ */
		this.scroll = new JScrollPane(centerPanel);

		scroll.getViewport().setOpaque(false);
		scroll.setOpaque(false);

		this.add(centerPanel, BorderLayout.CENTER);

		/* ============================================= */
	}

	/**
	 * Init the right panel for important data and prescription
	 */
	private void initRightPanel() {
		/* ============================================= */
		String cols = "0dlu," + "fill:100dlu:grow," + // prescription &
														// important data panel
				"0dlu";

		// check columns for the consultation entries and edit the laylout
		if (enabledEntriesLeft > 0 && enabledEntriesRight > 0) {
			cols = "0dlu," + "fill:200dlu:grow," + // consultation entries &
													// important data panel
					"1dlu," + "fill:100dlu:grow," + // prescription & important
													// data panel
					"0dlu";
		}

		this.rightPanel = new JPanel(new FormLayout(
				// cols
				cols,
				// rows
				"0dlu," + // 1
						"fill:120dlu," + // 2
						"3dlu," + // 3
						"fill:100dlu:grow," + // 4
						"0dlu")); // 5
		rightPanel.setOpaque(OPAQUE);

		if (enabledEntriesLeft > 0 && enabledEntriesRight > 0) {
			// init the consultation entries pannel
			initSecondConsultationEntryPanel(enabledEntriesRight);
			// add the important data panel
			importantDataPanel = this.patientPanel.getImportantDataModel().getImportantDataPanelView(false);
			rightPanel.add(new JScrollPane(importantDataPanel), cc.xywh(2, 2, 3, 1));
			// add the consultation entries pannel and prescription panel
			JPanel subPanel = new JPanel(new FormLayout(
					// rows
					"0dlu," + "fill:200dlu," + // consultation entries
							"1dlu," + "fill:300dlu:grow," + // prescription
							"0dlu",
					// columns
					"0dlu," + "fill:100dlu:grow," + "0dlu"));

			subPanel.setOpaque(OPAQUE);
			subPanel.add(this.secondConsultationEntryPanel, cc.xy(2, 2));
			subPanel.add(this.patientPanel.getPrescriptionDataModel().getPrescriptionPanelView(true), cc.xy(4, 2));
			// init scroll panel
			JScrollPane scrollPane = new JScrollPane(subPanel);
			scrollPane.setOpaque(OPAQUE);
			scrollPane.getViewport().setOpaque(OPAQUE);
			// add scroll panel
			rightPanel.add(scrollPane, cc.xywh(2, 4, 3, 1));
		} else {
			// add the important data panel
			importantDataPanel = this.patientPanel.getImportantDataModel().getImportantDataPanelView(false);
			rightPanel.add(new JScrollPane(importantDataPanel), cc.xy(2, 2));
			// add the prescription pannel
			rightPanel.add(new JScrollPane(this.patientPanel.getPrescriptionDataModel().getPrescriptionPanelView(true)),
					cc.xy(2, 4));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see lu.tudor.santec.gecamed.core.gui.GECAMedTab#preparetoShowup()
	 */
	@Override
	public void preparetoShowup() {
		/* ====================================================== */
		/* ====================================================== */
	}

	/**
	 * Init the measurement panel
	 */
	private void initMeasurementPanel(ConsultationEntryConfig entryConfig) {
		/* ====================================================== */
		JLabel iconLabel;
		JLabel topicLabel;

		CellConstraints cc = new CellConstraints();
		this.measurementPanel = new JPanel(new FormLayout(
				// cols
				"1dlu," + "fill:pref," + // 2
						"0dlu," + // 1
						"fill:pref," + // 2
						"3dlu," + // 3
						"fill:pref," + // 4
						"3dlu," + // 5
						"fill:pref:grow," + // 6
						"2dlu," + // 7
						"fill:pref," + // 8
						"1dlu", // 9
				// rows
				"1dlu," + // 1
						"center:pref," + // 2
						"fill:pref:grow," + // 3
						"1dlu," + // 4
						"fill:pref:grow," + // 5 // accidentPanel
						"1dlu" // 6
		));

		this.measurementPanel.setOpaque(OPAQUE);
		this.measurementPanel.setBorder(new TitledBorder(""));

		/* ------------------------------------------------------ */
		// icon label
		iconLabel = new JLabel("<html>&nbsp;" + entryConfig.getAcronym() + "&nbsp;");

		// iconLabel.setForeground(Color.WHITE);
		iconLabel.setBackground(new Color(entryConfig.getColor()));
		iconLabel.setOpaque(true);

		// topic label
		// get name of translatrix if possible
		// String translatrixName = "patient.incident." + entryConfig.getName();
		//
		// if(Translatrix.getTranslationString(translatrixName) !=
		// translatrixName)
		// {
		// topicLabel = new JLabel("<html>"
		// + Translatrix.getTranslationString(translatrixName)
		// + "&nbsp;&nbsp;");
		// }else{
		// topicLabel = new JLabel(entryConfig.getName());
		// }

		topicLabel = new JLabel(entryConfig.getTranslatedName());
		this.measurementPanel.add(GradientFactory.makeGradient(iconLabel, new Color(entryConfig.getColor()), true),
				cc.xy(2, 2));
		this.measurementPanel.add(GradientFactory.makeGradient(topicLabel, new Color(entryConfig.getColor()), true),
				cc.xy(4, 2));

		// topicLabel.setIcon(IconFetcher.getSmallIcon(PatientManagerModule.class,
		// PatientManagerModule.SOAP_S));

		topicLabel.setBackground(new Color(entryConfig.getColor()));
		topicLabel.setOpaque(true);

		JPanel mainPanel = new JPanel(new FormLayout(
				// cols
				"0dlu," + "fill:pref," + "1dlu," + "fill:pref," + "1dlu," + "fill:pref," + "1dlu," + "fill:pref,"
						+ "0dlu",
				// rows
				"3dlu," + "fill:pref," + "0dlu"));

		mainPanel.setOpaque(OPAQUE);
		/* ------------------------------------------------------ */
		// set border
		// measurementPanel.setBorder(new TitledBorder(
		// Translatrix.getTranslationString("patient.incident.measurement")));
		// measurementPanel.setBorder(BorderFactory.createTitledBorder(""));
		/* ------------------------------------------------------ */
		/* ------------------------------------------------------ */
		// create fields
		/* ------------------------------------------------------ */
		// labels
		JLabel sysLabel = new JLabel(Translatrix.getTranslationString("patient.incident.measurement.sys") + ":");
		JLabel diaLabel = new JLabel(Translatrix.getTranslationString("patient.incident.measurement.dia") + ":");
		JLabel poulseLabel = new JLabel(Translatrix.getTranslationString("patient.incident.measurement.poulse") + ":");
		JLabel heightLabel = new JLabel(Translatrix.getTranslationString("patient.incident.measurement.height") + ":");
		JLabel weightLabel = new JLabel(Translatrix.getTranslationString("patient.incident.measurement.weight") + ":");
		JLabel bmiLabel = new JLabel(Translatrix.getTranslationString("patient.incident.measurement.bmi") + ":");
		/* ------------------------------------------------------ */
		// textfields
		/* ------------------------------------------------------- */
		int cols = 5;

		this.sysField = new NumberField();
		this.diaField = new NumberField();
		this.poulseField = new NumberField();
		this.heightField = new NumberField();
		this.weightField = new NumberField();

		this.bmiField = new UndoTextField(cols, new UndoManager());
		/* ------------------------------------------------------- */
		// generic fields
		this.measField1 = new UndoTextField(cols, new UndoManager());
		this.measField2 = new UndoTextField(cols, new UndoManager());
		this.measField3 = new UndoTextField(cols, new UndoManager());
		/* ------------------------------------------------------- */

		this.mFields = new ArrayList<JTextField>();
		mFields.add(sysField);
		mFields.add(diaField);
		mFields.add(poulseField);
		mFields.add(heightField);
		mFields.add(weightField);
		// ------------------------
		mFields.add(measField1);
		mFields.add(measField2);
		mFields.add(measField3);

		int fieldHeight = 15;

		bmiField.setEditable(false);
		bmiField.setPreferredSize(new Dimension((int) bmiField.getPreferredSize().getWidth(), fieldHeight));

		for (JTextField f : mFields) {
			/* ------------------------------------------------------ */
			f.getDocument().addDocumentListener(this);
			f.setColumns(4);
			// set the field height
			f.setPreferredSize(new Dimension((int) f.getPreferredSize().getWidth(), fieldHeight));
			/* ------------------------------------------------------ */
		}

		/* ------------------------------------------------------ */
		String pCols = "2dlu, fill:pref,1dlu, fill:pref, 1dlu, fill:pref, 2dlu";
		String pRows = "0dlu, fill:pref, 1dlu, fill:pref, 1dlu, fill:pref, 0dlu";

		// assemble the first panel
		JPanel p1 = new JPanel(new FormLayout(pCols, pRows));
		p1.setOpaque(OPAQUE);
		/* ------------------------------------------------------ */
		p1.add(sysLabel, cc.xy(2, 2));
		p1.add(sysField, cc.xy(4, 2));
		p1.add(new FLabel("mmHg"), cc.xy(6, 2));

		p1.add(diaLabel, cc.xy(2, 4));
		p1.add(diaField, cc.xy(4, 4));
		p1.add(new FLabel("mmHg"), cc.xy(6, 4));

		p1.add(poulseLabel, cc.xy(2, 6));
		p1.add(poulseField, cc.xy(4, 6));
		p1.add(new FLabel("bpm"), cc.xy(6, 6));
		/* ------------------------------------------------------ */
		// assemble the second panel
		JPanel p2 = new JPanel(new FormLayout(pCols, pRows));
		p2.setOpaque(OPAQUE);
		/* ------------------------------------------------------ */
		p2.add(heightLabel, cc.xy(2, 2));
		p2.add(heightField, cc.xy(4, 2));
		p2.add(new FLabel("cm"), cc.xy(6, 2));

		p2.add(weightLabel, cc.xy(2, 4));
		p2.add(weightField, cc.xy(4, 4));
		p2.add(new FLabel("kg"), cc.xy(6, 4));

		p2.add(bmiLabel, cc.xy(2, 6));
		p2.add(bmiField, cc.xy(4, 6));
		p2.add(new FLabel("kg/m" + "\u00B2"), cc.xy(6, 6)); // "\u00B2" unicode
															// for squared
		/* ------------------------------------------------------ */
		// assemble the third panel for generic fields
		JPanel p3 = new JPanel(new FormLayout(pCols, pRows));
		p3.setOpaque(OPAQUE);
		// first field
		if ((Boolean) PatientManagerModule.getInstance().patientSettings.getValue(IncidentManager.MEAS_1)) {
			/* ------------------------------------------------------- */
			MeasurementType t = PatientManagerModule.getInstance().patientSettings.getType(IncidentManager.MEAS_1);
			if (t != null) {
				p3.add(new JLabel(t.getAlias() + ":"), cc.xy(2, 2));
				p3.add(measField1, cc.xy(4, 2));
				p3.add(new FLabel(t.getUnit()), cc.xy(6, 2));
			}
			/* ------------------------------------------------------- */
		}
		// second field
		if ((Boolean) PatientManagerModule.getInstance().patientSettings.getValue(IncidentManager.MEAS_2)) {
			/* ------------------------------------------------------- */
			MeasurementType t = PatientManagerModule.getInstance().patientSettings.getType(IncidentManager.MEAS_2);
			if (t != null) {
				p3.add(new JLabel(t.getAlias() + ":"), cc.xy(2, 4));
				p3.add(measField2, cc.xy(4, 4));
				p3.add(new FLabel(t.getUnit()), cc.xy(6, 4));
			}
			/* ------------------------------------------------------- */
		}
		// third field
		if ((Boolean) PatientManagerModule.getInstance().patientSettings.getValue(IncidentManager.MEAS_3)) {
			/* ------------------------------------------------------- */
			MeasurementType t = PatientManagerModule.getInstance().patientSettings.getType(IncidentManager.MEAS_3);
			if (t != null) {
				p3.add(new JLabel(t.getAlias() + ":"), cc.xy(2, 6));
				p3.add(measField3, cc.xy(4, 6));
				p3.add(new FLabel(t.getUnit()), cc.xy(6, 6));
			}
			/* ------------------------------------------------------- */
		}
		/* ------------------------------------------------------ */
		// add to the measurement panel
		mainPanel.add(p1, cc.xy(2, 2));
		mainPanel.add(p2, cc.xy(4, 2));
		mainPanel.add(p3, cc.xy(6, 2));
		/* ------------------------------------------------------ */
		/* ====================================================== */
		/* ------------------------------------------------------ */
		// center
		/* ------------------------------------------------------- */
		// anamnesisPanel.add(aScroll, cc.xywh(2, 3, 7, 1));
		this.measurementPanel.add(mainPanel, cc.xywh(2, 3, 7, 1));

		/*
		 * The BMI calculation
		 */
		initBMIEffect();
		/*
		 * Effects for the measurment fields like, selection on focus focus
		 * cycle
		 */
		initMeasurementFieldEffects();
	}

	/**
	 * Init anamnesis panel
	 */
	// private void initAnamnesisPanel() {
	// /* ====================================================== */
	// this.anamnesisPanel = new JPanel(new FormLayout(
	// // cols
	// "1dlu," + // 1
	// "fill:pref," + // 2
	// "3dlu," + // 3
	// "fill:pref," + // 4
	// "3dlu," + // 5
	// "fill:pref:grow," + // 6
	// "2dlu," + // 7
	// "fill:pref," + // 8
	// "1dlu", // 9
	// // rows
	// "1dlu," + // 1
	// "center:pref," + // 2
	// "fill:2dlu:grow," + // 3
	// "1dlu," + // 4
	// "fill:pref," + // 5 // accidentPanel
	// "1dlu" // 6
	// ));
	//
	// anamnesisPanel.setOpaque(OPAQUE);
	// anamnesisPanel.setBorder(new TitledBorder(""));
	//
	// /* ------------------------------------------------------ */
	// // topic label
	// JLabel topic = new JLabel("<html>"
	// + Translatrix.getTranslationString("patient.incident.soap.s")
	// + "&nbsp;&nbsp;");
	// topic.setIcon(IconFetcher.getSmallIcon(PatientManagerModule.class,
	// PatientManagerModule.SOAP_S));
	// topic.setBackground(new Color(197, 230, 254));
	// topic.setOpaque(true);
	//
	// /* ------------------------------------------------------ */
	// // code
	// JLabel codeLabel = new JLabel(Translatrix
	// .getTranslationString("patient.incident.code")
	// + ":");
	//
	// this.anamnesisCodeField = new UndoTextField(new UndoManager());
	// anamnesisCodeField.getDocument().addDocumentListener(this);
	//
	//
	// // a button for a search in some codes
	//
	// /* ------------------------------------------------------ */
	// // center
	// /* ------------------------------------------------------ */
	// // the center is one large textarea
	// this.anamnesisTextArea = new UndoTextArea(new UndoManager());
	// anamnesisTextArea.getDocument().addDocumentListener(this);
	// anamnesisTextArea.setLineWrap(true);
	// anamnesisTextArea.setFont(GECAMedFonts.TEXTFIELD_FONT);
	//
	// AutoCompletionTextComponent actc = new
	// GECAMedAutoCompletionTextComponent(
	// anamnesisTextArea, GECAMedAutoCompletionHandler.ANAMNESIS_CONTEXT);
	//
	//// JScrollPane aScroll = new JScrollPane(anamnesisTextArea);
	//// aScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
	//
	// // accindetPanel
	//// this.accidentPanel = new AccidentPanel();
	// /* ------------------------------------------------------ */
	// // assemble panel
	// // header
	// /* ------------------------------------------------------- */
	// anamnesisPanel.add(GradientFactory.makeGradient(topic, new Color(197,
	// 230, 254), true), cc.xy(2, 2));
	// anamnesisPanel.add(codeLabel, cc.xy(4, 2));
	// anamnesisPanel.add(anamnesisCodeField, cc.xy(6, 2));
	//
	// /* ------------------------------------------------------ */
	// // center
	// /* ------------------------------------------------------- */
	//// anamnesisPanel.add(aScroll, cc.xywh(2, 3, 7, 1));
	// anamnesisPanel.add(actc, cc.xywh(2, 3, 7, 1));
	//// anamnesisPanel.add(accidentPanel, cc.xywh(2, 5, 7, 1));
	// /* ====================================================== */
	// }

	/**
	 * Init the effects for the anamnesis components like listeners etc
	 */
	private void addFocusKeyListenerToPanels() {
		// TODO bug
		// set the focus key listener for the fields

		if (this.accidentPanel != null) {
			this.accidentPanel.getAccidentNumberTextField().addKeyListener(focusKeyListener);
			this.accidentPanel.getAccidentDateChooser().addKeyListener(focusKeyListener);
			this.accidentPanel.getAccidentDateChooser().addPropertyChangeListener("date", this);
		}
		if (this.soapSPanel != null) {
			if (this.soapSPanel.getEntryConfig().getContentField())
				this.soapSPanel.getContentTextArea().addKeyListener(focusKeyListener);
		}

		if (this.soapOPanel != null) {
			if (this.soapOPanel.getEntryConfig().getContentField())
				this.soapOPanel.getContentTextArea().addKeyListener(focusKeyListener);
		}

		if (this.soapAPanel != null) {
			if (this.soapAPanel.getEntryConfig().getContentField())
				this.soapAPanel.getContentTextArea().addKeyListener(focusKeyListener);
		}

		if (this.soapPPanel != null) {
			if (this.soapPPanel.getEntryConfig().getContentField())
				this.soapPPanel.getContentTextArea().addKeyListener(focusKeyListener);
		}

		if (this.cons1Panel != null) {
			if (this.cons1Panel.getEntryConfig().getContentField())
				this.cons1Panel.getContentTextArea().addKeyListener(focusKeyListener);
		}

		if (this.cons2Panel != null) {
			if (this.cons2Panel.getEntryConfig().getContentField())
				this.cons2Panel.getContentTextArea().addKeyListener(focusKeyListener);
		}

		if (this.cons3Panel != null) {
			if (this.cons3Panel.getEntryConfig().getContentField())
				this.cons3Panel.getContentTextArea().addKeyListener(focusKeyListener);
		}

	}

	/**
	 * @param ml
	 */
	protected void addAccidentDialogButtonListener(ActionListener ml) {

		if (ml == null)
			return;
		if (this.accidentPanel != null) {
			this.accidentPanel.getAccidentSelectionButton().addActionListener(ml);
		}
	}

	/**
	 * Init the sickleave panel
	 */
	private void initSickLeavePanel(DocumentListener documentListener, ConsultationEntryConfig entryConfig) {
		/* ====================================================== */
		JLabel iconLabel;
		JLabel topicLabel;

		CellConstraints cc = new CellConstraints();
		this.sickLeavePanel = new JPanel(new FormLayout(
				// cols
				"1dlu," + // 1
						"fill:pref," + // 2
						"0dlu," + // 3
						"fill:pref," + // 4
						"3dlu," + // 5
						"fill:pref," + // 6
						"3dlu," + // 7
						"fill:pref:grow," + // 8
						"2dlu," + // 9
						"fill:pref," + // 10
						"1dlu", // 11
				// rows
				"1dlu," + "pref," + "1dlu," + "fill:pref:grow," + "1dlu," + "pref," + "1dlu"));

		this.sickLeavePanel.setOpaque(OPAQUE);
		this.sickLeavePanel.setBorder(new TitledBorder(""));

		/* ------------------------------------------------------ */
		// icon label
		iconLabel = new JLabel("<html>&nbsp;" + entryConfig.getAcronym() + "&nbsp;");

		iconLabel.setBackground(new Color(entryConfig.getColor()));
		iconLabel.setOpaque(true);

		// topic label
		// get name of translatrix if possible
		// String translatrixName = "patient.incident." + entryConfig.getName();
		//
		// if(Translatrix.getTranslationString(translatrixName) !=
		// translatrixName)
		// {
		// topicLabel = new JLabel("<html>"
		// + Translatrix.getTranslationString(translatrixName)
		// + "&nbsp;&nbsp;");
		// }else{
		// topicLabel = new JLabel(entryConfig.getName());
		// }

		topicLabel = new JLabel(entryConfig.getTranslatedName());
		this.sickLeavePanel.add(GradientFactory.makeGradient(iconLabel, new Color(entryConfig.getColor()), true),
				cc.xy(2, 2));
		this.sickLeavePanel.add(GradientFactory.makeGradient(topicLabel, new Color(entryConfig.getColor()), true),
				cc.xy(4, 2));

		topicLabel.setBackground(new Color(entryConfig.getColor()));
		topicLabel.setOpaque(true);

		/* ------------------------------------------------------ */
		// code

		JLabel codeLabel;

		String translatrixCode = "patient.incident." + entryConfig.getCodeLabel();
		if (Translatrix.getTranslationString(translatrixCode) != translatrixCode) {
			codeLabel = new JLabel(Translatrix.getTranslationString(translatrixCode) + ":");
		} else {
			codeLabel = new JLabel(entryConfig.getCodeLabel());
		}
		sickLeaveCodeField = new UndoTextField(new UndoManager());
		sickLeaveCodeField.getDocument().addDocumentListener(documentListener);

		// start and end date
		JPanel datePanel = new JPanel(new FormLayout(
				// cols
				"1dlu," + // 1
						"fill:pref," + // 2
						"3dlu," + // 3
						"fill:pref:grow," + // 4
						"5dlu," + // 5
						"fill:pref," + // 6
						"3dlu," + // 7
						"fill:pref:grow," + // 8
						"1dlu", // 9
				// rows
				"1dlu," + "pref," + "1dlu"));
		datePanel.setOpaque(OPAQUE);

		sickLeaveStartDateLabel = new JLabel(
				Translatrix.getTranslationString("patient.incident.sickLeaveStartDateLabel") + ":");
		sickLeaveEndDateLabel = new JLabel(
				Translatrix.getTranslationString("patient.incident.sickLeaveEndDateLabel") + ":");

		// JSpinnerDateEditor l_DateEditor;
		// l_DateEditor = new JSpinnerDateEditor();
		// sickLeaveStartDateChooser = new JDateChooser(new Date(),
		// "yyyy-MM-dd", l_DateEditor);
		// sickLeaveStartDateChooser.setLocale(Translatrix.getLocale());
		// sickLeaveStartDateChooser.getDateEditor().setLocale(Translatrix.getLocale());
		sickLeaveStartDateChooser = GECAMedGuiUtils.getDateChooser(false);
		sickLeaveStartDateChooser.addPropertyChangeListener("date", this);
		// l_DateEditor = new JSpinnerDateEditor();
		// sickLeaveEndDateChooser = new JDateChooser(new Date(), "yyyy-MM-dd",
		// l_DateEditor);
		// sickLeaveEndDateChooser.setLocale(Translatrix.getLocale());
		// sickLeaveEndDateChooser.getDateEditor().setLocale(Translatrix.getLocale());
		sickLeaveEndDateChooser = GECAMedGuiUtils.getDateChooser(false);
		sickLeaveEndDateChooser.addPropertyChangeListener("date", this);

		datePanel.add(sickLeaveStartDateLabel, cc.xy(2, 2));
		datePanel.add(sickLeaveStartDateChooser, cc.xy(4, 2));
		datePanel.add(sickLeaveEndDateLabel, cc.xy(6, 2));
		datePanel.add(sickLeaveEndDateChooser, cc.xy(8, 2));
		// add auto completion
		AutoCompletionTextComponent sickLeaveCodeFieldActc = new GECAMedAutoCompletionTextComponent(
				this.sickLeaveCodeField, GECAMedAutoCompletionHandler.SICK_LEAVE_CONTEXT);

		// add code label, field and date choosers
		sickLeavePanel.add(codeLabel, cc.xy(6, 2));
		sickLeavePanel.add(sickLeaveCodeFieldActc, cc.xy(8, 2));
		sickLeavePanel.add(datePanel, cc.xyw(2, 4, 8));
	}

	private void initfirstConsultationEntryPanel(ConsultationEntryConfig[] consultationEntryArray) {
		int row = 0;
		StringBuilder rowLayout = new StringBuilder();

		// add position for accident panel
		rowLayout.append("0dlu,fill:pref,1dlu,");

		// calculate the row layout
		for (int i = 0; i < consultationEntryArray.length; i++) {
			if (consultationEntryArray[i] != null && consultationEntryArray[i].getEnabled()) {
				if (consultationEntryArray[i].getId().equals(IncidentManager.MEASUREMENT)
						|| consultationEntryArray[i].getId().equals(IncidentManager.SICK_LEAVE)
						|| !consultationEntryArray[i].getContentField()) {
					// components containing only text fields get their
					// preferred height and don't need to grow
					rowLayout.append("fill:pref");
				} else {
					// text areas have a minimum height and grow with the panel
					rowLayout.append("fill:25dlu:grow");
				}

				// add a separation, if this wasn't the last row to append
				if (i < consultationEntryArray.length - 1)
					rowLayout.append(",1dlu,");
			}
		}

		this.soapPanel = new JPanel(new FormLayout(
				// cols
				"0dlu,fill:pref:grow,0dlu",
				// rows
				rowLayout.toString()));
		soapPanel.setOpaque(OPAQUE);

		// add accindetPanel
		this.accidentPanel = new AccidentPanel();
		soapPanel.add(accidentPanel, cc.xy(2, row += 2));

		// add the other Panels
		for (int i = 0; i < consultationEntryArray.length; i++) {
			if (consultationEntryArray[i] != null && consultationEntryArray[i].getEnabled()) {
				if (consultationEntryArray[i].getId().equals(IncidentManager.SOAP_S)) {
					soapSPanel = new ConsultationEntryPanel(this, consultationEntryArray[i]);
					soapSPanel.setOpaque(OPAQUE);
					soapPanel.add(soapSPanel, cc.xy(2, row += 2));
				}
				if (consultationEntryArray[i].getId().equals(IncidentManager.SOAP_O)) {
					soapOPanel = new ConsultationEntryPanel(this, consultationEntryArray[i]);
					soapOPanel.setOpaque(OPAQUE);
					soapPanel.add(soapOPanel, cc.xy(2, row += 2));
				}
				if (consultationEntryArray[i].getId().equals(IncidentManager.SOAP_A)) {
					soapAPanel = new ConsultationEntryPanel(this, consultationEntryArray[i]);
					soapAPanel.setOpaque(OPAQUE);
					soapPanel.add(soapAPanel, cc.xy(2, row += 2));
				}
				if (consultationEntryArray[i].getId().equals(IncidentManager.SOAP_P)) {
					soapPPanel = new ConsultationEntryPanel(this, consultationEntryArray[i]);
					soapPPanel.setOpaque(OPAQUE);
					soapPanel.add(soapPPanel, cc.xy(2, row += 2));
				}
				if (consultationEntryArray[i].getId().equals(IncidentManager.CONS_1)) {
					cons1Panel = new ConsultationEntryPanel(this, consultationEntryArray[i]);
					cons1Panel.setOpaque(OPAQUE);
					soapPanel.add(cons1Panel, cc.xy(2, row += 2));
				}
				if (consultationEntryArray[i].getId().equals(IncidentManager.CONS_2)) {
					cons2Panel = new ConsultationEntryPanel(this, consultationEntryArray[i]);
					cons2Panel.setOpaque(OPAQUE);
					soapPanel.add(cons2Panel, cc.xy(2, row += 2));
				}
				if (consultationEntryArray[i].getId().equals(IncidentManager.CONS_3)) {
					cons3Panel = new ConsultationEntryPanel(this, consultationEntryArray[i]);
					cons3Panel.setOpaque(OPAQUE);
					soapPanel.add(cons3Panel, cc.xy(2, row += 2));
				}
				// add MEASURMENT and Sick_leave Panel
				if (consultationEntryArray[i].getId().equals(IncidentManager.MEASUREMENT)) {
					initMeasurementPanel(consultationEntryArray[i]);
					soapPanel.add(measurementPanel, cc.xy(2, row += 2));
				}
				if (consultationEntryArray[i].getId().equals(IncidentManager.SICK_LEAVE)) {
					initSickLeavePanel(this, consultationEntryArray[i]);
					soapPanel.add(this.sickLeavePanel, cc.xy(2, row += 2));
				}
			}
		}
	}

	private void initSecondConsultationEntryPanel(int entryNumber) {
		int z = 1;
		// int c = 0;
		String rowLayout = "0dlu,";

		for (int i = 0; i < consultationEntriesRight.length; i++) {
			if (consultationEntriesRight[i] != null && consultationEntriesRight[i].getEnabled()) {
				// c++;
				// if(c > entryNumber)
				// {
				// measurement / sickleave panel get another row layout
				if (consultationEntriesRight[i].getId().equals(IncidentManager.MEASUREMENT)
						|| consultationEntriesRight[i].getId().equals(IncidentManager.SICK_LEAVE)
						|| !consultationEntriesRight[i].getContentField()) {
					rowLayout = rowLayout + "fill:pref,";
				} else {
					rowLayout = rowLayout + "fill:2dlu:grow,";
				}
				if (z == consultationEntriesRight.length + 1)
					rowLayout = rowLayout + "0dlu";
				else
					rowLayout = rowLayout + "1dlu,";
				z++;
				// }

			}
		}

		this.secondConsultationEntryPanel = new JPanel(new FormLayout(
				// cols
				"0dlu," + "fill:pref:grow," + "0dlu",
				// rows
				rowLayout));

		secondConsultationEntryPanel.setOpaque(OPAQUE);

		// add Panels
		int row = 0;
		// c = 0;
		for (int i = 0; i < consultationEntriesRight.length; i++) {
			if (consultationEntriesRight[i] != null && consultationEntriesRight[i].getEnabled()) {
				// c++;
				// if(c > entryNumber)
				// {
				if (consultationEntriesRight[i].getId().equals(IncidentManager.SOAP_S)) {
					soapSPanel = new ConsultationEntryPanel(this, consultationEntriesRight[i]);
					secondConsultationEntryPanel.add(soapSPanel, cc.xy(2, row += 2));
				}
				if (consultationEntriesRight[i].getId().equals(IncidentManager.SOAP_O)) {
					soapOPanel = new ConsultationEntryPanel(this, consultationEntriesRight[i]);
					secondConsultationEntryPanel.add(soapOPanel, cc.xy(2, row += 2));
				}
				if (consultationEntriesRight[i].getId().equals(IncidentManager.SOAP_A)) {
					soapAPanel = new ConsultationEntryPanel(this, consultationEntriesRight[i]);
					secondConsultationEntryPanel.add(soapAPanel, cc.xy(2, row += 2));
				}
				if (consultationEntriesRight[i].getId().equals(IncidentManager.SOAP_P)) {
					soapPPanel = new ConsultationEntryPanel(this, consultationEntriesRight[i]);
					secondConsultationEntryPanel.add(soapPPanel, cc.xy(2, row += 2));
				}
				if (consultationEntriesRight[i].getId().equals(IncidentManager.CONS_1)) {
					cons1Panel = new ConsultationEntryPanel(this, consultationEntriesRight[i]);
					secondConsultationEntryPanel.add(cons1Panel, cc.xy(2, row += 2));
				}
				if (consultationEntriesRight[i].getId().equals(IncidentManager.CONS_2)) {
					cons2Panel = new ConsultationEntryPanel(this, consultationEntriesRight[i]);
					secondConsultationEntryPanel.add(cons2Panel, cc.xy(2, row += 2));
				}
				if (consultationEntriesRight[i].getId().equals(IncidentManager.CONS_3)) {
					cons3Panel = new ConsultationEntryPanel(this, consultationEntriesRight[i]);
					secondConsultationEntryPanel.add(cons3Panel, cc.xy(2, row += 2));
				}
				// add MEASURMENT and Sick_leave Panel
				if (consultationEntriesRight[i].getId().equals(IncidentManager.MEASUREMENT)) {
					initMeasurementPanel(consultationEntriesRight[i]);
					secondConsultationEntryPanel.add(measurementPanel, cc.xy(2, row += 2));
				}
				if (consultationEntriesRight[i].getId().equals(IncidentManager.SICK_LEAVE)) {
					initSickLeavePanel(this, consultationEntriesRight[i]);
					secondConsultationEntryPanel.add(this.sickLeavePanel, cc.xy(2, row += 2));
				}
				// }
			}
		}
	}
	/*
	 * --------------------------------------------------------------- End of
	 * GUI stuff *************************************************************
	 */

	/***************************************************************************
	 * Inline classes
	 */

	class MeasurementFocusTraversalPolicy extends FocusTraversalPolicy {

		@Override
		public Component getComponentAfter(Container aContainer, Component aComponent) {
			/* ============================================= */
			// get position of element
			int pos = -1;
			for (Component c : mFields) {
				pos++;
				if (aComponent.equals(c)) {
					break;
				}
			}
			/* ------------------------------------------------------ */
			if (pos < mFields.size() - 1) {
				return mFields.get(pos + 1);
			} else if (pos == mFields.size()) {
				/* ------------------------------------------------------ */
				// goto diagnostic field
				measurementPanel.setFocusCycleRoot(false);
				measurementPanel.setFocusTraversalPolicy(null);
				soapAPanel.getContentTextArea().requestFocus();
				return soapAPanel.getContentTextArea();
				// diagnosisTextArea.requestFocus();
				// return diagnosisTextArea;
				/* ------------------------------------------------------ */
			} else
				return mFields.get(0);
			/* ============================================= */
		}

		@Override
		public Component getComponentBefore(Container aContainer, Component aComponent) {
			/* ============================================= */
			// get position of element
			int pos = -1;
			for (Component c : mFields) {
				pos++;
				if (aComponent.equals(c)) {
					break;
				}
			}
			/* ------------------------------------------------------ */
			if (pos == 0) {
				// got to finding area
				return soapOPanel.getContentTextArea(); // findingTextArea;
			} else if (pos < mFields.size() - 1) {
				return mFields.get(pos - 1);
			} else
				return mFields.get(0);
			/* ============================================= */
		}

		@Override
		public Component getDefaultComponent(Container aContainer) {
			/* ============================================= */
			return sysField;
			/* ============================================= */
		}

		@Override
		public Component getFirstComponent(Container aContainer) {
			/* ============================================= */
			return mFields.get(0);
			/* ============================================= */
		}

		@Override
		public Component getLastComponent(Container aContainer) {
			/* ============================================= */
			return mFields.get(mFields.size() - 1);
			/* ============================================= */
		}

	}

	class AccidentListCellRenderer implements ListCellRenderer {

		private JLabel label;

		public AccidentListCellRenderer() {
			this.label = new JLabel();
		}

		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
				boolean cellHasFocus) {
			/* ====================================================== */
			if (value instanceof Incident) {
				/* ------------------------------------------------------- */
				Incident i = (Incident) value;
				label.setText("" + (i.getAccidentNr() != null ? i.getAccidentNr() : "") + (i.getAccidentDate() != null
						? " " + i.getAccidentDate() : "Cons Date: " + i.getIncidentDate()));
				return label;
				/* ------------------------------------------------------- */
			}
			return null;
			/* ====================================================== */
		}
	}
	/*
	 * ---------------------------------------------------------------
	 *
	 * End of Inline Classes
	 * *************************************************************
	 */

	public void changedUpdate(DocumentEvent e) {
		multiplePurposeDocumentListen();
	}

	public void insertUpdate(DocumentEvent e) {
		multiplePurposeDocumentListen();
	}

	public void removeUpdate(DocumentEvent e) {
		multiplePurposeDocumentListen();
	}

	public void propertyChange(PropertyChangeEvent evt) {

		// if accident date has change
		if (evt.getSource().equals(accidentPanel.getAccidentDateChooser())) {
			findExistingAccident(accidentPanel.getAccidentDate());
			multiplePurposeDocumentListen();
		}

		// if sick leave start date has change
		if (evt.getSource().equals(sickLeaveStartDateChooser)) {
			multiplePurposeDocumentListen();
		}

		// if sick leave end date has change
		if (evt.getSource().equals(sickLeaveEndDateChooser)) {
			multiplePurposeDocumentListen();
		}
	}

	/**
	 * write changes to the model
	 * 
	 */
	private synchronized void multiplePurposeDocumentListen() {

		if (!listenersActivated) {
			startSetTitle();
			// model.setModified(false);
			return;
		}

		listenersActivated = false;
		// mark modified
		model.setModified(true);

		// write all changes to the model
		// accident
		model.setAccidenNr(this.accidentPanel.getAccidentNumber());
		accidentPanel.setAccidentDate(accidentPanel.getAccidentDateChooser().getDate());
		model.setAccidentDate(this.accidentPanel.getAccidentDate());

		// anamnesis soapS
		if (this.soapSPanel != null) {
			model.setEntryCode(this.soapSPanel.getCode(), IncidentManager.SOAP_S);
			model.setEntryTextContent(this.soapSPanel.getText(), IncidentManager.SOAP_S);
		}

		// finding soapO
		if (this.soapOPanel != null) {
			model.setEntryCode(this.soapOPanel.getCode(), IncidentManager.SOAP_O);
			model.setEntryTextContent(this.soapOPanel.getText(), IncidentManager.SOAP_O);
		}

		// diagnosis soapA
		if (this.soapAPanel != null) {
			model.setEntryCode(this.soapAPanel.getCode(), IncidentManager.SOAP_A);
			model.setEntryTextContent(this.soapAPanel.getText(), IncidentManager.SOAP_A);
		}

		// treatment soapP
		if (this.soapPPanel != null) {
			model.setEntryCode(this.soapPPanel.getCode(), IncidentManager.SOAP_P);
			model.setEntryTextContent(this.soapPPanel.getText(), IncidentManager.SOAP_P);
		}

		// cons1
		if (this.cons1Panel != null) {
			model.setEntryCode(this.cons1Panel.getCode(), IncidentManager.CONS_1);
			model.setEntryTextContent(this.cons1Panel.getText(), IncidentManager.CONS_1);
		}

		// cons2
		if (this.cons2Panel != null) {
			model.setEntryCode(this.cons2Panel.getCode(), IncidentManager.CONS_2);
			model.setEntryTextContent(this.cons2Panel.getText(), IncidentManager.CONS_2);
		}

		// cons3
		if (this.cons3Panel != null) {
			model.setEntryCode(this.cons3Panel.getCode(), IncidentManager.CONS_3);
			model.setEntryTextContent(this.cons3Panel.getText(), IncidentManager.CONS_3);
		}
		// measurements
		if (this.measurementPanel != null) {
			try {
				model.setMeasurementValue(IncidentManager.SYS, "", getDoubleValue(sysField.getText()));
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				model.setMeasurementValue(IncidentManager.DIA, "", getDoubleValue(diaField.getText()));
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				model.setMeasurementValue(IncidentManager.POULSE, "", getDoubleValue(poulseField.getText()));
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				if (!heightField.getText().equals("")) {
					Double tmpHeight = Double.parseDouble(heightField.getText().replaceAll(",", "."));

					// Means we entered in meters
					if (tmpHeight < 3) {
						model.setMeasurementValue(IncidentManager.HEIGHT, "", tmpHeight);
					} else {
						// If centimeters -> Show in meters
						model.setMeasurementValue(IncidentManager.HEIGHT, "", tmpHeight / 100);
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				model.setMeasurementValue(IncidentManager.WEIGHT, "", getDoubleValue(weightField.getText()));
			} catch (Exception e) {
				e.printStackTrace();
			}

			Double meas1Double = null;
			try {
				meas1Double = Double.parseDouble(measField1.getText());
			} catch (Exception e) {
				// e.printStackTrace();
			}
			model.setMeasurementValue(IncidentManager.MEAS_1, measField1.getText(), meas1Double);

			Double meas2Double = null;
			try {
				meas2Double = Double.parseDouble(measField2.getText());
			} catch (Exception e) {

			}
			model.setMeasurementValue(IncidentManager.MEAS_2, measField2.getText(), meas2Double);

			Double meas3Double = null;
			try {
				meas3Double = Double.parseDouble(measField3.getText());
			} catch (Exception e) {

			}
			model.setMeasurementValue(IncidentManager.MEAS_3, measField3.getText(), meas3Double);
		}

		// sickleave
		if (sickLeavePanel != null) {
			Date startDate = sickLeaveStartDateChooser.getDate();
			Date endDate = sickLeaveEndDateChooser.getDate();

			if (startDate == null && endDate == null) {
				// do nothing and none of the other options
			} else if (endDate == null && startDate != null) {
				// set the end date to the start date
				endDate = startDate;
				sickLeaveStartDateChooser.setDate(startDate);
				sickLeaveEndDateChooser.setDate(endDate);
			} else if (startDate == null && endDate != null) {
				// set the start date to the end date
				startDate = endDate;
				sickLeaveStartDateChooser.setDate(startDate);
				sickLeaveEndDateChooser.setDate(endDate);
			} else if (startDate.after(endDate)) {
				// switch the dates
				Date tmp = startDate;
				startDate = endDate;
				endDate = tmp;
				sickLeaveStartDateChooser.setDate(startDate);
				sickLeaveEndDateChooser.setDate(endDate);
			}

			model.setSickLeaveStartDate(startDate, IncidentManager.SICK_LEAVE);
			model.setSickLeaveEndDate(endDate, IncidentManager.SICK_LEAVE);
			model.setEntryCode(this.sickLeaveCodeField.getText(), IncidentManager.SICK_LEAVE);

			if (this.sickLeaveCodeField.getText().equals("")) {
				sickLeaveStartDateLabel.setEnabled(false);
				sickLeaveEndDateLabel.setEnabled(false);
				sickLeaveStartDateChooser.setEnabled(false);
				sickLeaveEndDateChooser.setEnabled(false);
			} else {
				sickLeaveStartDateLabel.setEnabled(true);
				sickLeaveEndDateLabel.setEnabled(true);
				sickLeaveStartDateChooser.setEnabled(true);
				sickLeaveEndDateChooser.setEnabled(true);
			}
		}

		startSetTitle();
		listenersActivated = true;
	}

	private void findExistingAccident(Date date) {
		/* ================================================== */
		/* ------------------------------------------------------- */
		// try to get an existing accident number for that date and patient
		/* ------------------------------------------------------- */

		if (this.model == null || this.model.getPatient() == null || this.model.getPatient().getId() == null) {
			return;
		}
		
		List<Incident> currAccidents = PatientManagerModule.getPatientAccidents(this.model.getPatient().getId());

		if (currAccidents != null) {
			for (Incident acc : currAccidents) {
				Incident pi = model.getPureIncident();
				if (acc != null && acc.isPersistent() && pi != null && pi.isPersistent()
						&& DateUtil.isSameDay(acc.getAccidentDate(), date)
						&& !acc.getId().equals(model.getPureIncident().getId())) {
					/*
					 * -------------------------------------------------------
					 */
					// set the date and the number
					/*
					 * -------------------------------------------------------
					 */
					// listenersActivated = false;
					this.accidentPanel.setAccidentNumber(acc.getAccidentNr());
					model.getPureIncident().setParentAccidentIncidentId(acc.getId());
					// listenersActivated = true;
					break;
				}
			}
		}
	}

	/**
	 * @param value
	 * @return
	 */
	private Double getDoubleValue(String value) {
		/* ================================================== */
		if (value == null || "".equals(value))
			return null;
		/* ------------------------------------------------------- */
		try {
			/* --------------------------------------------- */
			Double b = Double.parseDouble(value.replaceFirst(",", "."));
			return b;
			/* --------------------------------------------- */
		} catch (Exception e) {
			/* --------------------------------------------- */
			return null;
			/* --------------------------------------------- */
		}
		/* ================================================== */
	}

	// ~ Inner Classes
	// ==========================================================
	class FLabel extends JLabel {

		/**
		 *
		 */
		private static final long serialVersionUID = 1L;

		public FLabel(String text) {
			super(text);
			this.setFont(new Font(this.getFont().getName(), Font.PLAIN, this.getFont().getSize() - 1));
		}
	}

	public boolean isContentModified() {
		return model.isModified();
	}

	public boolean isFirstTimeShowing() {
		return this.isFirstTimeShowing;
	}

	public void setFirstTimeShowing(boolean b) {
		this.isFirstTimeShowing = b;
	}

	public PrescriptionDataModel getPrescriptionModel() {
		return this.patientPanel.getPrescriptionDataModel();
	}

	public AccidentPanel getAccidentPanel() {
		return this.accidentPanel;
	}

	public IncidentModel getIncidentModel() {
		return this.model;
	}
}
