/*****************************************************************************
 *                                                                           *
 *  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  *
 *                                                                           *
 *****************************************************************************/
/*
 * Author: Johannes Hermen Tudor/Santec
 * Mail: johannes.hermen@tudor.lu
 * Created: Mar 3, 2005
 *
 */
package lu.tudor.santec.gecamed.patient.gui;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;

import lu.tudor.santec.gecamed.cara.gui.PatientCaraPanel;
import lu.tudor.santec.gecamed.core.gui.GECAMedAction;
import lu.tudor.santec.gecamed.core.gui.GECAMedFonts;
import lu.tudor.santec.gecamed.core.gui.GECAMedLog;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.GECAMedTab;
import lu.tudor.santec.gecamed.core.gui.IconFetcher;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.ModuleManager;
import lu.tudor.santec.gecamed.core.gui.PatientListener;
import lu.tudor.santec.gecamed.core.gui.utils.UrlOpener;
import lu.tudor.santec.gecamed.core.gui.widgets.StatusBar;
import lu.tudor.santec.gecamed.core.utils.GECAMedUtils;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.core.utils.VersionUtils;
import lu.tudor.santec.gecamed.dicom.gui.PatientDicomPanel;
import lu.tudor.santec.gecamed.esante.ejb.entity.beans.ESanteProperty;
import lu.tudor.santec.gecamed.esante.ejb.session.beans.ESanteConfigManagerBean;
import lu.tudor.santec.gecamed.esante.gui.tab.ESanteTab;
import lu.tudor.santec.gecamed.esante.gui.utils.ESanteGuiUtils;
import lu.tudor.santec.gecamed.formeditor.gui.view.FormTab;
import lu.tudor.santec.gecamed.labo.gui.patientview.LaboPanel;
import lu.tudor.santec.gecamed.letter.gui.LetterTemplateModule;
import lu.tudor.santec.gecamed.letter.gui.dialogs.NewLetterDialog;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Incident;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntry;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.IncidentEntryType;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient;
import lu.tudor.santec.gecamed.patient.ejb.session.beans.IncidentManagerBean;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IPatientPermissions;
import lu.tudor.santec.gecamed.patient.ejb.session.interfaces.IncidentManager;
import lu.tudor.santec.gecamed.patient.gui.administrative.PatientAdminPanel;
import lu.tudor.santec.gecamed.patient.gui.certificate.CertificatePrinter;
import lu.tudor.santec.gecamed.patient.gui.cyberlabKetterthill.CyberlabInitDialog;
import lu.tudor.santec.gecamed.patient.gui.erisk.EriskStarter;
import lu.tudor.santec.gecamed.patient.gui.fileimport.FileImportDialog;
import lu.tudor.santec.gecamed.patient.gui.history.HistoryDataAgent;
import lu.tudor.santec.gecamed.patient.gui.history.ImportantDataModel;
import lu.tudor.santec.gecamed.patient.gui.history.antecedents.AntecedentsListModel;
import lu.tudor.santec.gecamed.patient.gui.history.viewtab.HistoryViewTab;
import lu.tudor.santec.gecamed.patient.gui.hospitalisation.PatientHospitalisationPanel;
import lu.tudor.santec.gecamed.patient.gui.incident.IncidentTab;
import lu.tudor.santec.gecamed.patient.gui.medLogin.MedLoginInitDialog;
import lu.tudor.santec.gecamed.patient.gui.memo.MemoControler;
import lu.tudor.santec.gecamed.patient.gui.simpleview.OverviewPanel;
import lu.tudor.santec.gecamed.patient.utils.SettingConstants;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.Prescription;
import lu.tudor.santec.gecamed.prescription.ejb.session.beans.PrescriptionManagerBean;
import lu.tudor.santec.gecamed.prescription.ejb.session.interfaces.PrescriptionManager;
import lu.tudor.santec.gecamed.prescription.gui.PrescriptionIcons;
import lu.tudor.santec.gecamed.prescription.gui.editor.PrescriptionDataDialog;
import lu.tudor.santec.gecamed.prescription.gui.editor.PrescriptionDataModel;
import lu.tudor.santec.gecamed.prescription.gui.util.PrescriptionPrinter;
import lu.tudor.santec.gecamed.usermanagement.gui.settings.UserSettingsPlugin;
import lu.tudor.santec.i18n.Translatrix;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;


/**
 * Component that contains all other panels and components for a patient file.
 * Submodules are loaded and registered with their tooglebuttons. Each of them
 * is created in this class. To open multiple patient files in parallel, a PatientPanel
 * instance is created for each patient file and put into an open slot. These slots are listed
 * in a list of togglebuttons in the bottom of the navigation bar on the right.
 * If another view is selected, the appropriate PatientPanel instance is set to visible and
 * the view switch toogle buttons of the submodules are exchanged in the navigation bar.
 * 
 * 
 * Each submodule can be activated or deactivated in the patient admin settings.
 * The saveAction, coming from the action defined in the PatientManagerModule is piped to all
 * loaded submodules.
 * 
 * @author Johannes Hermen johannes.hermen@tudor.lu Tudor/Santec
 * @author martin.heinemann@tudor.lu Tudor/Santec
 * @author Thorsten Roth thorsten.roth(at)tudor.lu
 *
 * @version
 * <br>$Log: PatientPanel.java,v $
 * <br>Revision 1.166  2014-02-04 10:08:37  ferring
 * <br>eSante ID management completed
 * <br>Only those documents will be shown, that are retrieved by the RSQ
 * <br>
 * <br>Revision 1.165  2013-12-27 18:09:15  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.164  2013-12-06 13:48:56  troth
 * <br>Add EPSOS button to patient view to open the epsos website.
 * <br>
 * <br>Revision 1.163  2013-12-04 16:01:14  troth
 * <br>Add EPSOS button to patient view to open the epsos website.
 * <br>
 * <br>Revision 1.162  2013-11-22 13:51:04  troth
 * <br>Fix some small bugs in the consultation view.
 * <br>Add new gui function the patient setting to config the consultation view.
 * <br>
 * <br>Revision 1.161  2013-11-19 17:08:31  troth
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.160  2013-11-19 13:06:55  troth
 * <br>Set the important data panels in real time in the history view.
 * <br>
 * <br>Revision 1.159  2013-11-08 08:42:00  ferring
 * <br>exception logged instead of printStackTrace
 * <br>
 * <br>Revision 1.158  2013-07-15 06:18:35  ferring
 * <br>logging changed
 * <br>
 * <br>Revision 1.157  2013-07-10 16:28:43  troth
 * <br>Add lab talon button in patient view.
 * <br>
 * <br>Revision 1.156  2013-06-26 11:19:37  ferring
 * <br>migrating eSante view from dialogs to eSante patient tab
 * <br>
 * <br>Revision 1.155  2013-06-21 07:12:37  ferring
 * <br>form tab visible in options, but only shown, if module is loaded
 * <br>
 * <br>Revision 1.154  2012-11-16 10:34:55  ferring
 * <br>Drag and Drop of files into the patient module will call the FileImportDialog with this files included
 * <br>
 * <br>Revision 1.153  2012-08-06 14:04:04  troth
 * <br>Now the MedLogin service stores the tokens of the users in the new table external password store.
 * <br>
 * <br>Revision 1.152  2012-08-01 15:38:02  troth
 * <br>Remove token and password saving in the database for MedLogin and CyberLab. Now the token and password is only save for one GECAMed session.
 * <br>
 * <br>Revision 1.151  2012-07-12 15:50:32  troth
 * <br>Implementation of Ticket #1003.
 * <br>
 * <br>Revision 1.150  2012-07-09 13:41:13  troth
 * <br>DR.G
 * <br>
 * <br>Revision 1.149  2012-06-07 12:37:04  ferring
 * <br>setting the created date and created by will be done on the server before saving
 * <br>
 * <br>Revision 1.148  2012-06-07 11:59:12  ferring
 * <br>Store the user, that created an empty incident
 * <br>
 * <br>Revision 1.147  2012-03-08 13:49:41  troth
 * <br>Commented out the shortcut and hotkey in patient view for switch from admindataview to history
 * <br>
 * <br>Revision 1.146  2012-03-08 10:53:00  troth
 * <br>Add some Translatrix-Tags.
 * <br>
 * <br>Revision 1.145  2012-03-07 12:21:02  troth
 * <br>Finish the new function of the MedLogin Button.
 * <br>
 * <br>Revision 1.144  2012-03-05 10:09:14  troth
 * <br>Add new MedLogin Button in patient panel on the functionbar.
 * <br>
 * <br>Revision 1.143  2012-02-23 12:55:29  troth
 * <br>Fix tooltip on ERisk Button.
 * <br>
 * <br>Revision 1.142  2012-02-07 13:54:59  ferring
 * <br>warnings removed
 * <br>
 * <br>Revision 1.141  2012-01-26 13:42:43  troth
 * <br>Add tooltips to the buttons.
 * <br>
 * <br>Revision 1.140  2012-01-25 14:21:41  troth
 * <br>1. Add scrollbar to the PatientNaviBar.
 * <br>2. Add tooltips to the buttons.
 * <br>
 */
