/*******************************************************************************
 * 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.invoice;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.text.Caret;

import lu.tudor.santec.gecamed.billing.ejb.entity.beans.Invoice;
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.GECAMedModule;
import lu.tudor.santec.gecamed.core.gui.MainFrame;
import lu.tudor.santec.gecamed.core.gui.utils.DefaultComboBoxRenderer;
import lu.tudor.santec.gecamed.core.gui.utils.GECAMedGuiUtils;
import lu.tudor.santec.gecamed.core.gui.widgets.GECAMedBaseDialog;
import lu.tudor.santec.gecamed.core.gui.widgets.NumberField;
import lu.tudor.santec.gecamed.core.gui.widgets.PhysicianListModel;
import lu.tudor.santec.gecamed.core.gui.widgets.ReloadListener;
import lu.tudor.santec.gecamed.office.ejb.entity.beans.Physician;
import lu.tudor.santec.gecamed.office.gui.PhysicianComboBoxRenderer;
import lu.tudor.santec.gecamed.patient.ejb.entity.beans.Insurance;
import lu.tudor.santec.gecamed.patient.gui.InsuranceComboBoxRenderer;
import lu.tudor.santec.i18n.Relocalizable;
import lu.tudor.santec.i18n.Translatrix;

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

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

public class InvoicePropertiesPanel extends JPanel implements PropertyChangeListener,
															  ActionListener,
															  ItemListener,
															  Relocalizable,
															  FocusListener
	{
	private static final long serialVersionUID = 1L;
	
	private TitledBorder		m_Border;
	
	private JLabel				m_InvoiceNumberLabel;
	private JLabel				m_InvoiceDateLabel;
	private JLabel				m_PhysicianLabel;
	private JLabel				m_HealthInsuranceLabel;
	private JLabel				m_ThirdPartyPayerLabel;
	
	private NumberField			m_InvoiceNumber;
	private JButton				m_InvoiceSearchButton;
	private JDateChooser 		m_InvoiceDate;
	@SuppressWarnings("rawtypes")
	private JComboBox  			m_Physician;
	@SuppressWarnings("rawtypes")
	private JComboBox  			m_HealthInsurance;
//	private JComboBox  			m_ThirdPartyPayer;
	
//	private int					m_Default3ppIndex		= -1;
	private int					m_DefaultInsuranceIndex	= -1;
	
	private Vector<Insurance>	m_HealthInsurances;
	private Vector<Insurance>	m_ThirdPartyPayers;
	private Insurance 			m_DefaultInsurance;
	private Insurance 			m_CNSInsurance;
	
	private SimpleDateFormat	m_DateFormat;
	
	private JTextField			m_InvoiceDateField;
	private JTextField			m_PhysicianField;
	private JTextField			m_HealthInsuranceField;
//	private JTextField			m_ThirdPartyPayerField;
	
	private JCheckBox			m_FilterByPhysicianBox;
	
	private JCheckBox			m_IsThirdParty;

	private boolean m_wasTTP = true;

//	private Invoice m_Invoice;
	
	private boolean listenersActive = true;

private Date dueDate;

private DueDateDialog dueDateDialog;

	
//***************************************************************************
//* Class Constants                                                         *
//***************************************************************************

	public final static String  c_InvoiceNumber		= "InvoicePropertiesPanel.InvoiceNumber";
	public final static String  c_InvoiceDate 		= "InvoicePropertiesPanel.InvoiceDate";
	public final static String  c_Physician   		= "InvoicePropertiesPanel.Physician";
	public final static String  c_HealthInsurance   = "InvoicePropertiesPanel.HealthInsurance";
	public final static String  c_ThirdPartyPayer   = "InvoicePropertiesPanel.ThirdPartyPayer";
	
	private final static String c_Columns	= "fill:max(60dlu;pref),3dlu," +
											  "fill:max(60dlu;pref),3dlu," +
										 	  "fill:max(60dlu;pref),3dlu," +
										 	  "fill:max(50dlu;pref),3dlu," +
										 	  "fill:max(50dlu;pref)";
										 
	private final static String c_Rows		= "fill:pref,3dlu,fill:pref";
	
//***************************************************************************
//* Constructor(s)                                                          *
//***************************************************************************

@SuppressWarnings({ "unchecked", "rawtypes" })
public InvoicePropertiesPanel ()
    {	
	CellConstraints		l_Constraints;
    FormLayout			l_Layout;
    Color				l_DefaultColor; 
    JPanel				l_PhysicianLabelPanel;
    JPanel				l_InvoiceNumberPanel;
    
    l_Constraints  = new CellConstraints();
     
    l_Layout = new FormLayout(c_Columns, c_Rows);
    this.setLayout(l_Layout);
    this.setOpaque(false);
    
	m_Border = new TitledBorder (Translatrix.getTranslationString("InvoicePropertiesPanel.Title"));
    this.setBorder (m_Border);
    
    dueDateDialog = new DueDateDialog();
    
    m_InvoiceNumberLabel		= new JLabel ();
    m_InvoiceNumberLabel.setForeground (GECAMedColors.c_LabelColor);
    
    m_InvoiceDateLabel			= new JLabel ();
    m_InvoiceDateLabel.setForeground (GECAMedColors.c_LabelColor);
    
    m_PhysicianLabel			= new JLabel ();
    m_PhysicianLabel.setForeground (GECAMedColors.c_LabelColor);
    
    /**
     * @author ferring
     * Add a check box, to set whether the invoice panel shall be filtered by the current 
     * physician or not.
     */
    m_FilterByPhysicianBox 		= new JCheckBox(new AbstractAction(
    		Translatrix.getTranslationString("InvoicePropertiesPanel.AllPhysicians")) {
		private static final long serialVersionUID = 1L;
		
		public void actionPerformed(ActionEvent e) 
			{
			boolean l_Selected 	= ((JCheckBox)e.getSource()).isSelected();
			filterInvoicesByPhysician(!l_Selected);
			}
	});
    m_FilterByPhysicianBox.setToolTipText(
    		Translatrix.getTranslationString("InvoicePropertiesPanel.AllPhysiciansToolTip"));
    m_FilterByPhysicianBox.setForeground (GECAMedColors.c_LabelColor);
    m_FilterByPhysicianBox.setOpaque(false);
    m_FilterByPhysicianBox.setSelected(!InvoiceListingPanel.getDefaultFilterByPhysician());
    this.setFilterByPhysicianBoxVisible(true);
    
    l_PhysicianLabelPanel		= new JPanel(new BorderLayout());
    l_PhysicianLabelPanel.setOpaque(false);
    l_PhysicianLabelPanel.add(m_PhysicianLabel, BorderLayout.CENTER);
    l_PhysicianLabelPanel.add(m_FilterByPhysicianBox, BorderLayout.EAST);
    
    
    
    m_HealthInsuranceLabel		= new JLabel ();
    m_HealthInsuranceLabel.setForeground (GECAMedColors.c_LabelColor);
    
    m_ThirdPartyPayerLabel		= new JLabel ();
    m_ThirdPartyPayerLabel.setForeground (GECAMedColors.c_LabelColor);
      
    
    l_DefaultColor = (Color) UIManager.getDefaults().get("TextField.inactiveBackground");   
    UIManager.getDefaults().put("TextField.inactiveBackground", Color.WHITE );
    
