/*****************************************************************************
 *                                                                           *
 *  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.prescription.gui.widgets;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedTitledBorder;
import lu.tudor.santec.gecamed.core.gui.utils.WindowToolbox;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialog;
import lu.tudor.santec.gecamed.core.gui.widgets.NamedComponentVariable;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.letter.gui.components.LimitedTextArea;
import lu.tudor.santec.gecamed.prescription.ejb.entity.beans.PosologyTemplate;
import lu.tudor.santec.gecamed.prescription.ejb.session.beans.PrescriptionManagerBean;
import lu.tudor.santec.gecamed.prescription.ejb.session.interfaces.PrescriptionManager;
import lu.tudor.santec.i18n.Translatrix;
import lu.tudor.santec.widgets.gui.ButtonFactory;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * This is the posology choser. It offers multiple list to create drug posologies by clicking.
 * 
 * 
 * @author Johannes Hermen johannes.hermen(at)tudor.lu
 * 16.01.2008
 * 15:24:36
 *
 *
 * @version
 * <br>$Log: PosologyChooserDialog.java,v $
 * <br>Revision 1.29  2013-12-27 18:09:27  donak
 * <br>Cleanup of imports
 * <br>
 * <br>Revision 1.28  2012-07-26 14:36:05  troth
 * <br>Clear up code.
 * <br>
 * <br>Revision 1.27  2012-07-24 10:06:26  troth
 * <br>fix Ticket #1012 now the text is insert on the text cursor position of the textfield.
 * <br>
 * <br>Revision 1.26  2012-07-23 12:09:41  troth
 * <br>fix Ticket #1011 and #1012
 * <br>
 * <br>Revision 1.25  2012-07-19 15:46:43  troth
 * <br>fix Ticket #1011 - Falsche franz�sische �bersetzung im generierten Dosierungstext.
 * <br>
 * <br>Revision 1.24  2012-06-11 16:08:42  troth
 * <br>fix Ticket #990 - Textfield allows more characters than the database column.
 * <br>
 * <br>Revision 1.23  2012-03-20 14:44:11  troth
 * <br>1. Fix Ticket #948: Dosierungsvorlagen in Verschreibungsvorlagen l�schen bringt Fehler wenn leer.
 * <br>2. And remove same warnings.
 * <br>
 * <br>Revision 1.22  2011-03-15 09:19:23  troth
 * <br>complete - # 799: "Dosierungsform ""unit�"" ben�tigt"
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/799
 * <br>
 * <br>Revision 1.21  2010-10-20 14:26:26  troth
 * <br>remove system.out.println
 * <br>
 * <br>Revision 1.20  2010-05-31 13:05:41  troth
 * <br>bug fix - Incomplete - # 521: Unvollst�ndige Anzeige der Verschreibungen im Verlaufsbereich
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/521
 * <br>
 * <br>Revision 1.19  2010-05-17 08:44:23  troth
 * <br>small bugfix - add special character
 * <br>Incomplete - # 497: Seltsame Mengenbezeichnungen "½" und "¼" im Posologie-Fenster
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/497
 * <br>
 * <br>Revision 1.18  2010-05-11 13:28:50  troth
 * <br>Incomplete - # 197: PosologyChooser: use selected template
 * <br>http://santec.tudor.lu/trac/gecamed/ticket/197
 * <br>
 * <br>Revision 1.17  2010-04-27 11:36:36  troth
 * <br>special  character for quantities array
 * <br>
 * <br>Revision 1.16  2010-03-25 12:20:39  troth
 * <br>updated javadoc and refactured code
 * <br>
 * <br>Revision 1.15  2010-03-24 19:20:59  troth
 * <br>Redesign of the patient view history - PosologyChooserDialog extends now from GECAMedBaseDialog
 * <br>
 * <br>Revision 1.14  2010-03-11 12:19:06  troth
 * <br>add translatrix function
 * <br>
 * <br>Revision 1.13  2009-01-19 15:57:57  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.12  2008-12-05 17:34:23  heinemann
 * <br>moved some basic classes to lu.tudor.santec.widgets
 * <br>
 * <br>Revision 1.11  2008-10-09 12:39:55  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.10  2008-09-25 09:43:07  heinemann
 * <br>fixed copyrights
 * <br>
 * <br>Revision 1.9  2008-09-10 15:19:50  heinemann
 * <br>lesser height
 * <br>
 * <br>Revision 1.8  2008-06-12 15:18:30  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.7  2008-06-12 13:05:43  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.6  2008-06-12 09:41:26  heinemann
 * <br>*** empty log message ***
 * <br>
 * <br>Revision 1.5  2008-01-16 15:33:36  heinemann
 * <br>better documentation
 * <br>
 *   
 */