public class PatientPanel extends PatientViewTab implements PropertyChangeListener, ActionListener {
    //~ Static fields/initializers =============================================

	/** the logger Object for this class */
	private static Logger logger = Logger.getLogger(PatientPanel.class.getName());
	
    private static final long serialVersionUID = 1L;
    
    
    /* ------------------------------------------------------ */
    
	public static final String VIEW_CHANGED 	 = "view_changed";
    
    /* ------------------------------------------------------ */
    
    private static int  static_identifier = 1;
	
    private int  identifier ;
    
    private Collection<PatientViewTab> disabledTabs = new LinkedList<PatientViewTab>();
    
    
    
    //~ Instance fields ================================================== ======

    private LinkedHashMap<String, PatientViewTab> tabs = new LinkedHashMap<String, PatientViewTab>();

    private Patient patient;

	private CardLayout panelCardLayout;

	private JToggleButton patientButton;

	private PatientButtonPanel patientButtonPanel;

	private PatientViewTab currentPanel;

	private PatientAdminPanel patientAdminPanel; 

	private PatientButtonPanel functionButtonPanel;

	private IncidentTab incidentTab;

	private PatientManagerModule patientManagerModule;
	
	private CertificatePrinter certPrinter = new CertificatePrinter();

	private ImportantDataModel importantDataModel;

	private AntecedentsListModel antecedentModel;

	private MemoControler memoControler;

	private PatientViewTab firstViewTab;

	private JButton fileImportButton;

	private OverviewPanel overviewViewPanel;

	private AbstractButton letterButton;

	private HistoryDataAgent historyDataAgent;

	private IncidentManager incidentManager;
	
	private EmptyIncidentDialog emptyIncidentDialog = new EmptyIncidentDialog();

	private PrescriptionDataModel prescriptionDataModel;
	
	private PrescriptionDataDialog prescriptionDataDialog;

	private Incident incident;
	
	private long start;
	
	private boolean useMnemonics = false;
	
	private JPopupMenu LabButtonsPopup; // The popup contains all Lob buttons like Cyberlab, MedLogin and LabTalon
	
//	private static HashMap<Integer, String> medLoginTokenStore = new HashMap<Integer, String>();
	
	// Store for cyberlab password
//	private static HashMap<Integer, String> cyberlabPasswordStore = new HashMap<Integer, String>();

    //~ Constructors ===========================================================
    /**
     * creates a new PatientPanel
     *
     * @param patientManagerModule the parent of this panel.
     */
    public PatientPanel(PatientManagerModule patientManagerModule) { 
    	/* ================================================== */
    	this.patientManagerModule = patientManagerModule;
    	this.setOpaque(false);
    	/* ------------------------------------------------------ */
    	// create a new card layout for the submodules
    	/* ------------------------------------------------------- */
    	this.panelCardLayout = new CardLayout();
        this.setLayout(panelCardLayout);
        /* ------------------------------------------------------ */
        // save the patient and set its information to the
        // header
        /* ------------------------------------------------------- */
        this.patient = new Patient();
        this.setTitle(this.patient.toShortString());
        this.setName(this.patient.toShortString());
        this.setIcon(PatientManagerModule.getIcon(PatientManagerModule.PATIENT));
        /* ------------------------------------------------------ */
        // init the panels
        /* ------------------------------------------------------- */
        initPanels();
        /* ------------------------------------------------------- */
        // create the toogle buttons
        /* ------------------------------------------------------- */
        createPatientButton();
        /* ------------------------------------------------------- */
		/* ============================================= */
		
		incidentManager = (IncidentManager) ManagerFactory.getRemote(IncidentManagerBean.class);
		
		prescriptionDataDialog = this.prescriptionDataModel.getPrescriptionDialog();
		//this.prescriptionEditor = new PrescriptionEditor(this); 
    }
    

    /**
     * Init the patient panel like
     * consultation
     * historique
     * adminstrative
     * etc
     */
    private void initPanels() {
		/* ============================================= */
    	// wer hat denn das hier verbrochen??
    	String enabledModules = patientManagerModule.subModulesPlugin.getEnabledElements();
    	/* ------------------------------------------------------- */
    	// create the important data panel
    	/* ------------------------------------------------------- */
    	this.antecedentModel 	= new AntecedentsListModel();
    	//this.antecedentPanel = new AntecedentsPanel(antecedentModel); 
    	this.importantDataModel = new ImportantDataModel(antecedentModel, this);
    	
    	this.prescriptionDataModel = new PrescriptionDataModel(this);
    	//this.prescriptionDataModel = new PrescriptionDataModel(antecedentModel, this);
//    	this.historyTableModel 	= new HistoryTableModel();
    	/* ------------------------------------------------------- */
    	this.historyDataAgent = new HistoryDataAgent();
    	
//    	this.historyDataAgent.enableDebug();
    	
    	this.memoControler = new MemoControler();
    	
    		/* ------------------------------------------------------- */
    		// new cool layout =)
    		/* ------------------------------------------------------- */
    		// simple view
    		/* ------------------------------------------------------- */
    		if (GECAMedModule.userHasPermission(IPatientPermissions.VIEW_HISTORY))
    		{
    			this.overviewViewPanel = new OverviewPanel(this);
    			
    	    	if (PatientManagerModule.getUseMnemonics()) {
    	    		overviewViewPanel.getButton().setMnemonic(KeyEvent.VK_H);
    	    		overviewViewPanel.getButton().setToolTipText(overviewViewPanel.getButton().getToolTipText()+" [ALT+H]");
    	    	}
    			
    			this.tabs.put(this.overviewViewPanel.getName(), this.overviewViewPanel);
    		}
        	
        	/* ------------------------------------------------------- */
        	//  create the incident panel for the consultation screen
        	/* ------------------------------------------------------- */
        	if (enabledModules.contains("IncidentTab") && (GECAMedModule.userHasPermission(IPatientPermissions.CREATE_CONSULTATION))) {
        	    incidentTab = new IncidentTab(this);
        	    
    	    	if (PatientManagerModule.getUseMnemonics()) {
    	    		incidentTab.getButton().setMnemonic(KeyEvent.VK_C);
    	    		incidentTab.getButton().setToolTipText(incidentTab.getButton().getToolTipText()+" [ALT+C]");
    	    	}
    			this.tabs.put(incidentTab.getName(), incidentTab);
    		}
        	/* ------------------------------------------------------- */
        	// add Admin Panel
    		/* ------------------------------------------------------- */
    		if (GECAMedModule.userHasPermission(IPatientPermissions.VIEW_ADMINISTRATIVE)) {
        		patientAdminPanel = new PatientAdminPanel(null);
        		
        		if (PatientManagerModule.getUseMnemonics()) {
        			patientAdminPanel.getButton().setMnemonic(KeyEvent.VK_A);
        			patientAdminPanel.getButton().setToolTipText(patientAdminPanel.getButton().getToolTipText()+" [ALT+A]");
    	    	}
        		tabs.put(patientAdminPanel.getName(), patientAdminPanel);
    		}
    		/* ------------------------------------------------------- */
    		this.firstViewTab = overviewViewPanel;
//    	}
		
    	/* ------------------------------------------------------- */
	    //	  add Hospitalisation Panel        
    	/* ------------------------------------------------------- */
    	if (enabledModules.contains("PatientHospitalisationPanel")) {
	    	PatientViewTab hospPanel = new PatientHospitalisationPanel ();
		    this.tabs.put(hospPanel.getName(), hospPanel);
    	}
    	/* ------------------------------------------------------- */
	    //	  add Cara Panel        
    	/* ------------------------------------------------------- */
    	if (enabledModules.contains("PatientCaraPanel")  && (GECAMedModule.userHasPermission(IPatientPermissions.VIEW_HISTORY))) {
	    	PatientViewTab caraPanel = new PatientCaraPanel ();
	    	if (PatientManagerModule.getUseMnemonics()) {
	    		caraPanel.getButton().setMnemonic(KeyEvent.VK_R);
	    		caraPanel.getButton().setToolTipText(caraPanel.getButton().getToolTipText()+" [ALT+R]");
	    	}
		    this.tabs.put(caraPanel.getName(), caraPanel);
    	}
    	/* ------------------------------------------------------- */
	    //	  add DICOM Panel        
    	/* ------------------------------------------------------- */
    	if (enabledModules.contains("PatientDicomPanel") && (GECAMedModule.userHasPermission(IPatientPermissions.VIEW_HISTORY))) {
	    	PatientViewTab dicomPanel = new PatientDicomPanel ();
	    	if (PatientManagerModule.getUseMnemonics()) {
	    		dicomPanel.getButton().setMnemonic(KeyEvent.VK_R);
	    		dicomPanel.getButton().setToolTipText(dicomPanel.getButton().getToolTipText()+" [ALT+R]");
	    	}
		    this.tabs.put(dicomPanel.getName(), dicomPanel);
    	}
    	
    	/* ------------------------------------------------------- */
	    //	  add LABO Panel        
    	/* ------------------------------------------------------- */
    	if (enabledModules.contains("LaboPanel")  && (GECAMedModule.userHasPermission(IPatientPermissions.VIEW_HISTORY))) {
	    	PatientViewTab laboPanel = new LaboPanel ();
	    	
	    	if (PatientManagerModule.getUseMnemonics()) {
	    		laboPanel.getButton().setMnemonic(KeyEvent.VK_L);
	    		laboPanel.getButton().setToolTipText(laboPanel.getButton().getToolTipText()+" [ALT+L]");
	    	}
	    	
		    this.tabs.put(laboPanel.getName(), laboPanel);
    	}
    	
    	/* ------------------------------------------------------- */
	    //	  add History list panel      
    	/* ------------------------------------------------------- */
    	if (enabledModules.contains("HistoryViewTab")  && (GECAMedModule.userHasPermission(IPatientPermissions.VIEW_HISTORY))) {
	    	PatientViewTab historyView = new HistoryViewTab(this);

	    	if (PatientManagerModule.getUseMnemonics()) {
	    		historyView.getButton().setMnemonic(KeyEvent.VK_H);
	    		historyView.getButton().setToolTipText(historyView.getButton().getToolTipText()+" [ALT+H]");
	    	}
	    	
		    this.tabs.put(historyView.getName(), historyView);
    	}
    	
    	if (ESanteGuiUtils.isESanteModuleActivated())
    	{
    		ESanteTab eSanteView = new ESanteTab();
    		
	    	if (PatientManagerModule.getUseMnemonics()) {
	    		eSanteView.getButton().setMnemonic(KeyEvent.VK_S);
	    		eSanteView.getButton().setToolTipText(eSanteView.getButton().getToolTipText()+" [ALT+S]");
	    	}
	    	
    		this.tabs.put(eSanteView.getName(), eSanteView);
    	}
    	
    	/* ------------------------------------------------------- */
	    //	  add Form panel      
    	/* ------------------------------------------------------- */
    	if (//ModuleManager.getModule(FormEditorModule.MODULE_NAME) != null &&
    			enabledModules.contains(FormTab.TAB_NAME) &&
    			GECAMedModule.userHasPermission(IPatientPermissions.EDIT_CONSULTATION)) 
    	{    		
	    	PatientViewTab formEditorView = new FormTab(this);

	    	if (PatientManagerModule.getUseMnemonics()) {
	    		formEditorView.getButton().setMnemonic(KeyEvent.VK_F);
	    		formEditorView.getButton().setToolTipText(formEditorView.getButton().getToolTipText()+" [ALT+F]");
	    	}
	    	
		    this.tabs.put(formEditorView.getName(), formEditorView);
    	}
		/* ============================================= */
	}
    