//	m_InvoiceNumber = new JFormattedTextField (new InvoiceNumberFormatter(InvoiceNumberFormatter.c_ShortFormat));
    m_InvoiceNumber = new NumberField(20, false);
	m_InvoiceNumber.addActionListener(this);
	m_InvoiceNumber.addFocusListener(this);
	
	m_InvoiceSearchButton = new JButton();
	m_InvoiceSearchButton.addActionListener(this);
	m_InvoiceSearchButton.setIcon(GECAMedModule.getScaledIcon(GECAMedIconNames.SEARCH, 18));
	m_InvoiceSearchButton.setPreferredSize(new Dimension(18, 18));
	
	l_InvoiceNumberPanel	= new JPanel(new BorderLayout());
	l_InvoiceNumberPanel.add(m_InvoiceNumber, BorderLayout.CENTER);
	l_InvoiceNumberPanel.add(m_InvoiceSearchButton, BorderLayout.EAST);
	l_InvoiceNumberPanel.setOpaque(false);
    
    m_InvoiceDate = GECAMedGuiUtils.getDateChooser(false); 
    m_InvoiceDate.addPropertyChangeListener(this);
    m_InvoiceDateField		= new JTextField ();
    m_InvoiceDateField.setEditable(false);
    
    ReloadListener reloadListener = new ReloadListener()
	{
    	private Object p;
    	
    	public void prepareReload ()
    	{
    		if (m_Physician != null)
    			p = m_Physician.getSelectedItem();
    	}
    	
    	
		public void reloaded ()
		{
			if (m_Physician != null)
				m_Physician.setSelectedItem(p);
		}
	};
    m_Physician	   	 		= new JComboBox (new PhysicianListModel(reloadListener));
    m_Physician.setRenderer(new PhysicianComboBoxRenderer ());
    m_Physician.addItemListener (this);
    m_Physician.setEnabled (BillingModule.userHasPermission (MainFrame.PERMISSIONS_CORE, MainFrame.PERMISSION_CHANGE_PHYSICIAN));
    
    m_PhysicianField		= new JTextField ();
    m_PhysicianField.setEditable(false);
    
    m_HealthInsurance 		= new JComboBox ();
    m_HealthInsurance.setRenderer(new InsuranceComboBoxRenderer(true));
    m_HealthInsurance.addItemListener(this);
    m_HealthInsurance.addActionListener(this);
    m_HealthInsuranceField	= new JTextField ();
    m_HealthInsuranceField.setEditable(false);
    