public class PosologyChooserDialog extends GECAMedBaseDialog implements ActionListener{

	private static final long serialVersionUID = 1L;
	private ButtonGroup freqGroup;
	private JRadioButton freqGroupResetter;
	
	private JButton undoButton;
	private ButtonGroup timeGroup;
	private JRadioButton timeGroupResetter;
	private ButtonGroup mealGroup;
	private JRadioButton mealGroupResetter;
	private ButtonGroup periodGroup;
	private JRadioButton periodGroupResetter;
	private LimitedTextArea posologieTextTotal;
	private JTextField quantityTextField;
	private JTextField typeTextField;
	private JList typeList;
	private JList quantityList;
	private JButton addButton;
	private LayoutManager gridLayout = new GridLayout(0,1, 2, 2);
	private KeyListener focusKeyListener;
	private JButton saveTemplateButton;
	private JList templateList;
	private DefaultListModel templateListModel;
	private JButton addTemplateButton;
	private PrescriptionManager manager;
	private JPopupMenu popup;
	private static PosologyChooserDialog posologyChooserDialog;
	
	private boolean posologyChanged 	= false;
	private boolean selectionChanged 	= false;
	private boolean isTemplateListSelected = false;
	private CellConstraints cc;
	private JDialog showingDialog;
	private int templateListRow = -1;