	//~ Methods ================================================================
    /**
     * returns the shown Patient
     *
     * @return the shown Patient
     */
    public Patient getPatient()
    {
        return this.patient;
    }
    
    
    
    /**
     * Shows a panel<br/>
     * Use constants: <ul>
     * <li>ADMIN_PANEL</li>
     * <li>HISTORY_PANEL</li>
     * <li>INCIDENT_PANEL</li>
     * <li>MEMO_PANEL</li>
     * <li>VACCINATION_PANEL</li>
     * </ul>
     * 
     * @param panel
     */
    public void showPanel(String panel) {
    	/* ====================================================== */
    	if (panel != null) {
    		if (this.currentPanel != null && panel.equals(this.currentPanel.getName()))
    			return;
    		
    		/* ------------------------------------------------------ */
    		if (this.currentPanel != null) 
    			this.currentPanel.preparetoHide();
    		currentPanel = tabs.get(panel);
    		// if tab not exists
    		if (currentPanel == null )
    			return;
    		currentPanel.preparetoShowup();
    		this.panelCardLayout.show(this, panel);
    		currentPanel.getButton().setSelected(true);
    		currentPanel.afterShowup();
    		firePropertyChange(VIEW_CHANGED, null, panel);
    		/* ------------------------------------------------------ */
    	}
		/* ====================================================== */
    }
    
    
    /**
     * check if panel is the active panel
     * @param panel name of the panel
     * Use constants: <ul>
     * <li>ADMIN_PANEL</li>
     * <li>HISTORY_PANEL</li>
     * <li>INCIDENT_PANEL</li>
     * <li>MEMO_PANEL</li>
     * <li>VACCINATION_PANEL</li>
     * </ul>
     * @return true if panel ist active panel else false
     */
    public boolean isPanelSet(String panel)
    {
    	if (this.currentPanel != null && panel.equals(this.currentPanel.getName()))
			return true;
    	else return false;
    }

    /**
     * saves the PatientData.
     * Delegates the call to all submodules.
     */
	public void savePatient() {
    	/* ================================================== */

    	for (Iterator<PatientViewTab> iter = tabs.values().iterator(); iter.hasNext();) {
			GECAMedTab tab = (GECAMedTab) iter.next();
			if (tab.isTabEnabled()) {
				tab.saveData();
				tab.setModified(false);
			}
		}

    	
    	// save prescription
    	if (this.prescriptionDataModel.isPrescriptionModified()) {
    		this.prescriptionDataModel.saveData();    		
    	}

    	
    	
        // --------------------------------------------------------------------------
    	setPatient(this.patientAdminPanel.getPatient(), true);
		logger.info(Translatrix
				.getTranslationString("pm.newValuesForPatient:")
				+ " "
				+ this.patientAdminPanel.getPatient().toShortString()
				+ " "
				+ Translatrix.getTranslationString("pm.saved"));
		StatusBar.getInstance().setProgress(
				Translatrix.getTranslationString("pm.patientSaved"), 100);
		/* ================================================== */
    }
	
    public boolean isFilledOK() {
	return patientAdminPanel.isFilledOK();
    }
    
    
	/* (non-Javadoc)
	 * @see lu.tudor.santec.gecamed.patient.gui.PatientViewTab#setPatient(lu.tudor.santec.gecamed.patient.ejb.entity.beans.Patient)
	 */
	public void setPatient(Patient patient) {
		/* ================================================== */
		for (PatientViewTab tab : disabledTabs)
			tab.setPermanentlyDisabled(false);
		disabledTabs.clear();
		setPatient(patient, false);
		/* ================================================== */
	}	
		