//    m_ThirdPartyPayer		= new JComboBox ();
//    m_ThirdPartyPayer.setRenderer(new InsuranceComboBoxRenderer(true));
//    m_ThirdPartyPayer.addItemListener(this);
//    m_ThirdPartyPayerField	= new JTextField ();
//    m_ThirdPartyPayerField.setEditable(false);
    
    m_IsThirdParty = new JCheckBox();
    m_IsThirdParty.setOpaque(false);
    m_IsThirdParty.addActionListener(this);
    
    UIManager.getDefaults().put("TextField.inactiveBackground", l_DefaultColor );
    
    this.relocalize ();
    
    this.add (m_InvoiceNumberLabel, 	l_Constraints.xywh(1, 1, 1, 1));
    this.add (m_InvoiceDateLabel, 		l_Constraints.xywh(3, 1, 1, 1));
//    this.add (m_PhysicianLabel, 		l_Constraints.xywh(5, 1, 1, 1));
    this.add (l_PhysicianLabelPanel, 	l_Constraints.xywh(5, 1, 1, 1));
//    this.add (m_HealthInsuranceLabel, 	l_Constraints.xywh(7, 1, 1, 1));
//    this.add (m_ThirdPartyPayerLabel, 	l_Constraints.xywh(9, 1, 1, 1));
    this.add (m_ThirdPartyPayerLabel, 	l_Constraints.xywh(7, 1, 1, 1)); 
    this.add (m_HealthInsuranceLabel, 	l_Constraints.xywh(9, 1, 1, 1));
    
    this.add (l_InvoiceNumberPanel, 	l_Constraints.xywh(1, 3, 1, 1));
    this.add (m_InvoiceDate, 			l_Constraints.xywh(3, 3, 1, 1));
    this.add (m_Physician, 				l_Constraints.xywh(5, 3, 1, 1));
//    this.add (m_HealthInsurance, 		l_Constraints.xywh(7, 3, 1, 1));
//    this.add (m_ThirdPartyPayer, 		l_Constraints.xywh(9, 3, 1, 1));
    
    this.add (m_IsThirdParty, 			l_Constraints.xywh(7, 3, 1, 1));
    this.add (m_HealthInsurance, 		l_Constraints.xywh(9, 3, 1, 1));
    }

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

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

//public void populatePhysicians (Collection <Physician> p_Physicians)
//	{
//	Iterator <Physician>	l_PhysicianIterator;
//	
//	if (p_Physicians == null) return;
//	
//	l_PhysicianIterator = p_Physicians.iterator();
//	while (l_PhysicianIterator.hasNext())
//		{
//		m_Physician.addItem (l_PhysicianIterator.next());
//		}
//	}

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