	/**
	 * 
	 */
	public PosologyChooserDialog() {
		/* ================================================== */
		super(Translatrix.getTranslationString("doseDialog.title"), true, true);
				
		JPanel panel = new JPanel();
		
		panel.setBackground(GECAMedColors.c_GECAMedBackground);
		
		panel.setLayout(new FormLayout(
				"5dlu, fill:50dlu, 3dlu, fill:50dlu, 3dlu, fill:85dlu, 3dlu, fill:95dlu, 3dlu, pref, 5dlu", // cols
				"5dlu, 0dlu, 0dlu, fill:180dlu, 3dlu, fill:pref, center:40dlu, fill:90dlu, 3dlu, fill:55dlu, 3dlu, pref, 5dlu")); // rows
	
		this.cc = new CellConstraints();
		/* ------------------------------------------------------- */
   	 	// Get the type manager
		/* ------------------------------------------------------- */
		this.manager = (PrescriptionManager) ManagerFactory.getRemote(PrescriptionManagerBean.class);
		/* ------------------------------------------------------- */
		// create a keylistener to ensure the right focus traversal from 
		// each radio group an list
		/* ------------------------------------------------------- */
		initFocusKeyListener();
		/* ------------------------------------------------------- */
		
		/* ------------------------------------------------------- */
		// create the groups
		/* ------------------------------------------------------- */
		
		panel.add(new NamedComponentVariable(Translatrix.getTranslationString("doseDialog.amount"), createQuantityPanel()),	cc.xywh(2, 4, 1, 3));
		panel.add(new NamedComponentVariable(Translatrix.getTranslationString("doseDialog.form"), createTypePanel()),	cc.xywh(4, 4, 1, 3));
		
		panel.add(new NamedComponentVariable(Translatrix.getTranslationString("doseDialog.frequency"), createFreqPanel()), 	cc.xy(6, 4));
		panel.add(new NamedComponentVariable(Translatrix.getTranslationString("doseDialog.period"), createPeriodPanel()),	cc.xy(6, 6));
		
		panel.add(new NamedComponentVariable(Translatrix.getTranslationString("doseDialog.times"), createTimePanel()),		cc.xyw(8, 4, 3));
		panel.add(new NamedComponentVariable(Translatrix.getTranslationString("doseDialog.meal"), createMealPanel()), 	 	cc.xyw(8, 6, 2));
		/* ------------------------------------------------------- */
		addButton = new JButton(Translatrix.getTranslationString("doseDialog.buttons.add"));
		
		addButton.setIcon(GECAMedModule.getMediumIcon(GECAMedModule.ADD));
		addButton.addActionListener(this);
		
		addButton.setPreferredSize(new Dimension(addButton.getPreferredSize().width, 
									(int) (addButton.getPreferredSize().height*1.15)));

		panel.add(addButton, cc.xyw(2, 7, 9));
		/* ------------------------------------------------------- */
		JPanel jp = new JPanel(new BorderLayout(5,5));
		jp.setOpaque(false);
		templateListModel = new DefaultListModel();
		/* ------------------------------------------------------- */
		try {
			List<PosologyTemplate> templates = manager.getPosologyTemplates(GECAMedModule.getCurrentPhysician().getId());
			for (PosologyTemplate element : templates) {
				templateListModel.addElement(element);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		/* ------------------------------------------------------- */
		templateList = new JList(templateListModel);
		JScrollPane jspl = new JScrollPane(templateList);
		jspl.setOpaque(false);
		jspl.getViewport().setOpaque(false);
		jp.add(jspl);

		/* ------------------------------------------------------- */
		addTemplateButton = ButtonFactory.createNarrowButton(GECAMedModule.getSmallIcon(GECAMedModule.ADD));
		addTemplateButton.setToolTipText(Translatrix.getTranslationString("doseDialog.buttons.add"));
		
		addTemplateButton.addActionListener(this);
		JPanel bb = new JPanel(new BorderLayout());
		bb.setOpaque(false);
		bb.add(addTemplateButton, BorderLayout.NORTH);
		
		/* ------------------------------------------------------- */
		JPanel templatePanel = new JPanel(new BorderLayout());
		templatePanel.setOpaque(false);
		templatePanel.setBorder(new GECAMedTitledBorder(Translatrix.getTranslationString("doseDialog.template")));
		
		templatePanel.add(jp, BorderLayout.CENTER);
		templatePanel.add(bb, BorderLayout.EAST);
		
		panel.add(templatePanel, cc.xyw(2, 8, 9));
		/* ------------------------------------------------------- */
		posologieTextTotal = new LimitedTextArea(500);
		
		JScrollPane paine = new JScrollPane(posologieTextTotal);
		paine.setOpaque(false);
		paine.getViewport().setOpaque(false);
		paine.setBorder(new GECAMedTitledBorder(Translatrix.getTranslationString("doseDialog.dosetotal")));
		
		panel.add(paine, cc.xyw(2, 10, 9));
		/* ------------------------------------------------------- */
		// add a documentlistener on the textarea to be informed if the user changed
		// the assembled posology by hand
		/* ------------------------------------------------------- */
		this.posologieTextTotal.getDocument().addDocumentListener(new DocumentListener() {

			public void changedUpdate(DocumentEvent e) {
				/* ====================================================== */	
				posologyChanged = true;
				/* ====================================================== */
			}

			public void insertUpdate(DocumentEvent e) {
				/* ====================================================== */				
				posologyChanged = true;
				/* ====================================================== */
			}

			public void removeUpdate(DocumentEvent e) {
				/* ====================================================== */
				posologyChanged = true;
				/* ====================================================== */
			}
		});
		/* ------------------------------------------------------- */
		// init the JPopup menu for right click in the template field
		/* ------------------------------------------------------- */
		initPopup();
		/* ------------------------------------------------------- */
		// create the buttons for the lower side
		/* ------------------------------------------------------- */
		buildBottomButtons(panel);
		/* ------------------------------------------------------- */
		
		this.add(panel);
		this.setResizable(false);
		this.pack();
		
		posologyChooserDialog = this;
		/* ================================================== */
	}
	
	
	/**
	 * create a keylistener to ensure the right focus traversal from 
     * each radio group an list
	 */
	private void initFocusKeyListener() {
		/* ====================================================== */
		this.focusKeyListener = new KeyAdapter() {
			
			@Override
			public void keyReleased(KeyEvent e) {
				/* ================================================== */
				if (e.getSource() instanceof JList) {
					if (e.getKeyCode() == KeyEvent.VK_LEFT) {
						((JComponent)e.getSource()).transferFocusBackward();
					} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
						((JComponent)e.getSource()).transferFocus();
					}
				} 	else if (e.getSource() instanceof JRadioButton) {
					if (e.getKeyCode() == KeyEvent.VK_LEFT) {
						((JComponent)e.getSource()).transferFocusUpCycle();
					} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
						((JComponent)e.getSource()).transferFocusUpCycle();
					} else if (e.getKeyCode() == KeyEvent.VK_UP) {
						((JComponent)e.getSource()).transferFocusBackward();
					}else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
						((JComponent)e.getSource()).transferFocus();
					}
				} else if (e.getSource() instanceof JTextField) {
					if (e.getKeyCode() == KeyEvent.VK_UP) {
						((JComponent)e.getSource()).transferFocusUpCycle();
					}else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
						((JComponent)e.getSource()).transferFocusDownCycle();
					}
				}
				/* ================================================== */
			}
			
		};
		/* ====================================================== */
	}


	/**
	 * Build the buttons for the bottom line save template, revert, cancel, ok
	 */
	private void buildBottomButtons(JPanel panel) {
		/* ================================================== */
			
		this.saveTemplateButton = new JButton(Translatrix.getTranslationString("template.saveas"));

		this.saveTemplateButton.addActionListener(this);
		this.addButton(saveTemplateButton);//bbb.addFixed(saveTemplateButton);
		
		this.undoButton = new JButton(Translatrix.getTranslationString("core.clear"));
		this.undoButton.addActionListener(this);
		this.addButton(undoButton);//this.addFixed(undoButton);
		
		this.cancelButton.addActionListener(this);
		this.okButton.addActionListener(this);
		/* ================================================== */
	}
	
	
	/**
	 * Init the popup menu
	 */
	private void initPopup() {
		/* ================================================== */
		/* ------------------------------------------------------- */
		// init the popup
		/* ------------------------------------------------------- */
		this.popup = new JPopupMenu();
		
		JMenuItem delete = new JMenuItem(
				Translatrix.getTranslationString("core.delete"),
				GECAMedModule.getSmallIcon (GECAMedIconNames.REMOVE_LINE));
		/* ------------------------------------------------------ */
		delete.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				/* ============================================= */
				try {
					manager.deletePosologyTemplate((PosologyTemplate)templateList.getSelectedValue());
					templateListModel.remove(templateList.getSelectedIndex());
					templateList.clearSelection();
					isTemplateListSelected = false;
				} catch (Exception e3) {
					e3.printStackTrace();
				}
				/* ============================================= */
			}
		});
		/* ------------------------------------------------------ */
		popup.add(delete);
		
		MouseAdapter popupListener = new MouseAdapter() {

			/* (non-Javadoc)
			 * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
			 */
			@Override
			public void mousePressed(MouseEvent e) {
				/* ============================================= */
				//clicked(e);
				/* ============================================= */
			}

			/* (non-Javadoc)
			 * @see java.awt.event.MouseAdapter#mouseReleased(java.awt.event.MouseEvent)
			 */
			@Override
			public void mouseReleased(MouseEvent e) {
				/* ============================================= */
				clicked(e);
				/* ============================================= */
			}
			
			private void clicked(MouseEvent e) {
				/* ====================================================== */
				
				try {
					int row = templateList.locationToIndex(e.getPoint());
					
					if(templateListRow != row){
						templateListRow = row;
						templateList.setSelectedIndex(row);
						isTemplateListSelected = true;
					}else{
						if(isTemplateListSelected){
							templateList.clearSelection();
							isTemplateListSelected = false;
						}else{
							templateList.setSelectedIndex(row);
							isTemplateListSelected = true;
						}
						
					}
					
				} catch (Exception e1) {
				}
				
				if (e.isPopupTrigger()) {
					if(templateList.getModel().getSize() > 0)
					{
						int row = templateList.locationToIndex(e.getPoint());
						templateList.setSelectedIndex(row);
						templateListRow = row;
						isTemplateListSelected = true;
						popup.show(templateList, e.getX(), e.getY());
					}
				}
				/* ====================================================== */
			}
		};
		templateList.addMouseListener(popupListener);
		/* ================================================== */
	}
	
	/**
	 * @param group
	 * @param text
	 * @return
	 */
	private JRadioButton createRadioButton(ButtonGroup group, String text) {
		/* ================================================== */
		JRadioButton rb = new JRadioButton(text);
		rb.addKeyListener(focusKeyListener);
		rb.setOpaque(false);
		if (text.equals(".")) {
			text = "";
		}
		rb.setActionCommand(text);
		group.add(rb);
		rb.addActionListener(this);
		return rb;
		/* ================================================== */
	}
	
	/**
	 * @param group
	 * @param text
	 * @return
	 */
	private JPanel createRadioButtonTextField(ButtonGroup group, final String text) {
		/* ================================================== */
		JPanel jp = new JPanel(new FlowLayout(FlowLayout.LEFT, 0,0));
		jp.setOpaque(false);
		final JRadioButton rb = new JRadioButton("");
		rb.addKeyListener(focusKeyListener);
		rb.setOpaque(false);
		group.add(rb);
		jp.add(rb);
		final JTextField tf = new JTextField("0",6);
		tf.setHorizontalAlignment(JTextField.RIGHT);
		tf.addKeyListener(new KeyListener(){
			public void keyTyped(KeyEvent e) {
			}
			public void keyPressed(KeyEvent e) {
			}
			public void keyReleased(KeyEvent e)
			{
				int number = 0 ;
				try {
					number = Integer.parseInt(tf.getText());
				} catch (Exception e2) {
					
				}
				
				if(number > 1) rb.setActionCommand(tf.getText() + " " + text);
				else{
					if(text.equals(Translatrix.getTranslationString("doseDialog.period.daily"))) 
						rb.setActionCommand(tf.getText() + " " + Translatrix.getTranslationString("doseDialog.period.day"));
					if(text.equals(Translatrix.getTranslationString("doseDialog.period.weekly"))) 
						rb.setActionCommand(tf.getText() + " " + Translatrix.getTranslationString("doseDialog.period.week"));
					if(text.equals(Translatrix.getTranslationString("doseDialog.period.monthly"))) 
						rb.setActionCommand(tf.getText() + " " + Translatrix.getTranslationString("doseDialog.period.month"));
				}
				rb.doClick();
			}
		});
		jp.add(tf);
		jp.add(new JLabel(text));
		rb.setActionCommand("");
		rb.addActionListener(this);
		return jp;
		/* ================================================== */
	}
	
	private JPanel createFreqPanel() {
		
		int rowAnz = 9;
		JPanel freqPanel = new JPanel(gridLayout); 
		freqPanel.setOpaque(true);
		freqPanel.setBackground(Color.WHITE);
		freqPanel.setBorder(new LineBorder(GECAMedColors.c_GECAMedTitledBorder));
		
		freqGroup = new ButtonGroup();
		freqGroupResetter = createRadioButton(freqGroup, "");
		freqPanel.add(freqGroupResetter);
		freqPanel.add(createRadioButton(freqGroup, "1x " + Translatrix.getTranslationString("doseDialog.daily")));
		freqPanel.add(createRadioButton(freqGroup, "2x " + Translatrix.getTranslationString("doseDialog.daily")));
		freqPanel.add(createRadioButton(freqGroup, "3x " + Translatrix.getTranslationString("doseDialog.daily")));
		freqPanel.add(createRadioButton(freqGroup, "4x " + Translatrix.getTranslationString("doseDialog.daily")));
		
		freqPanel.add(createRadioButtonTextField(freqGroup, ""));

		for (int i = freqPanel.getComponentCount(); i < rowAnz; i++) {
			freqPanel.add(new JLabel());
		}
		return freqPanel;
	}
	
	
	/**
	 * @return
	 */
	private JPanel createTimePanel() {
				
		FormLayout layout = new FormLayout("fill:95dlu", // columns
		"pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu ,pref, 2dlu, pref, 2dlu, pref, 2dlu, pref" ); // rows
		JPanel timePanel = new JPanel(layout);
		timePanel.setOpaque(true);
		timePanel.setBackground(Color.WHITE);
		timePanel.setBorder(new LineBorder(GECAMedColors.c_GECAMedTitledBorder));
		
		timeGroup = new ButtonGroup();
		timeGroupResetter = createRadioButton(timeGroup, "");
		
		timePanel.add(timeGroupResetter, cc.xy(1, 1));
		timePanel.add(createRadioButton(timeGroup, Translatrix.getTranslationString("doseDialog.times.morning")), cc.xy(1, 3));
		timePanel.add(createRadioButton(timeGroup, Translatrix.getTranslationString("doseDialog.times.noon")), cc.xy(1, 5));
		timePanel.add(createRadioButton(timeGroup, Translatrix.getTranslationString("doseDialog.times.evening")), cc.xy(1, 7));
		timePanel.add(createRadioButton(timeGroup, Translatrix.getTranslationString("doseDialog.times.morningAndNoon")), cc.xy(1, 9));
		timePanel.add(createRadioButton(timeGroup, Translatrix.getTranslationString("doseDialog.times.morningAndEvening")), cc.xy(1, 11));
		timePanel.add(createRadioButton(timeGroup, Translatrix.getTranslationString("doseDialog.times.noonAndEvening")), cc.xy(1, 13));
		timePanel.add(createRadioButton(timeGroup, Translatrix.getTranslationString("doseDialog.times.morningNoonEvening")), cc.xy(1, 15));
		timePanel.add(createRadioButton(timeGroup, Translatrix.getTranslationString("doseDialog.times.morningNoonEveningAndBed")), cc.xy(1, 17)); 
		
		return timePanel;
	}
	
	/**
	 * @return
	 */
	private JPanel createMealPanel() {

		int rowAnz = 4;
		
		JPanel mealPanel = new JPanel(gridLayout);
		mealPanel.setOpaque(true);
		mealPanel.setBackground(Color.WHITE);
		mealPanel.setBorder(new LineBorder(GECAMedColors.c_GECAMedTitledBorder));
		
		mealGroup = new ButtonGroup();
		mealGroupResetter =  createRadioButton(mealGroup, "");
		mealPanel.add(mealGroupResetter);
		mealPanel.add(createRadioButton(mealGroup, Translatrix.getTranslationString("doseDialog.meal.before")));
		mealPanel.add(createRadioButton(mealGroup, Translatrix.getTranslationString("doseDialog.meal.during")));
		mealPanel.add(createRadioButton(mealGroup, Translatrix.getTranslationString("doseDialog.meal.after"))); 

		for (int i = mealPanel.getComponentCount(); i < rowAnz; i++) {
			mealPanel.add(new JLabel());
		}
		return mealPanel;
	}
	
	private JPanel createPeriodPanel() {

		int rowAnz = 4;
		
		JPanel periodPanel = new JPanel(gridLayout);
		periodPanel.setOpaque(true);
		periodPanel.setBackground(Color.WHITE);
		periodPanel.setBorder(new LineBorder(GECAMedColors.c_GECAMedTitledBorder));

		periodGroup = new ButtonGroup();
		periodGroupResetter =  createRadioButton(periodGroup, "");
		periodPanel.add(periodGroupResetter);
		periodPanel.add(createRadioButtonTextField(periodGroup, Translatrix.getTranslationString("doseDialog.period.daily")));
		periodPanel.add(createRadioButtonTextField(periodGroup, Translatrix.getTranslationString("doseDialog.period.weekly")));
		periodPanel.add(createRadioButtonTextField(periodGroup, Translatrix.getTranslationString("doseDialog.period.monthly")));
		
		
		
		for (int i = periodPanel.getComponentCount(); i < rowAnz; i++) {
			periodPanel.add(new JLabel());
		}
		return periodPanel;
	}
	
	
	/**
	 * @return
	 */
	private JPanel createQuantityPanel() {
		/* ================================================== */
		String[] quantities = {
				" ",
				"\u00BD", // 1/2
				"\u00BC", // 1/4
				"1",
				"2",
				"3",
				"4",
				"5",
				"6",
				"7",
				"8",
				"9",
				"10",
				"15",
				"20",
				"30",
				"40",
				"50",
				"100",
				"200",
				"500"
		};

		JPanel quantityPanel = new JPanel(new BorderLayout(5,5));
		quantityPanel.setOpaque(false);
		
		quantityList = new JList(quantities);
		quantityList.setSelectedIndex(0);
		quantityList.addKeyListener(focusKeyListener);
		JScrollPane jsp = new JScrollPane(quantityList);
		jsp.setOpaque(false);
		jsp.getViewport().setOpaque(false);
		quantityPanel.add(jsp, BorderLayout.CENTER);
		
		quantityTextField = new JTextField();
		//quantityTextField.setFocusable(false);
		quantityPanel.add(quantityTextField, BorderLayout.SOUTH);
		/* ------------------------------------------------------- */
		// list selection listener
		/* ------------------------------------------------------- */
		quantityList.addListSelectionListener(new ListSelectionListener() {
			
			public void valueChanged(ListSelectionEvent e) {
				/* ------------------------------------------------------- */
				quantityTextField.setText(quantityList.getSelectedValue() + "");
				// set the flag to changed
				PosologyChooserDialog.this.selectionChanged = true;
				/* ------------------------------------------------------- */
			}
		});
		
		quantityTextField.getDocument().addDocumentListener(new DocumentListener() {
			public void insertUpdate(DocumentEvent e) {
				buildPosologie();
			}
			public void removeUpdate(DocumentEvent e) {
				buildPosologie();
			}
			public void changedUpdate(DocumentEvent e) {
				buildPosologie();
			}
		});
		
		return quantityPanel;
		/* ================================================== */
	}
	
	private JPanel createTypePanel() {
		/* ================================================== */
		String[] types = {
				" ",
				Translatrix.getTranslationString("doseDialog.form.amp"),
				Translatrix.getTranslationString("doseDialog.form.applic"),
				Translatrix.getTranslationString("doseDialog.form.bouff"),
				Translatrix.getTranslationString("doseDialog.form.caps"),
				Translatrix.getTranslationString("doseDialog.form.cac"),
				Translatrix.getTranslationString("doseDialog.form.cas"),
				Translatrix.getTranslationString("doseDialog.form.cc"),
				Translatrix.getTranslationString("doseDialog.form.comp"),
				Translatrix.getTranslationString("doseDialog.form.compeff"),
				Translatrix.getTranslationString("doseDialog.form.dose"),
				Translatrix.getTranslationString("doseDialog.form.drag"),
				Translatrix.getTranslationString("doseDialog.form.gel"),
				Translatrix.getTranslationString("doseDialog.form.g"),
				Translatrix.getTranslationString("doseDialog.form.gttes"),
				Translatrix.getTranslationString("doseDialog.form.inhal"),
				Translatrix.getTranslationString("doseDialog.form.injection"),
				Translatrix.getTranslationString("doseDialog.form.mes"),
				Translatrix.getTranslationString("doseDialog.form.mg"),
				Translatrix.getTranslationString("doseDialog.form.ml"),
				Translatrix.getTranslationString("doseDialog.form.ovule"),
				Translatrix.getTranslationString("doseDialog.form.patch"),
				Translatrix.getTranslationString("doseDialog.form.pil"),
				Translatrix.getTranslationString("doseDialog.form.sach"),
				Translatrix.getTranslationString("doseDialog.form.sol"),
				Translatrix.getTranslationString("doseDialog.form.spray"),
				Translatrix.getTranslationString("doseDialog.form.suppo"),
				Translatrix.getTranslationString("doseDialog.form.susp"),
				Translatrix.getTranslationString("doseDialog.form.unit")
		};

		JPanel typePanel = new JPanel(new BorderLayout(5,5));
		typePanel.setOpaque(false);
		
		typeList = new JList(types);
		typeList.setSelectedIndex(0);
		typeList.addKeyListener(focusKeyListener);
		
		JScrollPane jsp = new JScrollPane(typeList);
		
		jsp.setOpaque(false);
		jsp.getViewport().setOpaque(false);
		typePanel.add(jsp, BorderLayout.CENTER);
		
		typeTextField = new JTextField();
		typeTextField.setFocusable(false);
		typePanel.add(typeTextField, BorderLayout.SOUTH);
		/* ------------------------------------------------------- */
		// list selection listener
		/* ------------------------------------------------------- */
		typeList.addListSelectionListener(new ListSelectionListener() {
			
			public void valueChanged(ListSelectionEvent e) {
				/* ------------------------------------------------------- */
				typeTextField.setText(typeList.getSelectedValue() + "");
				// set the flag to changed
				PosologyChooserDialog.this.selectionChanged = true;
				/* ------------------------------------------------------- */
			}
		});
		
		typeTextField.getDocument().addDocumentListener(new DocumentListener() {
			public void insertUpdate(DocumentEvent e) {
				buildPosologie();
			}
			public void removeUpdate(DocumentEvent e) {
				buildPosologie();
			}
			public void changedUpdate(DocumentEvent e) {
				buildPosologie();
			}
		});
		
		return typePanel;
		/* ================================================== */
	}
	
	
	/**
	 * @return
	 */
	public String showDialog(Window parent) {
		/* ================================================== */
		this.reset();
		this.showingDialog =  WindowToolbox.reOwnDialog(this, parent);
		showingDialog.pack();
		MainFrame.showDialogCentered(showingDialog);

		if (! posologieTextTotal.getText().equals("")) {
			// clear html-tags
			String posologieText = posologieTextTotal.getText();
			
			posologieText = posologieText.replace("</html>", "");
			posologieText = posologieText.replace("<html>", "");
			
			return posologieText;//posologieTextTotal.getText();
		}
		return null;
		/* ================================================== */
	}


	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		/* ================================================== */
		
		if (e.getSource().equals(this.undoButton)) {
			this.reset();
		} else 
			if (e.getSource().equals(this.okButton)) {
				/* ------------------------------------------------------- */
				String buildPos = buildPosologie();
				/* ------------------------------------------------------- */
				
				if (posologyChanged || selectionChanged || isTemplateListSelected) {
					
					if(!buildPos.equals(""))
						posologieTextTotal.append(buildPos);
//					else
//						posologieTextTotal.append(buildPos + "\n");
					
					posologyChanged = false;
					
					if(isTemplateListSelected){
						if(!templateList.getSelectedValue().equals(""))
							posologieTextTotal.append(templateList.getSelectedValue() + "");
//						else
//							posologieTextTotal.append(templateList.getSelectedValue() + "\n");
					}
				}
				
//				if (posologyChanged && selectionChanged) {
//						posologieTextTotal.append(buildPos + "\n");
//						posologyChanged = false;
//				}
//				else
//					if (selectionChanged) {
//						posologieTextTotal.append(buildPos + "\n");
//						posologyChanged = false;
//					}
				
					/* ------------------------------------------------------- */
//				this.setVisible(false);
				showingDialog.setVisible(false);
				/* ------------------------------------------------------- */
			} else 
				if (e.getSource().equals(this.cancelButton)) {
					/* ------------------------------------------------------- */
					// reset all fields and close
					/* ------------------------------------------------------- */
					this.reset();
//					this.setVisible(false);
					showingDialog.setVisible(false);
					/* ------------------------------------------------------- */
				} else 
					if (e.getSource().equals(this.addButton)) {
						/* ------------------------------------------------------- */
						// add from selection to the posology
						/* ------------------------------------------------------- */
						posologieTextTotal.append(buildPosologie() + "\n");
						this.selectionChanged = false;
						posologyChanged = false;
						/* ------------------------------------------------------- */
					} else 
						if (e.getSource().equals(this.addTemplateButton)) {
							/* ------------------------------------------------------- */
							// add from template to posology
							/* ------------------------------------------------------- */
							if (templateList.getSelectedValue() != null) {
								posologieTextTotal.append(templateList.getSelectedValue()  + "");
								this.selectionChanged = false;
								posologyChanged = false;
								templateList.clearSelection();
								isTemplateListSelected = false;
							}
							/* ------------------------------------------------------- */
						} else if (e.getSource().equals(this.saveTemplateButton)) {
							/* ------------------------------------------------------- */
							// save template
							/* ------------------------------------------------------- */
							if (posologieTextTotal.getText().length() < 2)
								return;
							PosologyTemplate t = new PosologyTemplate();
							t.setText(posologieTextTotal.getText());
							t.setPhysicianID(GECAMedModule.getCurrentPhysician().getId());
							t = manager.savePosologyTemplate(t);
							templateListModel.addElement(t);
							/* ------------------------------------------------------- */
						} else {
							/* ------------------------------------------------------- */
							// else, action from a radio button or JList
							/* ------------------------------------------------------- */
							// the selected posology has changed!
							/* ------------------------------------------------------- */
							this.selectionChanged = true;
							buildPosologie();
							/* ------------------------------------------------------- */
						}
		/* ================================================== */
	}

	private String buildPosologie() {
		StringBuffer sb = new StringBuffer();
		try {
			if (!quantityTextField.getText().equals(" ") && !quantityTextField.getText().equals(""))
				sb.append(quantityTextField.getText() + " ");	
		} catch (Exception e1) {
		}
		try {
			if (!typeTextField.getText().equals(" ") && !typeTextField.getText().equals(""))
				sb.append(typeTextField.getText() + " ");	
		} catch (Exception e1) {
		}
		try {
			if (freqGroup.getSelection().getActionCommand() != "")
				sb.append(freqGroup.getSelection().getActionCommand() + " ");	
		} catch (Exception e1) {
		}
		try {
			if (timeGroup.getSelection().getActionCommand() != "")
				sb.append(timeGroup.getSelection().getActionCommand() + " ");	
		} catch (Exception e1) {
		}
		try {
			if (mealGroup.getSelection().getActionCommand() != "")
				sb.append(mealGroup.getSelection().getActionCommand() + " ");	
		} catch (Exception e1) {
		}
		try {
			if (periodGroup.getSelection().getActionCommand() != "")
				sb.append(Translatrix.getTranslationString("doseDialog.period.during") + " " + periodGroup.getSelection().getActionCommand() + " ");	
		} catch (Exception e1) {
		}
		
		return sb.toString();
	}



	public void reset() {
		try {
			this.quantityList.setSelectedIndex(-1);
			this.typeList.setSelectedIndex(-1);
			this.freqGroupResetter.setSelected(true);
			this.timeGroupResetter.setSelected(true);
			this.mealGroupResetter.setSelected(true);
			this.periodGroupResetter.setSelected(true);
			
			this.quantityList.requestFocus();
			
//			this.posologieText.setSelectedItem("");
			this.posologieTextTotal.setText("");
			this.selectionChanged = false;
			this.posologyChanged = false;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class FocusRadioButton extends JRadioButton implements FocusListener {
		
		private static final long serialVersionUID = 1L;
		
		public FocusRadioButton(String text) {
			super(text);
			this.addFocusListener(this);
		}

		public void focusGained(FocusEvent e) {
			this.setSelected(true);
		}
		public void focusLost(FocusEvent e) {
		}
	}
	
	public static PosologyChooserDialog getInstance(){
		if (posologyChooserDialog == null) {
			new PosologyChooserDialog();
		}
		return posologyChooserDialog;
	}
	
}