	/**
	 * @param newPatient
	 * @param force
	 */
	protected void setPatient(Patient newPatient, boolean force) {
	    start = System.currentTimeMillis();
	    /* ================================================== */
		if (!force && this.patient != null && this.patient.equals(newPatient)) {
			logger.info("old Patient == new Patient: doing nothing");
			return;
		}

		// TODO try init the overviewPanel new
//		if (GECAMedModule.userHasPermission(IPatientPermissions.VIEW_HISTORY))
//		{
//        	this.tabs.remove(overviewViewPanel);
//			this.overviewViewPanel = new OverviewPanel(this);
//        	this.tabs.put(overviewViewPanel.getName() , overviewViewPanel);
//        	this.firstViewTab = overviewViewPanel;
//        	createPatientButton();
//		}
		
		boolean isModified = false;
		/* ------------------------------------------------------- */
		if (this.isModified())
			isModified = true;
		else {
			/* ------------------------------------------------------- */
			for (Iterator<PatientViewTab> iter = tabs.values().iterator(); iter.hasNext();) {
				GECAMedTab tab = (GECAMedTab) iter.next();
				if (tab.isModified())
					isModified = true;
			}
		}
		if (prescriptionDataModel.isPrescriptionModified())
			isModified = true;
		
		
		
		/* ------------------------------------------------------- */
		// if force, do not ask for save modifications
		/* ------------------------------------------------------- */
		if (!force) {
			/* ------------------------------------------------------- */
			if (isModified && ( getPatient() != null ) && isFilledOK() ) {
//				! ( ( patient.getSurName() == null || "".equals(getPatient().getSurName().trim()) ) && 
//					( patient.getFirstName() == null || "".equals(getPatient().getFirstName().trim()) ) ) ) {
				/* ------------------------------------------------------- */
				logger.info("old Patient was modified: save before");
				int n = JOptionPane.showConfirmDialog(
				    MainFrame.getInstance(),
				    "Patient " + this.getPatient().toString() + " \n" + Translatrix.getTranslationString("pm.savequestion"),
				    Translatrix.getTranslationString("pm.savePatient"),
				    JOptionPane.YES_NO_CANCEL_OPTION);
				/* ------------------------------------------------------- */
				if (n == JOptionPane.YES_OPTION) {
					/* ------------------------------------------------------- */
					// if yes we save the Patient
					savePatient();
					// log
					long took = (System.currentTimeMillis()-start);
					GECAMedLog.user(PatientManagerModule.MODULE_NAME,
	        				PatientManagerModule.UPDATE_PATIENT, "Patient: ID " + this.patient.toLogString(), 
	        				took);
	        		/* ------------------------------------------------------- */
				} else if (n == JOptionPane.CANCEL_OPTION || n == JOptionPane.CLOSED_OPTION) {
					// for cancel we do not set the new Patient
					return;
				}
				/* ------------------------------------------------------- */
			} else {
				logger.info("old Patient was not modified: ok");
			}
		} else {
			logger.info("forcing closing of patient");
		}
		/* ------------------------------------------------------- */
		// log closing of old patient
		/* ------------------------------------------------------- */
		if (this.patient != null && this.patient.isPersistent()) {
			GECAMedLog.user(PatientManagerModule.MODULE_NAME,
					PatientManagerModule.CLOSE_PATIENT, "Patient: ID " + this.patient.getId() 
    					+ "; " + this.patient.getSurName()+", "
    					+this.patient.getFirstName()+"; " 
    					+ this.patient.getSocialSecurityNumber(), 
    					null);
		}
		
		if (currentPanel != null && currentPanel instanceof ESanteTab)
		{
			// do not show the eSante tab when loading a new patient (
			showPanel(PatientAdminPanel.NAME);
		}
		
		logger.info("set new patient to Tab");
		this.patient = newPatient;
		this.incident = null;
		this.setTitle(this.patient.toShortString());
		this.patientButton.setText(this.patient.toShortString());
		this.setName(this.patient.toShortString());
        /* ------------------------------------------------------- */
        // set the patient to the models of the views
        /* ------------------------------------------------------- */
        this.prescriptionDataModel.setPatient(newPatient);
		this.antecedentModel.setPatient(	newPatient);
		this.importantDataModel.setPatient(	newPatient);
//		this.historyTableModel.setPatient(	newPatient);
		this.historyDataAgent.setPatient(	newPatient);
		this.memoControler.setPatient(		newPatient);
		/* ------------------------------------------------------- */
		
		// set new Patient to all tabs
		for (Iterator<PatientViewTab> iter = tabs.values().iterator(); iter.hasNext();) {
			PatientViewTab tab = (PatientViewTab) iter.next();
			tab.setPatient(newPatient);
			tab.enableTab();
		}
                
		logger.info("enable all tabs");
		setTabsEnabled();
    	// log opening of new patient
		if (this.patient != null && this.patient.isPersistent()) {
		    long took = (System.currentTimeMillis()-start);
			GECAMedLog.user(PatientManagerModule.MODULE_NAME,PatientManagerModule.OPEN_PATIENT,"Patient: ID " + this.patient.getId() 
					+ "; " + this.patient.getSurName()+", "
					+ this.patient.getFirstName()+"; " 
					+ this.patient.getSocialSecurityNumber(),
					took
					);
		}
		/* ================================================== */
	}
	
	/**
	 * 
	 */
	protected void setTabsEnabled() {
		/* ================================================== */
		// Select the administrative tab for new patients
        if (! patient.isPersistent()) {
        	try {
        		/* ------------------------------------------------------- */
        		// select Admin Tab as Default for new Patient.
        		// patientTabs.setSelectedIndex(1);
        		// enable admin panel at first
        		/* ------------------------------------------------------- */
        		patientAdminPanel.getButton().doClick();
        		// Disable function buttons of the modules
        		
        		PatientManagerModule.getInstance().getNaviBar().enablePanels(false);
        		
        		for (PatientViewTab tab : tabs.values()) {
        			/* ------------------------------------------------------- */
					if (tab instanceof PatientAdminPanel) {
						tab.showTab();
						tab.enableTab();						
					} else {
						tab.disableTab();
						if (tab.getActionComponents() != null)
							for (JComponent c : tab.getActionComponents())
								c.setEnabled(false);
					}
					/* ------------------------------------------------------- */
				}
        		
        		Component[] c = functionButtonPanel.getComponents();
        		for (int i = 0; i < c.length; i++) {
        			c[i].setEnabled(false);
    			}
        		// enabled MedLogin Button because this function can always be used
        		c[c.length-1].setEnabled(true);
        		// c[c.length-2].setEnabled(true); //TODO Dr. G
        		/* ------------------------------------------------------- */
			} catch (Exception e) {
			}
			/* ------------------------------------------------------- */
        } else {
        	/* ------------------------------------------------------- */
        	for (PatientViewTab tab : tabs.values()) {
        		/* ------------------------------------------------------- */
        		tab.enableTab();
        		
    			if (tab.getActionComponents() != null)
					for (JComponent c : tab.getActionComponents())
						c.setEnabled(true);
    			/* ------------------------------------------------------- */
        	}
        	PatientManagerModule.getInstance().getNaviBar().enablePanels(true);
        	Component[] c = functionButtonPanel.getComponents();
    		for (int i = 0; i < c.length; i++) {
    			c[i].setEnabled(true);
			}
    		// enabled MedLogin Button because this function can always be used
    		c[c.length-1].setEnabled(true);
    		// c[c.length-2].setEnabled(true); //TODO Dr. G
    		/* ------------------------------------------------------- */
        }
        /* ================================================== */
	}
	
	/**
	 * Returns the identifier for the current PatientPanel instance.
	 * Used to distinguish differen PatientPanel instances
	 * 
	 * @return
	 */
	public String getIdentifier() {
		return identifier+"";
	}
	