public void populateInsurances (Collection <Insurance> p_Insurances)
	{
	Iterator <Insurance> l_InsuranceIterator;
	Insurance			 l_Insurance;
//	Insurance            l_DefaultInsurance = null;
	Integer              l_Zero = Integer.valueOf(0);
	
	if (p_Insurances == null) return;
	
	m_HealthInsurances = new Vector<Insurance>();
	m_ThirdPartyPayers = new Vector<Insurance>();
	
	l_InsuranceIterator = p_Insurances.iterator();
	while (l_InsuranceIterator.hasNext())
		{
		l_Insurance = l_InsuranceIterator.next();
		
		if (l_Insurance.getPrimary()) m_HealthInsurances.add (l_Insurance);
		if (l_Insurance.getThirdParty()) m_ThirdPartyPayers.add (l_Insurance);
		
//		if (l_Insurance.getPrimary()) m_HealthInsurance.addItem (l_Insurance);
//		if (l_Insurance.getThirdParty()) m_ThirdPartyPayer.addItem (l_Insurance);
		
		if (m_DefaultInsurance == null 	&& l_Zero.equals(l_Insurance.getId()))
			m_DefaultInsurance = l_Insurance;
		
		if (m_CNSInsurance == null 	&& Insurance.INSURANCE_CNS.equals(l_Insurance.getAcronym()))
			m_CNSInsurance = l_Insurance;
	
	}
	
	// set default indices
	if (m_DefaultInsurance != null)
		{
		m_HealthInsurance.setSelectedItem(m_DefaultInsurance);
		m_DefaultInsuranceIndex	= m_HealthInsurance.getSelectedIndex();
		}
	if (m_DefaultInsuranceIndex < 0)
		m_DefaultInsuranceIndex = 0;
	
//	if (l_DefaultInsurance != null)
//		{
//		m_ThirdPartyPayer.setSelectedItem(l_DefaultInsurance);
//		m_Default3ppIndex	= m_ThirdPartyPayer.getSelectedIndex();
//		}
//	if (m_Default3ppIndex < 0)
//		m_Default3ppIndex = 0;
	
	m_IsThirdParty.setSelected(false);
	reloadInsuranceBox();
}

//---------------------------------------------------------------------------
/**
 * Method is part of the Relocalizable interface. The method does everything
 * required to reflect changes of active Locale
 */
//---------------------------------------------------------------------------

public void relocalize() 
	{

	String dateString = GECAMedGuiUtils.getDateFormatString(false); 
	  	
	m_DateFormat = new SimpleDateFormat (dateString);   

	if (m_Border != null)
	    m_Border.setTitle (Translatrix.getTranslationString("InvoicePropertiesPanel.Title"));

	if (m_InvoiceDate != null) 
		{
		m_InvoiceDate.setLocale (Translatrix.getLocale());
		m_InvoiceDate.setDateFormatString(dateString);   
		m_InvoiceDate.getDateEditor().setLocale (Translatrix.getLocale());
		m_InvoiceDate.getDateEditor().setDateFormatString(dateString);
		}
	
	if (m_InvoiceNumberLabel!=null) 		 
		m_InvoiceNumberLabel.setText (Translatrix.getTranslationString("InvoicePropertiesPanel.InvoiceNumberLabel"));
	
	if (m_InvoiceDateLabel!=null) 		 
		m_InvoiceDateLabel.setText (Translatrix.getTranslationString("InvoicePropertiesPanel.InvoiceDateLabel"));
	
	if (m_PhysicianLabel!=null)
		m_PhysicianLabel.setText (Translatrix.getTranslationString("InvoicePropertiesPanel.PhysicianLabel"));
	
	if (m_HealthInsuranceLabel!=null)
		m_HealthInsuranceLabel.setText (Translatrix.getTranslationString("InvoicePropertiesPanel.HealthInsuranceLabel"));
	
	if (m_ThirdPartyPayerLabel!=null)
		m_ThirdPartyPayerLabel.setText ("");
		
	
	if (m_IsThirdParty!=null)
		m_IsThirdParty.setText (Translatrix.getTranslationString("InvoicePropertiesPanel.ThirdPartyLabel"));
	
	}

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

private void swapComponents (JComponent p_Out, JComponent p_In, CellConstraints p_Constraints)
	{
	if (p_Out.getParent() == this)
		{
		this.remove (p_Out);
		this.add( p_In,p_Constraints);
		//p_In.repaint();
		}
	}

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

/**
 * @author ferring
 * Called, if the filter option has changed.
 * 
 * @param p_Filter
 */
private void filterInvoicesByPhysician(boolean p_Filter)
	{
	BillingModule l_Module = BillingModule.getInstance();
	
	l_Module.setInvoicePanelFilter(p_Filter);
	
	l_Module.reloadInvoices();
	}

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

