/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed 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 (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
package lu.tudor.santec.gecamed.billing.gui.templates;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Act;
import lu.tudor.santec.gecamed.billing.ejb.entity.beans.InvoiceTemplate;
import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Rate;
import lu.tudor.santec.gecamed.billing.ejb.entity.beans.TemplateRate;
import lu.tudor.santec.gecamed.billing.ejb.session.beans.InvoiceTemplateBean;
import lu.tudor.santec.gecamed.billing.ejb.session.beans.NomenclatureBean;
import lu.tudor.santec.gecamed.billing.ejb.session.interfaces.InvoiceTemplateInterface;
import lu.tudor.santec.gecamed.billing.ejb.session.interfaces.NomenclatureInterface;
import lu.tudor.santec.gecamed.billing.gui.BillingModule;
import lu.tudor.santec.gecamed.core.gui.GECAMedColors;
import lu.tudor.santec.gecamed.core.gui.GECAMedIconNames;
import lu.tudor.santec.gecamed.core.gui.GECAMedMessage;
import lu.tudor.santec.gecamed.core.gui.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.widgets.LimitTextField;
import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.i18n.Relocalizable;
import lu.tudor.santec.i18n.Translatrix;

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

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

//***************************************************************************
//* Class Definition and Members                                            *
//***************************************************************************

public class InvoiceTemplateDialog extends JDialog implements ActionListener,
															  ListSelectionListener,
															  Relocalizable
	{
	private TemplateListBox				m_Templates;
	
//	private GhostGlassPane				m_GhostPane;
	
	private TitledBorder				m_PropertiesBorder;
	private JPanel						m_PropertiesPanel;
	private JLabel						m_ShortcutLabel;
	private JTextField					m_Shortcut;
	private JLabel						m_DescriptionLabel;
	private JTextArea					m_Description;
	private JToggleButton				m_Visibility;
	
	private JDateChooser 				m_ActDateChooser;
//	private JCheckBox					m_SaveSuffixesBox;
	private JButton						m_NewTemplateButton;
	private JButton						m_SaveTemplateButton;
//	private JButton						m_UseTemplateButton;
	private JButton						m_DeleteTemplateButton;
	
	private JButton						m_CancelButton;
	private JButton						m_OkayButton;
	
	private InvoiceTemplateInterface	m_TemplateInterface;
	private NomenclatureInterface		m_NomenclatureInterface;
	
	private Set <TemplateRate> 			m_Rates;
	private InvoiceTemplate				m_Template;
	private boolean						m_Validated;
	
	private static Logger m_Logger = Logger.getLogger (InvoiceTemplateDialog.class.getName());
	
//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

	private static final long serialVersionUID = 1L;
	
	public static final int c_OpenDialog				= 0;
	public static final int c_SaveDialog				= 1;

	public static final String c_TemplateChanged	 	 = "TemplateChanged";
	public static final String c_TemplateOrderChanged	 = "TemplateOrderChanged";
	public static final String c_TemplateListChanged	 = "TemplateListChanged";
	
	public static final String c_Title					= "InvoiceTemplateDialog.Title";
	public static final String c_PropertiesBorder		= "InvoiceTemplateDialog.PropertiesBorder";
	public static final String c_ShortcutLabel			= "InvoiceTemplateDialog.ShortcutLabel";
	public static final String c_DescriptionLabel		= "InvoiceTemplateDialog.DescriptionLabel";
	public static final String c_SaveSuffixesBox		= "InvoiceTemplateDialog.SaveSuffixesButton";
	public static final String c_NewTemplateButton		= "InvoiceTemplateDialog.NewTemplateButton";
	public static final String c_SaveTemplateButton		= "InvoiceTemplateDialog.SaveTemplateButton";
	public static final String c_DeleteTemplateButton	= "InvoiceTemplateDialog.DeleteTemplateButton";
	public static final String c_NewTemplateTip			= "InvoiceTemplateDialog.NewTemplateTip";
	public static final String c_SaveTemplateTip		= "InvoiceTemplateDialog.SaveTemplateTip";
	public static final String c_DeleteTemplateTip		= "InvoiceTemplateDialog.DeleteTemplateTip";
	public static final String c_VisibilityTip			= "InvoiceTemplateDialog.VisibilityTip";
	
    private final static String c_Columns				= "3dlu,fill:max(100dlu;pref)," +
														  "3dlu,fill:max(50dlu;pref)," +
														  "3dlu,fill:max(50dlu;pref),10dlu";
	
	private final static String c_Rows					= "3dlu,fill:pref," +
														  "3dlu,fill:max(10dlu;pref)," +
														  "3dlu,fill:max(10dlu;pref)," +
														  "3dlu,fill:max(10dlu;pref)," +
														  "3dlu,fill:max(10dlu;pref)," +
														  "fill:pref:grow," +
														  "fill:max(10dlu;pref),3dlu";

	private final static String c_PropertiesColumns		= "3dlu,fill:pref," +
														  "3dlu,fill:pref:grow,3dlu";
	
	private final static String c_PropertiesRows		= "3dlu,fill:pref," +
														  "3dlu,fill:max(10dlu;pref)," +
														  "3dlu,fill:pref," +
														  "3dlu,fill:max(10dlu;pref)," +
														  "3dlu,fill:pref,3dlu";
	
	private final static String c_TemplateName			= "$TEMPLATE_NAME";
	
//***************************************************************************
//* Constructor                                                             *
//***************************************************************************

public 	InvoiceTemplateDialog (int p_DialogMode)
	{
	super (MainFrame.getInstance(),Translatrix.getTranslationString("InvoiceTemplateDialog.Title"),true);

	CellConstraints	l_Constraints;
	FormLayout		l_Layout;
	
	l_Constraints = new CellConstraints ();
	
//	m_GhostPane = new GhostGlassPane();
//    this.setGlassPane(m_GhostPane);
//    
	this.getContentPane().setBackground (GECAMedColors.c_GECAMedBackground);

//	this.setDefaultCloseOperation (JDialog.DO_NOTHING_ON_CLOSE);
	
	//=======================================================================
	//= Template Properties Panel
	//=======================================================================
	
	m_PropertiesBorder = new TitledBorder (Translatrix.getTranslationString(c_PropertiesBorder));
	m_PropertiesPanel  = new JPanel ();
	
	l_Layout = new FormLayout (c_PropertiesColumns, c_PropertiesRows);
	m_PropertiesPanel.setLayout (l_Layout);
	m_PropertiesPanel.setOpaque (false);
	m_PropertiesPanel.setBorder (m_PropertiesBorder);
	
	m_ShortcutLabel 	= new JLabel (Translatrix.getTranslationString(c_ShortcutLabel));
	m_Shortcut			= new LimitTextField(10);
	m_Shortcut.setEditable(false);
	m_DescriptionLabel	= new JLabel (Translatrix.getTranslationString(c_DescriptionLabel));
	m_Description		= new JTextArea (4,24);
	m_Description.setLineWrap(true);
	m_Description.setEditable(false);
	
	m_Visibility		= new JToggleButton ();
	m_Visibility.setIcon(BillingModule.getIconResource ("public.png"));
	m_Visibility.setSelectedIcon (BillingModule.getIconResource ("private.png"));
	m_Visibility.setToolTipText (Translatrix.getTranslationString(c_VisibilityTip));
	m_Visibility.setEnabled(false);
	
	m_PropertiesPanel.add (m_ShortcutLabel, 	l_Constraints.xywh(2, 2, 1, 1));
	m_PropertiesPanel.add (m_Shortcut,      	l_Constraints.xywh(2, 4, 1, 1));
	m_PropertiesPanel.add (m_DescriptionLabel,  l_Constraints.xywh(2, 6, 1, 1));
	m_PropertiesPanel.add (m_Description,  		l_Constraints.xywh(2, 8, 3, 1));
	m_PropertiesPanel.add (m_Visibility,		l_Constraints.xywh(2, 10, 1, 1));
	
	l_Layout = new FormLayout (c_Columns, c_Rows);
	this.setLayout (l_Layout);
	
	m_Templates = new TemplateListBox ();
	m_Templates.addListSelectionListener(this);
	m_Templates.addMouseListener(new MouseListener() {
		
		public void mouseReleased(MouseEvent e) {}
		public void mousePressed(MouseEvent e) {}
		public void mouseExited(MouseEvent e) {}
		public void mouseEntered(MouseEvent e) {}
		
		public void mouseClicked(MouseEvent e) {
			if (e.getClickCount() >= 2
					&& !m_SaveTemplateButton.isEnabled()) 
				{
				closeWithOKOption();
				}
		}
	});
//	m_Templates.setGhostPane(m_GhostPane);
	
//	m_SaveSuffixesBox = new JCheckBox(Translatrix.getTranslationString(c_SaveSuffixesBox));
//	m_SaveSuffixesBox.setEnabled(false);
	
	m_ActDateChooser = GECAMedGuiUtils.getDateChooser(false);
	
	m_NewTemplateButton   = new JButton (Translatrix.getTranslationString(c_NewTemplateButton));
	m_NewTemplateButton.setIcon(BillingModule.getIconResource ("new_template.png"));
	m_NewTemplateButton.setToolTipText (Translatrix.getTranslationString(c_NewTemplateTip));
	m_NewTemplateButton.setHorizontalAlignment(SwingConstants.LEFT);
	m_NewTemplateButton.setVerticalTextPosition(AbstractButton.CENTER);
	m_NewTemplateButton.setHorizontalTextPosition(AbstractButton.TRAILING); 
	m_NewTemplateButton.addActionListener(this);
	m_NewTemplateButton.setEnabled(false);
	
//	m_UseTemplateButton    = new JButton (Translatrix.getTranslationString(c_UseTemplateButton));
//	m_UseTemplateButton.setIcon(BillingModule.getIconResource ("open_template.png"));
//	m_UseTemplate.setToolTipText (Translatrix.getTranslationString(c_AddActTip));
//	m_UseTemplateButton.setHorizontalAlignment(SwingConstants.LEFT);
//	m_UseTemplateButton.setVerticalTextPosition(AbstractButton.CENTER);
//	m_UseTemplateButton.setHorizontalTextPosition(AbstractButton.TRAILING); 
	
	m_SaveTemplateButton   = new JButton (Translatrix.getTranslationString(c_SaveTemplateButton));
	m_SaveTemplateButton.setIcon(BillingModule.getIconResource ("save_template.png"));
	m_SaveTemplateButton.setToolTipText (Translatrix.getTranslationString(c_SaveTemplateTip));
	m_SaveTemplateButton.setHorizontalAlignment(SwingConstants.LEFT);
	m_SaveTemplateButton.setVerticalTextPosition(AbstractButton.CENTER);
	m_SaveTemplateButton.setHorizontalTextPosition(AbstractButton.TRAILING); 
	m_SaveTemplateButton.addActionListener(this);
	m_SaveTemplateButton.setEnabled(false);
	
	m_DeleteTemplateButton = new JButton (Translatrix.getTranslationString(c_DeleteTemplateButton));
	m_DeleteTemplateButton.setIcon(BillingModule.getIconResource ("delete_template.png"));
	m_DeleteTemplateButton.setToolTipText (Translatrix.getTranslationString(c_DeleteTemplateTip));
	m_DeleteTemplateButton.setHorizontalAlignment(SwingConstants.LEFT);
	m_DeleteTemplateButton.setVerticalTextPosition(AbstractButton.CENTER);
	m_DeleteTemplateButton.setHorizontalTextPosition(AbstractButton.TRAILING); 
	m_DeleteTemplateButton.addActionListener(this);
	
	m_OkayButton = new JButton (Translatrix.getTranslationString("core.ok"));
	m_OkayButton.setIcon(GECAMedModule.getSmallIcon(GECAMedIconNames.OK));
//	m_CloseButton.setHorizontalAlignment(SwingConstants.LEFT);
//	m_CloseButton.setVerticalTextPosition(AbstractButton.CENTER);
//	m_CloseButton.setHorizontalTextPosition(AbstractButton.TRAILING); 
	m_OkayButton.addActionListener(this);

	m_CancelButton = new JButton (Translatrix.getTranslationString("core.cancel"));
	m_CancelButton.setIcon(GECAMedModule.getSmallIcon(GECAMedIconNames.CANCEL));
	m_CancelButton.addActionListener (this);
//	m_CloseButton.setHorizontalAlignment(SwingConstants.LEFT);
//	m_CloseButton.setVerticalTextPosition(AbstractButton.CENTER);
//	m_CloseButton.setHorizontalTextPosition(AbstractButton.TRAILING); 
	m_CancelButton.addActionListener(this);

	
	this.add (m_Templates, 		 		l_Constraints.xywh(2, 2, 1, 10));
	
	this.add (m_PropertiesPanel, 		l_Constraints.xywh(4, 2, 3, 1));
	this.add (m_ActDateChooser, 		l_Constraints.xywh(4, 4, 3, 1));
	this.add (m_NewTemplateButton, 	 	l_Constraints.xywh(4, 6, 3, 1));
//	this.add (m_UseTemplateButton, 	 	l_Constraints.xywh(4, 8, 1, 1));
	this.add (m_SaveTemplateButton, 	l_Constraints.xywh(4, 8, 3, 1));
	this.add (m_DeleteTemplateButton,  	l_Constraints.xywh(4, 10, 3, 1));
	this.add (m_OkayButton,  	 		l_Constraints.xywh(4, 12, 1, 1));
	this.add (m_CancelButton,  	 		l_Constraints.xywh(6, 12, 1, 1));
	
	this.setComponentsEnabled(p_DialogMode);
	this.m_DeleteTemplateButton.setEnabled(m_Template != null);
	}

//---------------------------------------------------------------------------
//***************************************************************************
//* Class Primitives		                                                *
//***************************************************************************
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
//===========================================================================
//= Getters for required Interfaces
//===========================================================================
//---------------------------------------------------------------------------

private InvoiceTemplateInterface getTemplateInterface ()
	{
	if (m_TemplateInterface != null) return m_TemplateInterface;

	try {
		m_TemplateInterface = (InvoiceTemplateInterface) ManagerFactory.getRemote(InvoiceTemplateBean.class);
//		InitialContext l_Context = new InitialContext();
//		m_TemplateInterface = (InvoiceTemplateInterface) l_Context.lookup("InvoiceTemplateBean/remote");
//		l_Context.close();
		} 
	catch (Exception p_Exception) 
		{
		m_Logger.log(Level.ERROR, "Failed to lookup InvoiceTemplate Interface!",p_Exception);
		}

	return m_TemplateInterface;
	}

//---------------------------------------------------------------------------

private NomenclatureInterface getNomenclatureInterface ()
	{
	if (m_NomenclatureInterface != null) return m_NomenclatureInterface;

	try {
		m_NomenclatureInterface = (NomenclatureInterface) ManagerFactory.getRemote(NomenclatureBean.class);
//		InitialContext l_Context = new InitialContext();
//		m_NomenclatureInterface = (NomenclatureInterface) l_Context.lookup("NomenclatureBean/remote");
//		l_Context.close();
		} 
	catch (Exception p_Exception) 
		{
		m_Logger.log(Level.ERROR, "Failed to lookup Nomenclature Interface!",p_Exception);
		}

	return m_NomenclatureInterface;
	}

//---------------------------------------------------------------------------

private Set <TemplateRate> lookupRatesForActs (Set <Act> p_Acts)
	{
	NomenclatureInterface	l_NomenclatureInterface;
	Set <TemplateRate>		l_TemplateRates;
	Iterator <Act>			l_ActIterator;
	Act						l_Act;
	Rate					l_Rate;
	TemplateRate 			l_TemplateRate;
	boolean					l_Failed = false;
	
	if (p_Acts == null) return null;

	l_NomenclatureInterface = this.getNomenclatureInterface();
	if (l_NomenclatureInterface == null) return null;
	
	l_TemplateRates = new LinkedHashSet <TemplateRate> ();
	
	l_ActIterator = p_Acts.iterator();
	while (l_ActIterator.hasNext() && !l_Failed)
		{
		l_Act  = l_ActIterator.next();
		l_Rate = null;
		try	{
			l_Rate = l_NomenclatureInterface.getRateByCode(l_Act.getCode(), l_Act.getPerformedDate());
			}
		catch (Exception p_Exception) 
			{
			m_Logger.log(Level.ERROR, "Failed to lookup Nomenclature Interface!",p_Exception);
			l_Failed = true;
			}
		
		if (l_Rate != null) 
			{
			l_TemplateRate = new TemplateRate();
			l_TemplateRate.setRate(l_Rate);
			l_TemplateRate.setSuffixes(l_Act.getSuffixes());
			l_TemplateRate.setQuantity(l_Act.getQuantity());
			l_TemplateRates.add(l_TemplateRate);
			}
		}
	return l_TemplateRates;
	}

//---------------------------------------------------------------------------

private void populateTemplateListbox ()
	{
	InvoiceTemplateInterface		l_TemplateInterface;
	Collection <InvoiceTemplate>	l_Templates = null;
	
	l_TemplateInterface = this.getTemplateInterface();
	if (l_TemplateInterface == null) return;
	
	try	{
		l_Templates = l_TemplateInterface.getTemplatesByUser (BillingModule.getCurrentUser().getId());
		}
	catch (Exception p_Exception)
		{
		m_Logger.log(Level.ERROR, "Failed to fetch Invoice Templates!",p_Exception);
		}
	
	if (l_Templates != null) 
		{
		m_Templates.setTemplates (l_Templates);
		m_Templates.packColumns();
		m_Templates.packRows();
		}
	}

//---------------------------------------------------------------------------

private boolean updateSequenceNumbers ()
	{
	Collection <InvoiceTemplate>	l_Templates;
	Iterator <InvoiceTemplate>		l_TemplateIterator;
	InvoiceTemplate					l_Template;
	int								l_SequenceNumber = 0;
	boolean							l_OrderChanged = false;
	
	l_Templates = m_Templates.getTemplates();
	if (l_Templates == null) return false;
	
	l_TemplateIterator = l_Templates.iterator();
	while (l_TemplateIterator.hasNext())
		{
		l_Template = l_TemplateIterator.next();
		if (l_Template.getSequenceNumber() == null)
			{
			l_Template.setSequenceNumber(l_SequenceNumber);
			this.saveTemplate (l_Template);
			}	
		else if (!l_Template.getSequenceNumber().equals(l_SequenceNumber))
			{
			l_Template.setSequenceNumber(l_SequenceNumber);
			this.saveTemplate (l_Template);
			l_OrderChanged = true;
			}
		l_SequenceNumber++;
		}
	
	return l_OrderChanged;
	}

//---------------------------------------------------------------------------

public void setPropertiesFromRates ()
	{
	Iterator <TemplateRate>	l_RateIterator;
	Rate			l_Rate;
	
	if ((m_Rates != null) && (m_Rates.size() == 1))
		{
		l_RateIterator = m_Rates.iterator();
		l_Rate		   = l_RateIterator.next().getRate();
		
		m_Shortcut.setText(l_Rate.getCode());
		m_Description.setText(l_Rate.getLabel());
		}
	}

//---------------------------------------------------------------------------

private InvoiceTemplate updateTemplate (InvoiceTemplate	p_Template)
	{
	p_Template.setShortcut(m_Shortcut.getText());
	p_Template.setLabel(m_Description.getText());
	p_Template.setTemplateRates(m_Rates);
	
	if (m_Visibility.isSelected())
		p_Template.setUserId(BillingModule.getCurrentUser().getId());
	else
		p_Template.setUserId(null);

	if (!p_Template.isPersistent())
		{
		m_Templates.addTemplate (p_Template);
		m_Templates.selectTemplate (p_Template.getShortcut());
		m_Templates.revalidate();
		}
	
	return p_Template;
	}

//---------------------------------------------------------------------------

private InvoiceTemplate saveTemplate (InvoiceTemplate p_Template)
	{
	InvoiceTemplateInterface	l_TemplateInterface;
	
	l_TemplateInterface = this.getTemplateInterface();
	if (l_TemplateInterface == null) return p_Template;
	
	try	{
		p_Template = l_TemplateInterface.saveTemplate(p_Template);
		}
	catch (Exception p_Exception)
		{
		m_Logger.log(Level.ERROR, "Failed to save Invoice Template!",p_Exception);
		}
	return p_Template;
	}

//---------------------------------------------------------------------------

private void deleteTemplate (InvoiceTemplate p_Template)
	{
	InvoiceTemplateInterface	l_TemplateInterface;
	
	l_TemplateInterface = this.getTemplateInterface();
	if (l_TemplateInterface == null) return;
	
	try	{
		l_TemplateInterface.deleteTemplate(p_Template);
		}
	catch (Exception p_Exception)
		{
		m_Logger.log(Level.ERROR, "Failed to delete Invoice Template!",p_Exception);
		}
	}

//---------------------------------------------------------------------------

public void createNewTemplate ()
{
	m_Templates.selectTemplate(null);
	m_Template = null;
	m_Shortcut.setText("");
	m_Description.setText("");
	m_Visibility.setSelected(false);
}

//---------------------------------------------------------------------------

private void closeWithOKOption ()
	{
	GECAMedMessage	l_Message;
	
	m_Validated = true;
	if (this.updateSequenceNumbers())
		{
		l_Message = new GECAMedMessage(BillingModule.getInstance(), c_TemplateOrderChanged, null, null);		
		MainFrame.fireGECAMedMessage (l_Message);
		}
	this.setVisible(false);
	}

/**
 * @author ferring
 * Enable or disable the text components and buttons, which are used
 * to change the template, depending on which dialog is loaded - 
 * save template or use template.
 */
private void setComponentsEnabled (int p_DialogMode) 
	{
	m_SaveTemplateButton.setEnabled(p_DialogMode == c_SaveDialog);
	m_Visibility.setEnabled(p_DialogMode == c_SaveDialog);
	m_Shortcut.setEditable(p_DialogMode == c_SaveDialog);
	m_Description.setEditable(p_DialogMode == c_SaveDialog);
//	m_SaveSuffixesBox.setEnabled(p_DialogMode == c_SaveDialog);
	m_ActDateChooser.setEnabled(p_DialogMode == c_OpenDialog);
	m_NewTemplateButton.setEnabled(p_DialogMode == c_SaveDialog);
	m_OkayButton.setEnabled(p_DialogMode == c_OpenDialog);
	}


//---------------------------------------------------------------------------
//***************************************************************************
//* Class Body				                                                *
//***************************************************************************
//---------------------------------------------------------------------------	

public void setVisible (boolean p_ShowIt)
	{
	if (p_ShowIt) 
		{
		this.populateTemplateListbox();
		if (m_Templates.getSelectedTemplate() == null) 
			this.setPropertiesFromRates ();
	
		m_Templates.packColumns();
		m_Templates.packRows();
		
		m_Validated = false;
		}
		
	super.setVisible (p_ShowIt);
	}

//---------------------------------------------------------------------------	

public void setRatesForTemplate (Set <TemplateRate> p_Rates)
	{
	m_Rates = p_Rates;
	}

//---------------------------------------------------------------------------	

public void setActsForTemplate (Set <Act> p_Acts)
	{
	m_Rates = this.lookupRatesForActs(p_Acts);
	}

//---------------------------------------------------------------------------	

public Set <TemplateRate> getRatesFromTemplate ()
	{
	if (m_Template != null) 
		 return m_Template.getTemplateRates();
	else return null;
	}

//---------------------------------------------------------------------------

public Date getActDate ()
	{
	return m_ActDateChooser.getDate();
	}

//---------------------------------------------------------------------------

public void setActDate (Date date)
	{
	m_ActDateChooser.setDate(date);
	}

//---------------------------------------------------------------------------	

public boolean wasValidated ()
	{
	return m_Validated;
	}

//---------------------------------------------------------------------------	

public void relocalize() 
	{
	}

//---------------------------------------------------------------------------	

public void actionPerformed (ActionEvent p_Event) 
	{
	GECAMedMessage	l_Message;
	int				l_Row;
	int				l_ButtonOption;
	
	if (p_Event.getSource().equals(m_NewTemplateButton))
		{
		this.createNewTemplate ();		
		}
	else if (p_Event.getSource().equals(m_SaveTemplateButton))
		{
		if (m_Template == null) m_Template = new InvoiceTemplate ();
		else
			{
			// Ask, if user wants to override this template. Stop, if user cancels.
			l_ButtonOption = JOptionPane.showConfirmDialog(this, 
					Translatrix.getTranslationString("InvoiceTemplateDialog.OverwritingTemplateWarningMessage")
					.replace(c_TemplateName, m_Template.getShortcut()), 
					Translatrix.getTranslationString("InvoiceTemplateDialog.OverwritingTemplateWarningTitle"), 
					JOptionPane.OK_CANCEL_OPTION, 
					JOptionPane.WARNING_MESSAGE);
			
			if (l_ButtonOption != JOptionPane.OK_OPTION) return;
			}
		
		m_Template = this.updateTemplate (m_Template);
		m_Template = this.saveTemplate   (m_Template);
		
		l_Row = m_Templates.findTemplate(m_Template.getShortcut());
		if (l_Row >= 0) m_Templates.setTemplateAt(m_Template, l_Row);
		
		l_Message = new GECAMedMessage(BillingModule.getInstance(), c_TemplateChanged, null, m_Template.getId());		
		MainFrame.fireGECAMedMessage (l_Message);
		}
	else if (p_Event.getSource().equals(m_DeleteTemplateButton))
		{
		if (m_Template != null) 
			{
			l_ButtonOption = JOptionPane.showConfirmDialog(this, 
					Translatrix.getTranslationString("InvoiceTemplateDialog.DeleteTemplateWarningMessage")
					.replace(c_TemplateName, m_Template.getShortcut()), 
					Translatrix.getTranslationString("InvoiceTemplateDialog.DeleteTemplateWarningTitle"), 
					JOptionPane.OK_CANCEL_OPTION, 
					JOptionPane.WARNING_MESSAGE);
			
			if (l_ButtonOption != JOptionPane.OK_OPTION) return;
			
			this.deleteTemplate(m_Template);
			m_Templates.removeSelectedTemplate();
			l_Message = new GECAMedMessage(BillingModule.getInstance(), c_TemplateListChanged, null, null);		
			MainFrame.fireGECAMedMessage (l_Message);
			}
		m_Template = null;
		}
	else if (p_Event.getSource().equals(m_CancelButton))
		{
		this.setVisible(false);
		}
	else if (p_Event.getSource().equals(m_OkayButton))
		{
		closeWithOKOption();
		}
	}

//---------------------------------------------------------------------------	

public void valueChanged(ListSelectionEvent p_Event) 
	{
	InvoiceTemplate	l_Template; 
	
	if (!p_Event.getValueIsAdjusting())
    	{    
		l_Template = m_Templates.getSelectedTemplate();
		if (l_Template == null) return;
		
		m_Template = l_Template;
		m_Shortcut.setText(m_Template.getShortcut());
		m_Description.setText (m_Template.getLabel());
		m_Visibility.setSelected((l_Template.getUserId() != null));
    	}
	
	m_DeleteTemplateButton.setEnabled(m_Template != null);
	}

//---------------------------------------------------------------------------	
//***************************************************************************
//* End of Class				                            				*
//***************************************************************************
//---------------------------------------------------------------------------	
}