	/**
	 * Create the buttons that are placed on top of the navigation bar to the right
	 * 
	 */
	private void createPatientButton() {
		
		boolean smallIcons = false;
		try {
			smallIcons = (Boolean) MainFrame.getInstance().userSettings.getValue(UserSettingsPlugin.SMALL_ICONS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		/* ================================================== */
		this.identifier = static_identifier;
		static_identifier++;
		this.patientButton = new JToggleButton(patient.toShortString());
		this.patientButton.setActionCommand(identifier+"");
		
		
//		this.patientButtonPanel = new PatientButtonPanel(Translatrix.getTranslationString("patient.navigation"), Color.CYAN, 3,  new Vector<AbstractButton>());
		this.patientButtonPanel = new PatientButtonPanel(Translatrix.getTranslationString("patient.navigation"), new Color(153,204,255), 3,  new Vector<AbstractButton>());
		ActionListener tabListener = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/* ============================================= */
				showPanel(e.getActionCommand());
				/* ============================================= */
			}
		};
		
		
		this.functionButtonPanel = new PatientButtonPanel(Translatrix.getTranslationString("patient.functions"), new Color(153,204,255), 1, new Vector<AbstractButton>());

		
		for (Iterator<String> iter = tabs.keySet().iterator(); iter.hasNext();) {
			String tabName = (String) iter.next();
			/* ------------------------------------------------------- */
			PatientViewTab tab = tabs.get(tabName);
			tab.addPropertyChangeListener(this);
			tab.getButton().setActionCommand(tabName);
			tab.getButton().addActionListener(tabListener);
			patientButtonPanel.addToggleButton(tab.getButton());
			/* ------------------------------------------------------ */
			if (tab.getActionComponents() != null)
				for (JComponent c : tab.getActionComponents())  {
					functionButtonPanel.addComponent(c);
				}
			this.add(tab,tabName);
		}

		
		for (Iterator<?> iterator = certPrinter.getButtons().iterator(); iterator.hasNext();) {
			JButton a = (JButton) iterator.next();
			a.setEnabled(false);
			functionButtonPanel.addButton(a);
		}
		
		if (EriskStarter.checkErisk() && GECAMedModule.userHasPermission(IPatientPermissions.VIEW_HISTORY))
		{
			JButton eCompassButton = null;
			if (smallIcons) {
				eCompassButton = new JButton(Translatrix.getTranslationString("ECompass.button"), PatientManagerModule.getMiniIcon(PatientManagerModule.E_KOMPASS));
			} else {
				eCompassButton = new JButton(Translatrix.getTranslationString("ECompass.button"), PatientManagerModule.getMediumIcon(PatientManagerModule.E_KOMPASS));
			}
			eCompassButton.setHorizontalAlignment(SwingConstants.LEFT);
			eCompassButton.setEnabled(true);
			eCompassButton.setToolTipText(Translatrix.getTranslationString("ECompass.buttonTip"));
			eCompassButton.setIconTextGap(1);
			eCompassButton.setFont(GECAMedFonts.BUTTON_FONT);
			eCompassButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
			eCompassButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {
						new EriskStarter().startEKompass();
					} catch (Exception ee) {
						logger.log(Level.WARN, "EriskStarter().startEKompass();", ee);
					}
				}
			});
			functionButtonPanel.addButton(eCompassButton);
			// --------------------------------------------------------------------------------------
			JButton eRiskButton = null;
			if (smallIcons) {
				eRiskButton = new JButton(Translatrix.getTranslationString("ERisk.button"), PatientManagerModule.getMiniIcon(PatientManagerModule.E_RISK));
			} else {
				eRiskButton = new JButton(Translatrix.getTranslationString("ERisk.button"), PatientManagerModule.getMediumIcon(PatientManagerModule.E_RISK));
			}
			eRiskButton.setHorizontalAlignment(SwingConstants.LEFT);
			eRiskButton.setEnabled(true);
			eRiskButton.setToolTipText(Translatrix.getTranslationString("ERisk.buttonTip"));
			eRiskButton.setIconTextGap(1);
			eRiskButton.setFont(GECAMedFonts.BUTTON_FONT);
			eRiskButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
			eRiskButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {
						new EriskStarter().startERisk();
					} catch (Exception ee) {
						logger.log(Level.WARN, "EriskStarter().startERisk();", ee);
					}
				}
			});
			functionButtonPanel.addButton(eRiskButton);
		}
		/* ------------------------------------------------------- */
		// Button for file import
		/* ------------------------------------------------------- */
		if (GECAMedModule.userHasPermission(IPatientPermissions.EDIT_HISTORY)) {
        		this.fileImportButton = new JButton(
        			Translatrix.getTranslationString("fileimport.button"),
        			(smallIcons?IconFetcher.getMiniIcon(PatientManagerModule.class, PatientManagerModule.ADD_FILE): IconFetcher.getMediumIcon(PatientManagerModule.class, PatientManagerModule.ADD_FILE)));
        		fileImportButton.setHorizontalAlignment(SwingConstants.LEFT);
        		fileImportButton.setEnabled(true);
        		fileImportButton.setToolTipText(Translatrix.getTranslationString("fileimport.buttonTip"));
        		fileImportButton.setIconTextGap(1);
        		fileImportButton.setFont(GECAMedFonts.BUTTON_FONT);
        		fileImportButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
        		fileImportButton.addActionListener(this);
        		functionButtonPanel.addButton(this.fileImportButton);
		}
		
		/* ------------------------------------------------------- */
		// Button for creating a new letter, shown when
		//	LetterTemplate Module is active
		/* ------------------------------------------------------- */
		
		letterButton = new JButton(Translatrix.getTranslationString("letter.button"),
				(smallIcons?IconFetcher.getMiniIcon(LetterTemplateModule.class, LetterTemplateModule.ICON_LETTER):IconFetcher.getMediumIcon(LetterTemplateModule.class, LetterTemplateModule.ICON_LETTER)));
			letterButton.setHorizontalAlignment(SwingConstants.LEFT);
			letterButton.setEnabled(true);
			letterButton.setToolTipText(Translatrix.getTranslationString("letter.buttonTip"));
			letterButton.setIconTextGap(1);
			letterButton.setFont(GECAMedFonts.BUTTON_FONT);
			letterButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
			letterButton.addActionListener(new ActionListener(){

				public void actionPerformed(ActionEvent e) {
//					new CreateLetterDialog();
					NewLetterDialog nd = new NewLetterDialog();
					MainFrame.showDialogCentered(nd);
				}
				
			});
			GECAMedModule module = ModuleManager.getModule("LetterTemplateModule");
			if(module !=null)
				functionButtonPanel.addButton(this.letterButton);
		
		try {
		    this.firstViewTab.getButton().doClick();			    
		} catch (Exception ee) {
			try {
				patientAdminPanel.getButton().doClick();
			} catch (Exception eee) {
				logger.warn("No button to click");
				//eee.printStackTrace();
			}
		}
		/* ------------------------------------------------------- */
		// prescription button
		/* ------------------------------------------------------- */
		// if user has right createPrescription, we display a button
		/* ------------------------------------------------------- */
		if (GECAMedModule.userHasPermission(IPatientPermissions.CREATE_PRESCRIPTION)) {
			/* ------------------------------------------------------- */

			JButton prescriptionButton = new JButton(Translatrix.getTranslationString("prescription.buttons.new"));
			
			prescriptionButton.setHorizontalAlignment(SwingConstants.LEFT);
			prescriptionButton.setEnabled(true);
			prescriptionButton.setToolTipText(Translatrix.getTranslationString("prescription.buttons.newTip"));
			prescriptionButton.setIconTextGap(1);
			prescriptionButton.setFont(GECAMedFonts.BUTTON_FONT);
			prescriptionButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
			prescriptionButton.setIcon(
					(smallIcons?PrescriptionIcons.getMiniIcon(PrescriptionIcons.PRSC_DRUG):PrescriptionIcons.getMediumIcon(PrescriptionIcons.PRSC_DRUG)));
			
			prescriptionButton.addActionListener(new ActionListener() {
	
				public void actionPerformed(ActionEvent e) {
					//prescriptionDataDialog.prescriptionDataModel.setPrescription(prescriptionDataDialog.prescriptionDataModel.getPrescription());
					prescriptionDataDialog.showDialog();
				}
				
			});
			functionButtonPanel.addButton(prescriptionButton);

			
			/* ------------------------------------------------------- */
			GECAMedModule.addPatientListener(new PatientListener() {

				public void patientChanged(Patient patient) {
					/* ====================================================== */
					
//					if (patient != null)
//						prescriptionEditor.reloadHistory(patient.getId());
//					else
//						prescriptionEditor.reloadHistory(null);
					/* ====================================================== */
				}
			});
			
			
			/* ------------------------------------------------------- */
			
			GECAMedAction printEmptyAction = new GECAMedAction(
				null,
				"prescription.buttons.printEmpty",
				(smallIcons?PrescriptionIcons.getMiniIcon(PrescriptionIcons.PRINT_EMPTY):PrescriptionIcons.getSmallIcon(PrescriptionIcons.PRINT_EMPTY)),
				KeyEvent.VK_V,
				false, false, false) {

                			private static final long serialVersionUID = 1L;
                
                			public void actionPerformed(ActionEvent evt) {
                				/* ====================================================== */
                				PrescriptionPrinter.printEmpty(GECAMedModule.getCurrentPatient());
                				/* ====================================================== */
                			}
			
			/* ------------------------------------------------------- */
			
        		};
        		JButton printEmptyButton = new JButton(printEmptyAction);
        		printEmptyButton.setHorizontalAlignment(SwingConstants.LEFT);
        		printEmptyButton.setEnabled(true);
        		printEmptyButton.setIconTextGap(1);
        		printEmptyButton.setFont(GECAMedFonts.BUTTON_FONT);
        		printEmptyButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
        		printEmptyButton.setToolTipText(Translatrix.getTranslationString("prescription.tooltip.printemptyprescription"));
        
        		functionButtonPanel.addButton(printEmptyButton);
			
		}

		/* ------------------------------------------------------- */
		// just create an empty incident....
		/* ------------------------------------------------------- */
		if (	(Boolean.TRUE.equals(PatientManagerModule.getInstance().administrativeElementsPlugin.getValue(SettingConstants.SHOW_EMPTY_INCIDENT_BUTTON)))) {
		    JButton emptyIncidentButton = new JButton(Translatrix.getTranslationString("dossier.emptyincident"));
		    emptyIncidentButton.setHorizontalAlignment(SwingConstants.LEFT);
		    emptyIncidentButton.setEnabled(true);
		    emptyIncidentButton.setToolTipText(Translatrix.getTranslationString("dossier.emptyincidentTip"));
		    emptyIncidentButton.setIconTextGap(1);
		    emptyIncidentButton.setFont(GECAMedFonts.BUTTON_FONT);
		    emptyIncidentButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
		    emptyIncidentButton.setIcon(
		    		(smallIcons?IconFetcher.getMiniIcon(PatientManagerModule.class, PatientManagerModule.PATIENT_VISITED):IconFetcher.getMediumIcon(PatientManagerModule.class, PatientManagerModule.PATIENT_VISITED)));
			emptyIncidentButton.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					// check if there is an incident newer than 6h
					List<IncidentEntry>	entries;
					IncidentEntryType	ieType;
					IncidentEntry		ie;
					Incident			inc;
					Date				date;
					Calendar			c = new GregorianCalendar();
					
					
					c.add(Calendar.HOUR_OF_DAY, -6);
					inc = incidentManager.getIncidentNewerThan(
							GECAMedModule.getCurrentPatient().getId(), 
							GECAMedModule.getCurrentPhysician().getId(), 
							c.getTime());
					
					// if not, create one...
					if (inc == null)
					{
						emptyIncidentDialog.showDialog();
						if (emptyIncidentDialog.retVal == true 
								&& emptyIncidentDialog.getPhysician() != null)
						{
							// create the incident entry
							ie		= new IncidentEntry();
							date	= new Date();
							ie.setTextContent(emptyIncidentDialog.getText());
//							ie.setCreated(date);
//							ie.setCreatedBy(GECAMedModule.getCurrentUser().getId());
							ie.setEntryDate(date);
							
							// set the incident entry type
							ieType	= incidentManager.getTypeByName(IncidentManager.SOAP_S, null);
							if (ieType != null)
							{
								ie.setEntryType(ieType);
								ie.setEntryTypeId(ieType.getId());
							}
							
							// create the incident
							inc 	= new Incident(GECAMedModule.getCurrentPatient().getId(), 
									emptyIncidentDialog.getPhysician().getId());
							inc.setIncidentDate(date);
							inc.setSiteId(MainFrame.getCurrentSiteId());
							
							// bind the entry to its incident
							entries	= new LinkedList<IncidentEntry>();
							entries.add(ie);
							inc.setIncidentEntries(entries);
							ie.setIncident(inc);
							// save the incident and with it the incident entry
							inc 	= incidentManager.saveIncident(inc);
//						    incidentManager.saveEntry(ie, IncidentManager.SOAP_S);
							
							reloadHistory();
						}
					}
				}
			});
			functionButtonPanel.addButton(emptyIncidentButton);
		}
		
		// -------------------------------------------------------
		// Lab Button show the popup with all lab buttons
		// -------------------------------------------------------
		JButton labButton = null;
		if (smallIcons) {
			labButton = new JButton(Translatrix.getTranslationString("labButton.buttonText"), PatientManagerModule.getMiniIcon(PatientManagerModule.LAB_BUTTON));			
		} else {
			labButton = new JButton(Translatrix.getTranslationString("labButton.buttonText"), PatientManagerModule.getMediumIcon(PatientManagerModule.LAB_BUTTON));
		}
		labButton.setHorizontalAlignment(SwingConstants.LEFT);
		labButton.setEnabled(true);
		labButton.setToolTipText(Translatrix.getTranslationString("labButton.buttonTip"));
		labButton.setIconTextGap(1);
		labButton.setFont(GECAMedFonts.BUTTON_FONT);
		labButton.setMargin(new java.awt.Insets(0, 0, 0, 0));

		final JMenuItem menuItemCyberLab = new JMenuItem(Translatrix.getTranslationString("cyberlabKetterthill.button"), PatientManagerModule.getMediumIcon(PatientManagerModule.CYBERLAB_ICON));
		menuItemCyberLab.setToolTipText(Translatrix.getTranslationString("cyberlabKetterthill.buttonTip"));
		final JMenuItem menuItemMedLogin = new JMenuItem(Translatrix.getTranslationString("medLogin.button"), PatientManagerModule.getMediumIcon(PatientManagerModule.MEDLOGIN_ICON));
		menuItemMedLogin.setToolTipText(Translatrix.getTranslationString("medLogin.buttonTip"));
		final JMenuItem menuItemLabTalon = new JMenuItem(Translatrix.getTranslationString("labTalon.button"), PatientManagerModule.getMediumIcon(PatientManagerModule.LABTALON_ICON));
		menuItemLabTalon.setToolTipText(Translatrix.getTranslationString("labTalon.buttonTip"));
		
		ActionListener labButtonsPopupActionListener = new ActionListener() {
			
			public void actionPerformed(ActionEvent e)
			{
				if (menuItemCyberLab.equals(e.getSource()))
				{
					CyberlabInitDialog cyberlabInitDialog = new CyberlabInitDialog(Translatrix.getTranslationString("cyberlabKetterthill.dialogTitle"), true, true);
					cyberlabInitDialog.showDialog();
				}
				if (menuItemMedLogin.equals(e.getSource()))
				{
					MedLoginInitDialog medLoginInitDialog = new MedLoginInitDialog(Translatrix.getTranslationString("medLogin.dialogTitle"), true, true);
					medLoginInitDialog.showDialog();
				}
				if (menuItemLabTalon.equals(e.getSource()))
				{
					// not use jet
//					LabTalonInitDialog labTalonInitDialog = new LabTalonInitDialog(Translatrix.getTranslationString("cyberlabKetterthill.dialogTitle"), true, true);
//					labTalonInitDialog.showDialog();
					
					// direct call of the url Lab Talon
					String url = "https://labtalon.lu/resmed/fr/login?r=%2Fresults%2Fpatients";
					
					java.awt.Desktop desktop = null;
					// Before more Desktop API is used, first check 
					// whether the API is supported by this particular 
					// virtual machine (VM) on this particular host.
					//if (Desktop.isDesktopSupported())
					if(VersionUtils.isSmallerJavaVersionThan(6))
					{
						desktop = java.awt.Desktop.getDesktop();
						if (desktop.isSupported(java.awt.Desktop.Action.BROWSE))
						{
							URI uri = null;
					        try {
					            uri = new URI(url);
					            desktop.browse(uri);
					        }
					        catch(IOException ioe) {
					        	logger.log(Level.WARN, "Can't launching Browser.", ioe);
					        	JOptionPane.showMessageDialog(MainFrame.getInstance(),
					        			Translatrix.getTranslationString("medLogin.inuptErrorText"),
					        			Translatrix.getTranslationString("medLogin.inputErrorTitle"),
									    JOptionPane.WARNING_MESSAGE);
					        }
					        catch(URISyntaxException use) {
					        	logger.log(Level.WARN, "Can't launching Browser.", use);
					        	JOptionPane.showMessageDialog(MainFrame.getInstance(),
					        			Translatrix.getTranslationString("medLogin.inputErrorText"),
					        			Translatrix.getTranslationString("medLogin.inputErrorTitle"),
									    JOptionPane.WARNING_MESSAGE);
					        }
					    }else{
					    	logger.log(Level.WARN, "Desktop API doesn't support the browse action, can't launching Browser.");
						    if(!UrlOpener.openURL(url))
							{
								logger.log(Level.WARN, "ERROR: Launching Browser.");
								JOptionPane.showMessageDialog(MainFrame.getInstance(),
										"Can't launching the default system Browser",
										"Error: Launching Browser",
										JOptionPane.WARNING_MESSAGE);
							}
						}
					}else{
						logger.log(Level.WARN, "Desktop API not supported, can't launching Browser.");
						if(!UrlOpener.openURL(url))
						{
							logger.log(Level.WARN, "ERROR: Launching Browser.");
							JOptionPane.showMessageDialog(MainFrame.getInstance(),
									"Can't launching the default system Browser",
									"Error: Launching Browser",
									JOptionPane.WARNING_MESSAGE);
						}
					}
				}	
			}
		};
		
		LabButtonsPopup = new JPopupMenu();
		menuItemCyberLab.addActionListener(labButtonsPopupActionListener);
	    LabButtonsPopup.add(menuItemCyberLab);
	    menuItemMedLogin.addActionListener(labButtonsPopupActionListener);
	    LabButtonsPopup.add(menuItemMedLogin);
	    menuItemLabTalon.addActionListener(labButtonsPopupActionListener);
	    LabButtonsPopup.add(menuItemLabTalon);
	    
		functionButtonPanel.addButton(labButton);
		labButton.addMouseListener(new MouseListener() {
			
			public void mouseReleased(MouseEvent arg0)
			{
				LabButtonsPopup.show(arg0.getComponent(),arg0.getX(), arg0.getY());
			}
			
			public void mousePressed(MouseEvent arg0) {}
			
			public void mouseExited(MouseEvent arg0) {}
			
			public void mouseEntered(MouseEvent arg0) {}
			
			public void mouseClicked(MouseEvent arg0) {}
		});
		
		// -------------------------------------------------------
		// epSOS Button
		// -------------------------------------------------------
		JButton epSOSButton;
		if (smallIcons) {
			epSOSButton = new JButton(IconFetcher.getIcon(PatientManagerModule.class, PatientManagerModule.EPSOS_ICON_16));			
		} else {
			epSOSButton = new JButton(IconFetcher.getIcon(PatientManagerModule.class, PatientManagerModule.EPSOS_ICON_24));
		}
		epSOSButton.setHorizontalAlignment(SwingConstants.LEFT);
		epSOSButton.setEnabled(true);
		epSOSButton.setToolTipText(Translatrix.getTranslationString("epsosButton.toolTip"));
		epSOSButton.setIconTextGap(1);
		epSOSButton.setFont(GECAMedFonts.BUTTON_FONT);
		epSOSButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
		epSOSButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				java.awt.Desktop desktop = null;
				// Before more Desktop API is used, first check 
			    // whether the API is supported by this particular 
			    // virtual machine (VM) on this particular host.
			    //if (Desktop.isDesktopSupported())
			    String epsosUrl = ESanteConfigManagerBean.getInstance().getESantePropertyValue(ESanteProperty.PROP_EPSOS_URL);
			    
				if(VersionUtils.isSmallerJavaVersionThan(6))
				{
			        desktop = java.awt.Desktop.getDesktop();
			        if (desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
//			        	cyberlabPanel.saveLoginNameAndPassword();
			        	
			        	// launch browser
			        	onLaunchBrowser(epsosUrl,desktop);
			        }else{
			        	//System.out.println("WARNING: Desktop API doesn't support the browse action, can't launching Browser.");
			        	logger.log(Level.WARN, "Desktop API doesn't support the browse action, can't launching Browser.");
			        	if (!UrlOpener.openURL(epsosUrl))
			        	{
							logger.log(Level.WARN, "ERROR: Launching Browser.");
							JOptionPane.showMessageDialog(MainFrame.getInstance(),
								    "Can't launching the default system Browser",
								    "Error: Launching Browser",
								    JOptionPane.WARNING_MESSAGE);
						}
			        }
			    }else{
			    	//System.out.println("WARNING: Desktop API not supported, can't launching Browser.");
			    	logger.log(Level.WARN, "Desktop API not supported, can't launching Browser.");
			    	
			    	if(!UrlOpener.openURL(epsosUrl))
			    	{
						logger.log(Level.WARN, "ERROR: Launching Browser.");
						JOptionPane.showMessageDialog(MainFrame.getInstance(),
							    "Can't launching the default system Browser",
							    "Error: Launching Browser",
							    JOptionPane.WARNING_MESSAGE);
					}
			    }