public void propertyChange (PropertyChangeEvent p_ChangeEvent) 
	{
	
	if (listenersActive && (p_ChangeEvent.getSource() == m_InvoiceDate) && ("date".equals(p_ChangeEvent.getPropertyName())) )
		{

		if (!BillingModule.getInstance().checkActDate(m_InvoiceDate.getDate())) {
			try {
				listenersActive = false;
				m_InvoiceDate.setDate((Date) p_ChangeEvent.getOldValue());
				listenersActive = true;
			} catch (Exception e) {}
		}
		
//		System.out.println("----------------------------------");
//		System.out.println(m_InvoiceDate.getDate());
//		System.out.println(this.dueDate);
		// TODO ask to change due date after changing invoice date
		if (this.dueDate != null) {
			
			int retVal = dueDateDialog.showDueDateDialog(m_InvoiceDate.getDate(), Invoice.getDueDate(m_InvoiceDate.getDate()));
			if (retVal == GECAMedBaseDialog.OK_OPTION) {
				this.dueDate = dueDateDialog.getDueDate();
			}
			
		}
		
		this.firePropertyChange (c_InvoiceDate, p_ChangeEvent.getOldValue(), p_ChangeEvent.getNewValue());
		
//		BillingModule 	l_Module;
//		l_Module 	= BillingModule.getInstance();
//		l_Module.checkForDuplicateInovicesAtDate(BillingModule.getCurrentPatient(), 
//				(Physician)m_Physician.getSelectedItem(), m_InvoiceDate.getDate(), true);
		}
	}

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

public void itemStateChanged (ItemEvent p_ChangeEvent) 
	{
	if (! listenersActive ) return;
	
	if (p_ChangeEvent.getSource() == m_Physician)
		{
		this.firePropertyChange (c_Physician, null, p_ChangeEvent.getItem());
		return;
		}
	
	if (p_ChangeEvent.getSource() == m_HealthInsurance)
		{
		this.firePropertyChange (c_HealthInsurance, null, p_ChangeEvent.getItem());
		this.firePropertyChange (c_ThirdPartyPayer, null, getThirdPartyPayer());	
		return;
		}
	
//	if (p_ChangeEvent.getSource() == m_ThirdPartyPayer)
//		{
//		this.firePropertyChange (c_ThirdPartyPayer, null, p_ChangeEvent.getItem());
//		}
	}


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

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

@SuppressWarnings("unchecked")
public void reloadInsuranceBox () {
	
//	System.out.println("checkreloadBox");
	if (m_IsThirdParty.isSelected() == m_wasTTP) {
		return;
	}
	
//	System.out.println("\treloadbox");
	
	listenersActive = false;
	
	m_HealthInsurance.removeAllItems();
	
	if (m_IsThirdParty.isSelected()) {
		for (Insurance insurance : m_ThirdPartyPayers) {
			m_HealthInsurance.addItem(insurance);
		}
	} else {
		for (Insurance insurance : m_HealthInsurances) {
			m_HealthInsurance.addItem(insurance);
		}
	}
	
	m_wasTTP = m_IsThirdParty.isSelected();
	
	listenersActive = true;
	
}

public void setEnabled (boolean p_EnableIt)
	{
	CellConstraints		l_Constraints;
	
    l_Constraints  = new CellConstraints();
	
	if (p_EnableIt)
		{
		this.swapComponents(m_InvoiceDateField,			m_InvoiceDate,			l_Constraints.xywh(3, 3, 1, 1));
		this.swapComponents(m_PhysicianField,  			m_Physician,  			l_Constraints.xywh(5, 3, 1, 1));
		this.swapComponents(m_HealthInsuranceField,  	m_HealthInsurance,  	l_Constraints.xywh(9, 3, 1, 1));
		}
	else
		{
		this.swapComponents(m_InvoiceDate,				m_InvoiceDateField,		l_Constraints.xywh(3, 3, 1, 1));
		this.swapComponents(m_Physician,  				m_PhysicianField,  		l_Constraints.xywh(5, 3, 1, 1));
		this.swapComponents(m_HealthInsurance,  		m_HealthInsuranceField, l_Constraints.xywh(9, 3, 1, 1));
		}
	
	m_IsThirdParty.setEnabled(p_EnableIt);
	this.repaint();
	}

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

public void setInvoice (Invoice p_Invoice)
	{
	if (p_Invoice == null) return;
	
	listenersActive=false;
	
	this.dueDate 			= p_Invoice.getDueDate();
	setInvoiceNumber		(p_Invoice.getId());
	setInvoiceDate   		(p_Invoice.getInvoiceDate());
	setPhysician     		(p_Invoice.getPhysician());
//	setThirdPartyPayer		(p_Invoice.getThirdPartyPayer());
//	setHealthInsurance   	(p_Invoice.getHealthInsurance());
	
	setInsurances(p_Invoice);
	
	listenersActive=true;

	}

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