//				MedLoginInitDialog medLoginInitDialog = new MedLoginInitDialog(Translatrix.getTranslationString("medLogin.dialogTitle"), true, true);
//				medLoginInitDialog.showDialog();
			}
		});
		
		if (GECAMedUtils.isTrue(ESanteConfigManagerBean.getInstance().getESantePropertyValue(ESanteProperty.PROP_SHOW_EPSOS_BUTTON), true))
			functionButtonPanel.addButton(epSOSButton);
		
		// -------------------------------------------------------
		// MedLogin Button
		// -------------------------------------------------------
//		JButton medLoginButton = null;
//		if (smallIcons) {
//			medLoginButton = new JButton(Translatrix.getTranslationString("medLogin.button"), PatientManagerModule.getMiniIcon(PatientManagerModule.MEDLOGIN_ICON));			
//		} else {
//			medLoginButton = new JButton(Translatrix.getTranslationString("medLogin.button"), PatientManagerModule.getMediumIcon(PatientManagerModule.MEDLOGIN_ICON));
//		}
//		medLoginButton.setHorizontalAlignment(SwingConstants.LEFT);
//		medLoginButton.setEnabled(true);
//		medLoginButton.setToolTipText(Translatrix.getTranslationString("medLogin.buttonTip"));
//		medLoginButton.setIconTextGap(1);
//		medLoginButton.setFont(GECAMedFonts.BUTTON_FONT);
//		medLoginButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
//		medLoginButton.addActionListener(new ActionListener() {
//			public void actionPerformed(ActionEvent e)
//			{
//				MedLoginInitDialog medLoginInitDialog = new MedLoginInitDialog(Translatrix.getTranslationString("medLogin.dialogTitle"), true, true);
//				medLoginInitDialog.showDialog();
//			}
//		});
//		functionButtonPanel.addButton(medLoginButton);
		
//		// -------------------------------------------------------
//		// Dr. G Button ;)
//		// -------------------------------------------------------
//		JButton drgButton = null;
//		if (smallIcons) {
//			drgButton = new JButton(PatientManagerModule.getScaledIcon("drg.png", 64, 16));	
//		} else {
//			drgButton = new JButton(PatientManagerModule.getScaledIcon("drg.png", 94, 24));
//		}
//		drgButton.setHorizontalAlignment(SwingConstants.LEFT);
//		drgButton.setEnabled(true);
//		drgButton.setToolTipText("Dr. Google :)"); 
//		drgButton.setToolTipText("<html><img src=\"" +
//	      PatientPanel.class.getResource("\\resources\\icons\\drgtooltip.png") +
//	      "\"><p>Dr. Google :)</p>");
//		drgButton.setIconTextGap(1);
//		drgButton.setFont(GECAMedFonts.BUTTON_FONT);
//		drgButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
//		drgButton.addActionListener(new ActionListener() {
//			public void actionPerformed(ActionEvent e)
//			{
//				
//					String drgURL = "http://www.google.de"; 
//					Desktop desktop = null;
//				    // Before more Desktop API is used, first check 
//				    // whether the API is supported by this particular 
//				    // virtual machine (VM) on this particular host.
//				    //if (Desktop.isDesktopSupported())
//				    if(VersionUtils.isSmallerJavaVersionThan(6))
//					{
//				        desktop = Desktop.getDesktop();
//				        if (desktop.isSupported(Desktop.Action.BROWSE)) 
//				        {
//				        	// launch browser
//				        	URI uri = null;
//				            try {
//				                uri = new URI(drgURL);
//				                desktop.browse(uri);
//				            }
//				            catch(IOException ioe) {
//				                ioe.printStackTrace();
//				            }
//				            catch(URISyntaxException use) {
//				                use.printStackTrace();
//				            }
//				            
//				        }else{
//				        	//System.out.println("WARNING: Desktop API doesn't support the browse action, can't launching Browser.");
//				        	logger.log(Level.WARN, "Desktop API doesn't support the browse action, can't launching Browser.");
//				        	try {
//								BrowserLauncher.openURL(drgURL);
//							} catch (IOException e1) {
//								logger.log(Level.WARN, "ERROR: Launching Browser.", e1);
//								JOptionPane.showMessageDialog(MainFrame.getInstance(),
//									    "Can't launching the default system Browser",
//									    "Error: Launching Browser",
//									    JOptionPane.WARNING_MESSAGE);
//							}
//				        }
//				    }else{
//				    	//System.out.println("WARNING: Desktop API not supported, can't launching Browser.");
//				    	logger.log(Level.WARN, "Desktop API not supported, can't launching Browser.");
//				    	try {
//							BrowserLauncher.openURL(drgURL);
//						} catch (IOException e1) {
//							logger.log(Level.WARN, "ERROR: Launching Browser.", e1);
//							JOptionPane.showMessageDialog(MainFrame.getInstance(),
//								    "Can't launching the default system Browser",
//								    "Error: Launching Browser",
//								    JOptionPane.WARNING_MESSAGE);
//						}
//				    }
//			    }
//			
//		});
//		functionButtonPanel.addButton(drgButton);
	}
	
	
	/**
	 * Return patientButton panel
	 * 
	 * @return
	 */
	public PatientButtonPanel getButtonGroup() {
		/* ====================================================== */
		return this.patientButtonPanel;
		/* ====================================================== */
	}

	/**
	 * @param evt
	 */
	public void propertyChange(PropertyChangeEvent evt) {
		/* ============================================= */
		if (evt.getPropertyName().equals(GECAMedTab.DATA_CHANGED)) {
//		    new Exception().printStackTrace();
			setModified((Boolean)evt.getNewValue());
//			firePropertyChange(GECAMedTab.DATA_CHANGED, evt.getOldValue(), evt.getNewValue());
		}
		/* ============================================= */
	}

	/**
	 * @return the functionButtonPanel
	 */
	public PatientButtonPanel getFunctionButtonPanel() {
		return functionButtonPanel;
	}

	/**
//	 * @return the modified
//	 */
//	public boolean isModified() {
//		return this.modified;
//	}
	
	
	public void openConsultation (Incident incident)
	{
		openConsultation(incident.getId(), null);
	}
	
	
	/**
	 * @param incidentId
	 */
	public void openConsultation (IncidentEntry entry) 
	{
		openConsultation(entry.getIncidentId(), entry.getId());
	}
	
	
	private void openConsultation (Integer incidentId, Integer entryId)
	{
		if (this.incidentTab != null)
		{
			this.incidentTab.openConsultation(incidentId, entryId);
		}
		else
		{
			// if no incident tab is set for example if user is secretary
			// open the Prescription by double click on the history view 
			PrescriptionManager manager = (PrescriptionManager) ManagerFactory.getRemote(PrescriptionManagerBean.class);
			
			List<Prescription> prescriptionList = manager.getPrescriptionByIncidentEntry(entryId);
			
			if (prescriptionList != null && prescriptionList.size() > 0)
			{
				Prescription prescription = prescriptionList.get(0);
				this.getPrescriptionDataModel().setPrescription(prescription);
			}
		}
	}
	
	
	/**
	 * @return
	 */
	public AntecedentsListModel getAntecedentModel() {
		/* ====================================================== */
		return this.antecedentModel;
		/* ====================================================== */
	}
	
	public ImportantDataModel getImportantDataModel() {
		/* ================================================== */
		return this.importantDataModel;
		/* ================================================== */
	}