public boolean updateInvoice (Invoice p_Invoice)
	{
	boolean l_InvoiceModified = false;
	
	if (p_Invoice == null) return false;
	
	//-- Invoice Date --------------------------------------------------------
	
	if (!this.getInvoiceDate().equals (p_Invoice.getInvoiceDate()))
		{
		p_Invoice.setInvoiceDate (this.getInvoiceDate());
		l_InvoiceModified = true;
		}
	
	if (this.dueDate != null && !this.dueDate.equals (p_Invoice.getDueDate()))
		{
		p_Invoice.setDueDate(this.dueDate);
		l_InvoiceModified = true;
		}
	
	//-- Physician -----------------------------------------------------------
	
	if (!this.getPhysician().equals (p_Invoice.getPhysician()))
		{
		p_Invoice.setPhysician (this.getPhysician());
		l_InvoiceModified = true;
		}
	
	//-- Health Insurance ----------------------------------------------------
	
	if (!this.getHealthInsurance().equals (p_Invoice.getHealthInsurance()))
		{
		p_Invoice.setHealthInsurance (this.getHealthInsurance());
		p_Invoice.setMajoration(this.getHealthInsurance().getMajoration());
		l_InvoiceModified = true;
		}
	
	//-- Third Party Payer ---------------------------------------------------
	p_Invoice.setThirdPartyPayer (this.getThirdPartyPayer());			

			
	return l_InvoiceModified;
	}

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

public void reset ()
	{
	listenersActive = false;
	this.resetInvoiceNumber();
	this.resetInvoiceDate();
	this.resetPhysician();
	this.resetInsurances();
	listenersActive = true;
	}

private void resetInsurances() {
	m_IsThirdParty.setSelected(false);
	reloadInsuranceBox();
	m_HealthInsurance.setSelectedItem(m_CNSInsurance);
	
	DefaultComboBoxRenderer l_Renderer = (DefaultComboBoxRenderer) m_HealthInsurance.getRenderer();
	m_HealthInsuranceField.setText(l_Renderer.renderObject(m_HealthInsurance.getSelectedItem()));
}

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

public Integer getInvoiceNumber ()
	{
	String	l_Value;
	Integer	l_InvoiceNumber;
			
	l_Value = (String) m_InvoiceNumber.getText();
	if (InvoiceNumberFormatter.c_EmptyFieldShort.equals(l_Value))
		 l_InvoiceNumber = Integer.valueOf(0);
	else try 
			{
			l_InvoiceNumber = Integer.parseInt(l_Value);
			}
		catch (NumberFormatException p_Exception)
			{
			l_InvoiceNumber = Integer.valueOf (0);
			}
	return l_InvoiceNumber;
	}

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

private void setInvoiceNumber (Integer p_InvoiceId)
	{
	if (p_InvoiceId != null) 
		m_InvoiceNumber.setText(p_InvoiceId.toString());
	else 
		resetInvoiceNumber();
	}

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

private void resetInvoiceNumber ()
	{
//	m_InvoiceNumber.setValue (InvoiceNumberFormatter.c_EmptyFieldShort);
	m_InvoiceNumber.setText("");	
	}

//---------------------------------------------------------------------------
/**
 * Returns the currently selected Invoice Date
 */
//---------------------------------------------------------------------------

public Date getInvoiceDate ()
	{
	Date 	l_Date;
	
	l_Date = m_InvoiceDate.getDate();
	return l_Date;
	}

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

private void setInvoiceDate (Date p_InvoiceDate)
	{
	
	listenersActive=false;
	
	if (p_InvoiceDate != null) 
		{	
		m_InvoiceDate.setDate (p_InvoiceDate);
		m_InvoiceDateField.setText(m_DateFormat.format (p_InvoiceDate));
		}
	else this.resetInvoiceDate();
	
	listenersActive=true;
	}

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

private void resetInvoiceDate ()
	{
	m_InvoiceDate.setDate (new Date ());
	m_InvoiceDateField.setText(m_DateFormat.format (new Date()));	
	}

//---------------------------------------------------------------------------
/**
 * Returns the currently selected Healthinsurance
 */