//	public HistoryTableModel getHistoryTableModel() {
//		/* ====================================================== */
//		return this.historyTableModel;
//		/* ====================================================== */
//	}
	
	public MemoControler getMemoControler() {
		/* ================================================== */
		return this.memoControler;
		/* ================================================== */
	}
	
	public IncidentTab getIncidentTab() {
		/* ================================================== */
		return this.incidentTab;
		/* ================================================== */
	}
	
	public PrescriptionDataModel getPrescriptionDataModel()
	{
		return this.prescriptionDataModel;
	}



	public void actionPerformed(ActionEvent e) {
		/* ====================================================== */
		if (fileImportButton.equals(e.getSource())) {
			/* ------------------------------------------------------- */
			// show the import
			/* ------------------------------------------------------- */
			FileImportDialog fd = new FileImportDialog();
			/* ------------------------------------------------------- */
			
			if (fd.showDialog(overviewViewPanel.getSelectedIncident(), null)) {
				reloadHistory();
			}
			
			/* ------------------------------------------------------- */
		}
		/* ====================================================== */
	}
	
	
	/**
	 * Reloads the data of the history from the database
	 */
	public void reloadHistory() {
		/* ================================================== */
		this.historyDataAgent.reload();
		/* ================================================== */
	}
	
	
	/**
	 * @return the historyDataAgent
	 */
	public HistoryDataAgent getHistoryDataAgent() {
		/* ================================================== */
		return historyDataAgent;
		/* ================================================== */
	}

	@Override
	public String getName() {
		return null;
	}
	
	
	
	/**
	 * Returns the current incident of 
	 * the current patient and physician
	 * if none exists, a new one is created
	 * 
	 * @return a incident
	 */
	public Incident getIncidentAtATimePoint(boolean createNewIfNotExists, Calendar newerThan, Calendar olderThan) {
		/* ================================================== */

		if (newerThan == null || olderThan == null) {
			try {
				throw new Exception("None of the 2 Calendars may be NULL!");
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				return null;
			}
		}
		
		/* check, if there is an incident, newer than the newerThan
		 * and older than olderThan
		 */
		Incident incident = incidentManager.getIncidentNewerThan(
	    		this.getPatient().getId(), 
	    		GECAMedModule.getCurrentPhysician().getId(), 
	    		newerThan.getTime(), 
	    		olderThan.getTime());
		
		/* ------------------------------------------------------- */
		// if null, we have to create a new one
		/* ------------------------------------------------------- */
	    if (incident == null && createNewIfNotExists) {
	    	incident = new Incident();
	    	incident.setSiteId(MainFrame.getCurrentSiteId());
	    	incident.setPhysicianId(MainFrame.getCurrentPhysician().getId());
	    	incident.setPatientId(this.getPatient().getId());
	    	incident.setIncidentDate(olderThan.getTime());
	    	
	    	try {
	    		IncidentManager iManager = (IncidentManager) ManagerFactory.getRemote(
	    				IncidentManagerBean.class);
	    		incident = iManager.saveIncident(incident);
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    	}
		}
		return incident;	
		/* ================================================== */
	}
	
	
	public Incident getCurrentIncident (boolean createNewIfNotExists) {
		// reset current incident if current physician is different
		if (this.incident != null && this.incident.getPhysicianId() != GECAMedModule.getCurrentPhysician().getId())
			this.incident = null;
		
		// reload incident
		if (this.incident != null)
			this.incident = incidentManager.getIncident(incident.getId());
		
		if (this.incident != null)
			return this.incident;
		
		Calendar newerThan = new GregorianCalendar();
		// check if there is an incident newer than 4h
		newerThan.add(Calendar.HOUR_OF_DAY, -4);
		Calendar olderThan = new GregorianCalendar();
		
		this.incident = getIncidentAtATimePoint(createNewIfNotExists, newerThan, olderThan);
		return this.incident;
//		return getIncidentAtATimePoint(createNewIfNotExists, newerThan, olderThan);
	}
	

	public Incident getCurrentIncident() {
		return getCurrentIncident(true);
	}
	
	
	@Override
	public void incidentEntryDeleted(IncidentEntry entry) {
		for (PatientViewTab tab : tabs.values()) {
			tab.incidentEntryDeleted(entry);
		}
		
		// close open prescription
		if (getPrescriptionDataModel().getPrescription() != null &&
				getPrescriptionDataModel().getPrescription().getIncidentEntry() != null &&
				entry.equals(getPrescriptionDataModel().getPrescription().getIncidentEntry())) {
			getPrescriptionDataModel().setPrescription(new Prescription());
		}
	}


	public PrescriptionDataDialog getPrescriptionDialog()
    {
    	return this.prescriptionDataDialog;
    }
	
	/**
	 * Starts the default system web-browser over the desktop API (Java 1.6) and open the given url.
	 * @param url - the url to open in the web-browser
	 * @param desktop - handle to desktop object
	 */
	private void onLaunchBrowser(String url, java.awt.Desktop desktop) {
        URI uri = null;
        try {
            uri = new URI(url);
            desktop.browse(uri);
        }
        catch(IOException ioe) {
        	logger.log(Level.WARN, "Can't launching Browser.", ioe);
        	JOptionPane.showMessageDialog(MainFrame.getInstance(),
        			Translatrix.getTranslationString("medLogin.inuptErrorText"),
        			Translatrix.getTranslationString("medLogin.inputErrorTitle"),
				    JOptionPane.WARNING_MESSAGE);
        }
        catch(URISyntaxException use) {
        	logger.log(Level.WARN, "Can't launching Browser.", use);
        	JOptionPane.showMessageDialog(MainFrame.getInstance(),
        			Translatrix.getTranslationString("medLogin.inputErrorText"),
        			Translatrix.getTranslationString("medLogin.inputErrorTitle"),
				    JOptionPane.WARNING_MESSAGE);
        }
    }
	
	
	public void permanentlyDisableTab (String tabName)
	{
		PatientViewTab tab = tabs.get(tabName);
		tab.setPermanentlyDisabled(true);
		disabledTabs.add(tab);
		enableTab (tabName, false);
	}
	
	
	public void enableTab (String tabName, boolean enable)
	{
		PatientViewTab tab = tabs.get(tabName);
		if (tab != null)
		{
			if (enable && !disabledTabs.contains(tabName))
				tab.enableTab();
			else
				tab.disableTab();
		}
	}
}