//---------------------------------------------------------------------------

public Physician getPhysician ()
	{
	Physician	l_Physician;
	
	l_Physician = (Physician) m_Physician.getSelectedItem();
	return l_Physician;
	}

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

private void setPhysician (Physician p_Physician)
	{
	DefaultComboBoxRenderer	l_Renderer;

	if (p_Physician != null) 
		{
		m_Physician.setSelectedItem(p_Physician);
		l_Renderer = (DefaultComboBoxRenderer) m_Physician.getRenderer();
		m_PhysicianField.setText(l_Renderer.renderObject(p_Physician));
		}
	else resetPhysician ();	
	}

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

public void resetPhysician ()
	{
	if (m_Physician.getItemCount() > 0) m_Physician.setSelectedIndex(0);
	m_PhysicianField.setText ("");
	}

//---------------------------------------------------------------------------
/**
 * Returns the currently selected Healthinsurance
 */
//---------------------------------------------------------------------------

public Insurance getHealthInsurance ()
	{
	Insurance	l_HealthInsurance;
	l_HealthInsurance = (Insurance) m_HealthInsurance.getSelectedItem();
	return l_HealthInsurance;
	}

//---------------------------------------------------------------------------
//private Insurance m_DisbandedHealthInsurance;
//private Insurance m_DisbandedThirdPartyPayer;
//
//public void setHealthInsurance (Insurance p_HealthInsurance)
//	{
//	DefaultComboBoxRenderer	l_Renderer;
//	
//	if (m_DisbandedHealthInsurance != null)
//		{
//		m_HealthInsurance.removeItem(m_DisbandedHealthInsurance);
//		m_DisbandedHealthInsurance = null;
//		}
//	
//	if (p_HealthInsurance != null) 
//		{
//		if (p_HealthInsurance.getDisbanded())
//			{
//			m_DisbandedHealthInsurance = p_HealthInsurance;
//			m_HealthInsurance.addItem(m_DisbandedHealthInsurance);
//			}
//		m_HealthInsurance.setSelectedItem(p_HealthInsurance);
//		l_Renderer = (DefaultComboBoxRenderer) m_HealthInsurance.getRenderer();
//		m_HealthInsuranceField.setText(l_Renderer.renderObject(p_HealthInsurance));
//		}
//	else resetHealthInsurance ();
//	}

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

//public void resetHealthInsurance ()
//	{
//	if (m_HealthInsurance.getItemCount() > m_DefaultInsuranceIndex)
//		m_HealthInsurance.setSelectedIndex(m_DefaultInsuranceIndex);
//	else if (m_HealthInsurance.getItemCount() > 0)
//		m_HealthInsurance.setSelectedIndex(0);
//	m_HealthInsuranceField.setText ("");
//	}

//---------------------------------------------------------------------------
/**
 * Returns the currently selected third party paying insurance
 */
//---------------------------------------------------------------------------

public Insurance getThirdPartyPayer ()
	{
	Insurance	l_ThirdPartyPayer;
	
//	l_ThirdPartyPayer = (Insurance) m_ThirdPartyPayer.getSelectedItem();
	
	if (m_IsThirdParty.isSelected()) {
		l_ThirdPartyPayer = (Insurance) m_HealthInsurance.getSelectedItem();
	} else {
		l_ThirdPartyPayer = null; 
	}
	return l_ThirdPartyPayer;
	}

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

//public void setThirdPartyPayer (Insurance p_ThirdPartyPayer)
//	{
//	DefaultComboBoxRenderer	l_Renderer;
//	
//	if (m_DisbandedThirdPartyPayer != null)
//		{
//		m_ThirdPartyPayer.removeItem(m_DisbandedThirdPartyPayer);
//		m_DisbandedThirdPartyPayer = null;
//		}
//
//	if (p_ThirdPartyPayer != null) 
//		{
//		if (p_ThirdPartyPayer.getDisbanded())
//			{
//			m_DisbandedThirdPartyPayer = p_ThirdPartyPayer;
//			m_ThirdPartyPayer.addItem(m_DisbandedThirdPartyPayer);
//			}
//		m_ThirdPartyPayer.setSelectedItem (p_ThirdPartyPayer);
//		l_Renderer = (DefaultComboBoxRenderer) m_ThirdPartyPayer.getRenderer();
//		m_ThirdPartyPayerField.setText(l_Renderer.renderObject(p_ThirdPartyPayer));
//		}
//	else resetThirdPartyPayer ();
//	
//	}

public void setInsurances (Invoice p_Invoice)
{
	
	if (p_Invoice.getThirdPartyPayer() != null && ! p_Invoice.getThirdPartyPayer().equals(m_DefaultInsurance)) {
		m_IsThirdParty.setSelected(true);
	} else {
		m_IsThirdParty.setSelected(false);
		
	}
	
	reloadInsuranceBox();
	
//	System.out.println("Invoice insurance: " + p_Invoice.getHealthInsurance() + " " + p_Invoice.isPaidByThirdParty());
	
	if (m_IsThirdParty.isSelected()) {
		if (p_Invoice != null && p_Invoice.getThirdPartyPayer() != null)
			m_HealthInsurance.setSelectedItem(p_Invoice.getThirdPartyPayer());
		else 
			m_HealthInsurance.setSelectedIndex(0);		
	} else {
		if (p_Invoice != null && p_Invoice.getHealthInsurance() != null)
			m_HealthInsurance.setSelectedItem(p_Invoice.getHealthInsurance());
		else 
			m_HealthInsurance.setSelectedItem(m_CNSInsurance);
	}
	
//	System.out.println("Set insurance: " + m_HealthInsurance.getSelectedItem() + " " + m_IsThirdParty.isSelected());

	DefaultComboBoxRenderer l_Renderer = (DefaultComboBoxRenderer) m_HealthInsurance.getRenderer();
	m_HealthInsuranceField.setText(l_Renderer.renderObject(m_HealthInsurance.getSelectedItem()));

}

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

/**
 * @author ferring
 * Shows or hides the check box to the template list
 * 
 * @param p_Visible
 */
public void setFilterByPhysicianBoxVisible (boolean p_Visible)
	{
	if (BillingModule.userHasPermission (MainFrame.PERMISSIONS_CORE, MainFrame.PERMISSION_CHANGE_PHYSICIAN))
		{
		m_FilterByPhysicianBox.setVisible(p_Visible);
		}
	else m_FilterByPhysicianBox.setVisible(false); 
	} 

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

//public void resetThirdPartyPayer ()
//	{
//	if (m_ThirdPartyPayer.getItemCount() > m_Default3ppIndex) 
//		m_ThirdPartyPayer.setSelectedIndex(m_Default3ppIndex);
//	else if (m_ThirdPartyPayer.getItemCount() > 0) 
//		m_ThirdPartyPayer.setSelectedIndex(0);
//	
//	m_IsThirdParty.setEnabled(false);
//	
//	m_ThirdPartyPayerField.setText("");
//	}

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

public void actionPerformed(ActionEvent p_Event)
	{
	if (! listenersActive ) return;
	
	if (p_Event.getSource() == m_InvoiceNumber || p_Event.getSource() == m_InvoiceSearchButton) {
		this.firePropertyChange(c_InvoiceNumber, null, this.getInvoiceNumber());
	} else if (p_Event.getSource() == m_IsThirdParty) {
		reloadInsuranceBox();
		
		if (m_IsThirdParty.isSelected()) {
			m_HealthInsurance.setSelectedIndex(0);
		} else {
			m_HealthInsurance.setSelectedItem(m_CNSInsurance);
		}
		DefaultComboBoxRenderer l_Renderer = (DefaultComboBoxRenderer) m_HealthInsurance.getRenderer();
		m_HealthInsuranceField.setText(l_Renderer.renderObject(m_HealthInsurance.getSelectedItem()));
		
		if (m_IsThirdParty.isSelected()) {
			this.firePropertyChange(c_ThirdPartyPayer, null, m_HealthInsurance.getSelectedItem());			
		} else {
			this.firePropertyChange(c_ThirdPartyPayer, m_HealthInsurance.getSelectedItem(), null);
		}
	} else if (p_Event.getSource() == m_HealthInsurance) {
		this.firePropertyChange (c_HealthInsurance, null, getHealthInsurance());
		this.firePropertyChange (c_ThirdPartyPayer, null, getThirdPartyPayer());			
	}
} 

public void focusGained (FocusEvent e)
{
	if (e.getSource() == m_InvoiceNumber)
	{
		Caret c = m_InvoiceNumber.getCaret();
		c.setDot(0);
		c.moveDot(m_InvoiceNumber.getText().length());
	}
}

public void focusLost (FocusEvent e) {}

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