/*
 * PesquisasWindow.java
 *
 * Created on 3 de Junho de 2004, 18:13
 */

package siprp.pesquisas;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;

import com.evolute.utils.*;
import com.evolute.utils.data.*;
import com.evolute.utils.documents.*;
import com.evolute.utils.jdo.*;
import com.evolute.utils.tables.*;
import com.evolute.utils.tracker.*;
import com.evolute.utils.ui.*;
import com.evolute.utils.ui.text.*;

import siprp.data.*;

/**
 *
 * @author  fpalma
 */
public class PesquisasWindow extends JFrame
	implements TrackableWindow, ListSelectionListener, ActionListener
{
	private JDOProvider JDO;
	private PesquisasProvider provider;
	
	private JTextField anoText;
	private BaseTable empresasTable;
	private VectorTableModel empresasModel;
	private BaseTable estabelecimentosTable;
	private VectorTableModel estabelecimentosModel;
	private JButton pesquisarButton;
	private JButton exportarButton;
	private JEditorPane resultadoText;

//	public static void main( String args[] )
//		throws Exception
//	{
//		new PesquisasWindow().show();
//	}
	
	/** Creates a new instance of PesquisasWindow */
	public PesquisasWindow()
		throws Exception
	{
		provider = (PesquisasProvider)PesquisasProvider.getProvider();
		JDO =( JDOProvider ) Singleton.getInstance( Singleton.DEFAULT_JDO_PROVIDER );
		setupComponents();
	}
	
	private void setupComponents()
	{
		setSize( 1000, 700 );
		setTitle( "Relat\u00f3rio Anual" );
		
		JLabel anoLabel = new JLabel( "Ano" );
		anoText = new JTextField();
		anoText.setDocument( new YearDocument() );
		anoText.setPreferredSize( new Dimension( 50, 20 ) );
		new CopyPasteHandler( anoText );
			
		empresasModel = new VectorTableModel( new String[]{ "Designa\u00e7\u00e3o Social" } );
		empresasTable = new BaseTable( empresasModel );
		empresasTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
		empresasTable.setNonResizableNorReordable();
		empresasTable.getSelectionModel().addListSelectionListener( this );
		JScrollPane empresasScroll = new JScrollPane();
		empresasScroll.setBorder( BorderFactory.createTitledBorder( 
									BorderFactory.createEtchedBorder(), "Empresa" ) );
		empresasScroll.setViewportView( empresasTable );
		empresasScroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		empresasScroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
		empresasScroll.getVerticalScrollBar().setBlockIncrement(20);
		
		estabelecimentosModel = new VectorTableModel( new String[]{ "Nome" } );
		estabelecimentosTable = new BaseTable( estabelecimentosModel );
		estabelecimentosTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
		estabelecimentosTable.setNonResizableNorReordable();
		estabelecimentosTable.getSelectionModel().addListSelectionListener( this );
		JScrollPane estabelecimentosScroll = new JScrollPane();
		estabelecimentosScroll.setBorder( BorderFactory.createTitledBorder( 
									BorderFactory.createEtchedBorder(), "Estabelecimento" ) );
		estabelecimentosScroll.setViewportView( estabelecimentosTable );
		estabelecimentosScroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		estabelecimentosScroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
		
		pesquisarButton = new JButton( "Pesquisar" );
		pesquisarButton.addActionListener( this );
		exportarButton = new JButton( "Exportar" );
		exportarButton.addActionListener( this );
		
		resultadoText = new JEditorPane( "text/html", "" );
		resultadoText.setEditable( false );
//		resultadoText.setLineWrap( true );
//		resultadoText.setWrapStyleWord( true );
		new CopyPasteHandler( resultadoText );
		JScrollPane resultadoScroll = new JScrollPane();
		resultadoScroll.setViewportView( resultadoText );
		resultadoScroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		resultadoScroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
		
		JPanel pad;
		
		GridBagLayout gridbag = new GridBagLayout();
		getContentPane().setLayout( gridbag );
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.insets = new Insets( 5, 5, 5, 5 );
		
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.weighty = 0;
		constraints.gridheight = 1;
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		JPanel anoPanel = new JPanel();
		anoPanel.setLayout( new FlowLayout( FlowLayout.LEFT ) );
		anoPanel.add( anoLabel );
		anoPanel.add( anoText );
		gridbag.setConstraints( anoPanel, constraints );
		getContentPane().add( anoPanel );
		
		constraints.fill = GridBagConstraints.BOTH;
		constraints.weighty = 0.2;
		constraints.gridheight = 2;
		constraints.weightx = 0.3;
		constraints.gridwidth = 3;
		gridbag.setConstraints( empresasScroll, constraints );
		getContentPane().add( empresasScroll );
		
		gridbag.setConstraints( estabelecimentosScroll, constraints );
		getContentPane().add( estabelecimentosScroll );
		
		constraints.weighty = 0;
		constraints.gridheight = 1;
		constraints.weightx = 0.4;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		pad = new JPanel();
		gridbag.setConstraints( pad, constraints );
		getContentPane().add( pad );
		
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.weighty = 0;
		constraints.gridheight = 1;
		constraints.weightx = 0;
		constraints.gridwidth = 1;
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout( new GridLayout( 1, 2 ) );
		buttonPanel.add( pesquisarButton );
		buttonPanel.add( exportarButton );
		gridbag.setConstraints( buttonPanel, constraints );
		getContentPane().add( buttonPanel );
		
		constraints.weighty = 0;
		constraints.gridheight = 1;
		constraints.weightx = 0.4;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		pad = new JPanel();
		gridbag.setConstraints( pad, constraints );
		getContentPane().add( pad );
		
		constraints.fill = GridBagConstraints.BOTH;
		constraints.weighty = 0.8;
		constraints.gridheight = GridBagConstraints.REMAINDER;
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( resultadoScroll, constraints );
		getContentPane().add( resultadoScroll );
	}
	
	private boolean close()
	{
		setVisible( false );
		dispose();
		return true;
	}
	
	public boolean closeIfPossible()
	{
		return close();
	}
	
	public void open()
	{
		empresasTable.clearSelection();
		try
		{
			IDObject empresas[] = provider.getAllEmpresas();
			empresasModel.setValues( new Vector( Arrays.asList( empresas ) ) );
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a carregar dados", true );
		}
		setVisible( true );
	}
	
	public void refresh()
	{
	}
	
	public void valueChanged( ListSelectionEvent e )
	{
		Object source = e.getSource();
		if( source.equals( empresasTable.getSelectionModel() ) )
		{
			estabelecimentosTable.clearSelection();
			int selected = empresasTable.getSelectedRow();
			if( selected == -1 )
			{
				return;
			}
			IDObject empresa = (IDObject) empresasModel.getRowAt( selected );
			estabelecimentosModel.clearAll();
			IDObject estabelecimentos[];
			try
			{
				estabelecimentos = provider.getAllEstabelecimentosForEmpresa( empresa.getID() );
			}
			catch( Exception ex )
			{
				DialogException.showExceptionMessage( ex, "Erro a carregar os estabelecimentos", true );
				return;
			}
			Vector v = new Vector( Arrays.asList( estabelecimentos ) );
			v.add( new MappableObject( new Integer( -1 ), "TODOS" ) );
			estabelecimentosModel.setValues( v );
		}
/*		else if( source.equals( estabelecimentosTable.getSelectionModel() ) )
		{
		}*/
	}
	
	public void actionPerformed( ActionEvent e )
	{
		Object source = e.getSource();
		if( source.equals( pesquisarButton ) )
		{
			int sEmpresa = empresasTable.getSelectedRow();
			int sEstabelecimento = estabelecimentosTable.getSelectedRow();
			String anoStr = anoText.getText();
			int ano = ( anoStr.length() != 0 )? Integer.parseInt( anoStr ): -1;
			if( sEmpresa == -1 || ano == -1 )
			{
				JOptionPane.showMessageDialog( this, "Tem de escolher ano e empresa", "Erro...",
					JOptionPane.ERROR_MESSAGE );
				return;
			}
			StringBuffer buff = new StringBuffer();
			buff.append( "ANO: " );
			buff.append( "<B>" + ano + "</B><BR>" );
			buff.append( "<BR><I>EMPRESA</I><BR>" );
			try
			{
				Integer idEmpresa = ( (IDObject)empresasModel.getRowAt( sEmpresa ) ).getID();
				EmpresaData empresa = (EmpresaData)JDO.load( EmpresaData.class, idEmpresa );
				buff.append( "&nbsp;DESIGNA\u00C7\u00C3O SOCIAL: " );
				String designacao = (String)empresa.get( EmpresaData.DESIGNACAO_SOCIAL );
				buff.append( "<B>" + ( designacao == null ? "" : designacao.trim() ) + "</B><BR>" );
				buff.append( "&nbsp;MORADA: " );
				String morada = (String)empresa.get( EmpresaData.MORADA );
				buff.append( "<B>" + ( morada == null ? "" : morada.trim() ) + "</B><BR>" );
				buff.append( "&nbsp;LOCALIDADE: " );
				String localidade = ( String ) empresa.get( EmpresaData.LOCALIDADE );
				buff.append( "<B>" + ( localidade == null ? "" : localidade.trim() ) + "</B><BR>" );
				buff.append( "&nbsp;C\u00D3DIGO POSTAL: " );
				String codigoPostal = ( String ) empresa.get( EmpresaData.CODIGO_POSTAL );
				buff.append( "<B>" + ( codigoPostal == null ? "" : codigoPostal.trim() ) + "</B><BR>" );
				ContactoData contacto = (ContactoData)empresa.get( EmpresaData.CONTACTO_2 );
				if( contacto == null )
				{
					buff.append( "&nbsp;TELEFONE: <BR>" );
					buff.append( "&nbsp;FAX: <BR>" );
				}
				else
				{
					buff.append( "&nbsp;TELEFONE: " );
					String telefone = ( String ) contacto.get( ContactoData.TELEFONE );
					buff.append( "<B>" + ( telefone == null ? "" : telefone.trim() ) + "</B><BR>" );
					buff.append( "&nbsp;FAX: " );
					String fax = ( String ) contacto.get( ContactoData.TELEFONE );
					buff.append( "<B>" + ( fax == null ? "" : fax.trim() ) + "</B><BR>" );
				}
				buff.append( "&nbsp;DISTRITO: " );
				String distrito = ( String ) empresa.get( EmpresaData.DISTRITO );
				buff.append( "<B>" + ( distrito == null ? "" : distrito ) + "</B><BR>" );
				buff.append( "&nbsp;CONCELHO: " );
				String concelho = ( String ) empresa.get( EmpresaData.CONCELHO );
				buff.append( "<B>" + ( concelho == null ? "" : concelho ) + "</B><BR>" );
				buff.append( "&nbsp;N\u00DAMERO PESSOA COLECTIVA: " );
				String contribuinte = ( String ) empresa.get( EmpresaData.CONTRIBUINTE );
				buff.append( "<B>" + ( contribuinte == null ? "" : contribuinte ) + "</B><BR>" );
				buff.append( "&nbsp;N\u00DAMERO SEGURAN\u00C7A SOCIAL: " );
				String segSocial = ( String ) empresa.get( EmpresaData.SEGURANCA_SOCIAL );
				buff.append( "<B>" + ( segSocial == null ? "" : segSocial ) + "</B><BR>" );
				buff.append( "&nbsp;CAE: " );
				String CAE = ( String ) empresa.get( EmpresaData.CAE );
				buff.append( "<B>" + ( CAE == null ? "" : CAE ) + "</B><BR>" );
				buff.append( "<BR>&nbsp;N\u00DAMERO M\u00C9DIO DE TRABALHADORES DURANTE O ANO" );
				double contagemMedia[] = provider.countNumeroMedioTrabalhadoresEmpresa( idEmpresa, ano );
				buff.append( "<TABLE BORDER=\"0\">" );
				buff.append( "<TR>" );
				buff.append( "<TD>&nbsp;&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>TOTAL</TD><TD>&nbsp;</TD><TD>HOMENS</TD><TD>&nbsp;</TD><TD>MULHERES</TD>" );
				buff.append( "</TR><TR>" );
				buff.append( "<TD>&nbsp;&nbsp;</TD><TD>TOTAL</TD><TD>&nbsp;</TD><TD ALIGN=\"CENTER\"><B>" + (int)( Math.round( contagemMedia[0] ) + Math.round( contagemMedia[1] ) ) + "</B></TD>");
				buff.append( "<TD>&nbsp;</TD><TD ALIGN=\"CENTER\"><B>" + ( (int)Math.round( contagemMedia[0] ) ) + "</B></TD>" );
				buff.append( "<TD>&nbsp;</TD><TD ALIGN=\"CENTER\"><B>" + ( (int)Math.round( contagemMedia[1] ) ) + "</B></TD>" );
				buff.append( "</TR>" );
				buff.append( "</TABLE>" );
				buff.append( "<BR>&nbsp;N\u00DAMERO TOTAL DE TRABALHADORES DURANTE O ANO" );
				double contagemTotal[] = provider.countNumeroTotalTrabalhadoresEmpresa( idEmpresa, ano );
				buff.append( "<TABLE BORDER=\"0\">" );
				buff.append( "<TR>" );
				buff.append( "<TD>&nbsp;&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>TOTAL</TD><TD>&nbsp;</TD><TD>HOMENS</TD><TD>&nbsp;</TD><TD>MULHERES</TD>" );
				buff.append( "</TR><TR>" );
				buff.append( "<TD>&nbsp;&nbsp;</TD><TD>TOTAL</TD><TD>&nbsp;</TD><TD ALIGN=\"CENTER\"><B>" + (int)( Math.round( contagemTotal[0] ) + Math.round( contagemTotal[1] ) ) + "</B></TD>");
				buff.append( "<TD>&nbsp;</TD><TD ALIGN=\"CENTER\"><B>" + ( (int)Math.round( contagemTotal[0] ) ) + "</B></TD>" );
				buff.append( "<TD>&nbsp;</TD><TD ALIGN=\"CENTER\"><B>" + ( (int)Math.round( contagemTotal[1] ) ) + "</B></TD>" );
				buff.append( "</TR>" );
				buff.append( "</TABLE>" );
				
				IDObject estabelecimentos[];
				if( sEstabelecimento == -1 || ( ( IDObject )estabelecimentosModel.getRowAt( sEstabelecimento ) ).getID().equals( new Integer( -1 ) ) )
				{
					estabelecimentos = provider.getAllEstabelecimentosForEmpresa( idEmpresa );
				}
				else
				{
					estabelecimentos = new IDObject[ 1 ];
					estabelecimentos[ 0 ] = ( IDObject )estabelecimentosModel.getRowAt( sEstabelecimento );
				}
				buff.append( "<BR>" );
				buff.append( "<BR><I>&nbsp;ESTABELECIMENTOS</I><BR>" );
				buff.append( "<BR>" );
				for( int n = 0; n < estabelecimentos.length; n++ )
				{
					EstabelecimentoData estabelecimento = (EstabelecimentoData)JDO.load( EstabelecimentoData.class, estabelecimentos[ n ].getID() );
					buff.append( "&nbsp;&nbsp;NOME: " );
					String nome = (String)estabelecimento.get( EstabelecimentoData.NOME );
					buff.append( "<B>" + ( nome == null ? "" : nome.trim() ) + "</B><BR>" );
					buff.append( "&nbsp;&nbsp;MORADA: " );
					morada = (String)estabelecimento.get( EstabelecimentoData.MORADA );
					buff.append( "<B>" + ( morada == null ? "" : morada.trim() ) + "</B><BR>" );
					buff.append( "&nbsp;&nbsp;LOCALIDADE: " );
					localidade = (String)estabelecimento.get( EstabelecimentoData.LOCALIDADE );
					buff.append( "<B>" + ( localidade == null ? "" : localidade.trim() ) + "</B><BR>" );
					buff.append( "&nbsp;&nbsp;C\u00D3DIGO POSTAL: " );
					codigoPostal = (String)estabelecimento.get( EstabelecimentoData.CODIGO_POSTAL );
					buff.append( "<B>" + ( codigoPostal == null ? "" : codigoPostal.trim() ) + "</B><BR>" );
					contacto = (ContactoData)estabelecimento.get( EstabelecimentoData.CONTACTO );
					if( contacto == null )
					{
						buff.append( "&nbsp;&nbsp;TELEFONE: <BR>" );
						buff.append( "&nbsp;&nbsp;FAX: <BR>" );
					}
					else
					{
						buff.append( "&nbsp;&nbsp;TELEFONE: " );
						String telefone = ( String ) contacto.get( ContactoData.TELEFONE );
						buff.append( "<B>" + ( telefone == null ? "" : telefone.trim() ) + "</B><BR>" );
						buff.append( "&nbsp;&nbsp;FAX: " );
						String fax = ( String ) contacto.get( ContactoData.TELEFONE );
						buff.append( "<B>" + ( fax == null ? "" : fax.trim() ) + "</B><BR>" );
					}
					int countTrabalhadores[] = provider.countTrabalhadoresEstabelecimentoDezembro( estabelecimentos[ n ].getID(), ano );
					buff.append( "<BR>" );
					buff.append( "&nbsp;&nbsp;<I>TRABALHADORES A 31 DE DEZEMBRO DE " + ano + ":</I> " );
					buff.append( "<BR>" );
					buff.append( "<TABLE BORDER=\"0\">" );
					buff.append( "<TR>" );
					buff.append( "<TD>&nbsp;&nbsp;</TD><TD>&nbsp</TD><TD>TOTAL</TD><TD>HOMENS</TD><TD>MULHERES</TD>" );
					buff.append( "</TR>" );
					buff.append( "<TR>" );
					buff.append( "<TD>&nbsp;&nbsp;</TD><TD>TOTAL</TD>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadores[0] + countTrabalhadores[1] ) + "</B></Td>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadores[0] ) + "</B></TD>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadores[1] ) + "</B></TD>" );
					buff.append( "</TR>" );
					int countTrabalhadoresEtario[][] = provider.countTrabalhadoresEstabelecimentoDezembroPorGrupoEtario( estabelecimentos[ n ].getID(), ano );
					buff.append( "<TR>" );
					buff.append( "<TD>&nbsp;&nbsp;</TD><TD>MENOS DE 18 ANOS</TD>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadoresEtario[0][0] + countTrabalhadoresEtario[0][1] ) + "</B></Td>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadoresEtario[0][0] ) + "</B></TD>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadoresEtario[0][1] ) + "</B></TD>" );
					buff.append( "</TR>" );
					buff.append( "<TR>" );
					buff.append( "<TD>&nbsp;&nbsp;</TD><TD>18 A 49 ANOS</TD>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadoresEtario[1][0] + countTrabalhadoresEtario[1][1] ) + "</B></Td>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadoresEtario[1][0] ) + "</B></TD>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadoresEtario[1][1] ) + "</B></TD>" );
					buff.append( "</TR>" );
					buff.append( "<TR>" );
					buff.append( "<TD>&nbsp;&nbsp;</TD><TD>MAIS DE 50 ANOS</TD>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadoresEtario[2][0] + countTrabalhadoresEtario[2][1] ) + "</B></Td>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadoresEtario[2][0] ) + "</B></TD>"
									+ "<TD ALIGN=\"CENTER\"><B> " + ( countTrabalhadoresEtario[2][1] ) + "</B></TD>" );
					buff.append( "</TR>" );
					buff.append( "</TABLE>" );
					buff.append( "<BR>" );
					int countExames[][] = provider.countExamesEstabelecimentoDezembroPorGrupoEtario( estabelecimentos[ n ].getID(), ano );
					for( int cE = 0; cE < countExames[ countExames.length - 2 ].length; cE++ )
					{
						countExames[ countExames.length - 2 ][ cE ] += countExames[ countExames.length - 1 ][ cE ];
					}
					int totais[] = new int[ 6 ];
					for( int cE1 = 0; cE1 < totais.length; cE1++ )
					{
						for( int cE2 = 0; cE2 < countExames.length; cE2++ )
						{
							totais[ cE1 ] += countExames[ cE2 ][ cE1 ];
						}
					}
					buff.append( "<BR>" );
					buff.append( "&nbsp;&nbsp;<I>N\u00DAMERO DE EXAMES DE ADMISS\u00C3O, PERI\u00D3DICOS E OCASIONAIS EFECTUADOS</I>" );
					buff.append( "<BR>" );
					buff.append( "<TABLE BORDER=\"0\">" );
					buff.append( "<TR><TD>&nbsp;&nbsp;&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>TOTAL</TD><TD>&nbsp;</TD><TD>INFERIOR A 18 ANOS</TD>"
									+ "<TD>&nbsp;</TD><TD>18 A 49 ANOS</TD><TD>&nbsp;</TD><TD>50 E MAIS ANOS</TD><TD>&nbsp;</TD></TR>" );
					buff.append( "<TR><TD>&nbsp;&nbsp;&nbsp;</TD><TD>TOTAL DE EXAMES</TD><TD>&nbsp;</TD><TD>H</TD>" );
					buff.append( "<TD ALIGN=\"CENTER\"><B>" + ( totais[0] + totais[1] + totais[2] ) + "</B></TD><TD>&nbsp;</TD>" );
					for( int t = 0; t < 3; t++ )
					{
						buff.append( "<TD ALIGN=\"CENTER\"><B>" + totais[t] + "</B></TD><TD>&nbsp;</TD>" );
					}
					buff.append( "</TR>" );
					buff.append( "<TR><TD>&nbsp;&nbsp;&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>M</TD>" );
					buff.append( "<TD ALIGN=\"CENTER\"><B>" + ( totais[3] + totais[4] + totais[5] ) + "</B></TD><TD>&nbsp;</TD>" );
					for( int t = 3; t < 6; t++ )
					{
						buff.append( "<TD ALIGN=\"CENTER\"><B>" + totais[t] + "</B></TD><TD>&nbsp;</TD>" );
					}
					buff.append( "</TR>" );
					String sexos[] = new String[]{ "H", "M" };
					for( int t = 0; t < provider.DESCRICAO_TIPOS_EXAME.length; t++ )
					{
						buff.append( "<TR><TD>&nbsp;&nbsp;&nbsp;</TD><TD>&nbsp;"+provider.DESCRICAO_TIPOS_EXAME[t]+"</TD>" );
						
						for( int s = 0; s < 2; s++ )
						{
							buff.append( "<TD>&nbsp;</TD><TD>" + sexos[ s ] + "</TD>" );
							buff.append( "<TD ALIGN=\"CENTER\"><B>" + (countExames[t][s*3]+countExames[t][s*3+1]+countExames[t][s*3+2]) + "</B></TD><TD>&nbsp;</TD>" );
							for( int d = 0; d < 3; d++ )
							{
								buff.append( "<TD ALIGN=\"CENTER\"><B>" + countExames[t][s*3+d] + "</B></TD><TD>&nbsp;</TD>" );
							}
							if( s == 0 )
							{
								buff.append( "</TR><TR><TD>&nbsp;&nbsp;&nbsp;</TD><TD>&nbsp;</TD>" );
							}
							else
							{
								buff.append( "</TR>" );
							}
						}
					}
					int countExamesOcasionais[][] = provider.countExamesOcasionaisEstabelecimentoDezembroPorGrupoEtario( estabelecimentos[ n ].getID(), ano );
					for( int t = 0; t < provider.DESCRICAO_TIPOS_OCASIONAL.length; t++ )
					{
						buff.append( "<TR><TD>&nbsp;&nbsp;&nbsp;</TD><TD>&nbsp;&nbsp;&nbsp;&nbsp;"+provider.DESCRICAO_TIPOS_OCASIONAL[t]+"</TD>" );
						
						for( int s = 0; s < 2; s++ )
						{
							buff.append( "<TD>&nbsp;</TD><TD>" + sexos[ s ] + "</TD>" );
							int sum = countExamesOcasionais[t][s*3]+countExamesOcasionais[t][s*3+1]+countExamesOcasionais[t][s*3+2];
							buff.append( "<TD ALIGN=\"CENTER\"><B>" + ( sum < 0 ? "-" : "" + sum ) + "</B></TD><TD>&nbsp;</TD>" );
							for( int d = 0; d < 3; d++ )
							{
								int val = countExamesOcasionais[t][s*3+d];
								if( val < 0 )
								{
									countExamesOcasionais[t][s*3+d] = 0;
								}
								buff.append( "<TD ALIGN=\"CENTER\"><B>" + ( val < 0 ? "-" : "" + val ) + "</B></TD><TD>&nbsp;</TD>" );
							}
							if( s == 0 )
							{
								buff.append( "</TR><TR><TD>&nbsp;&nbsp;&nbsp;</TD><TD>&nbsp;&nbsp;&nbsp;&nbsp;</TD>" );
							}
							else
							{
								buff.append( "</TR>" );
							}
						}
					}
					buff.append( "</TABLE>" );
					buff.append( "<BR>" );
					buff.append( "&nbsp;&nbsp;<I>EXAMES COMPLEMENTARES REALIZADOS</I>" );
					buff.append( "<BR>" );
					buff.append( "<TABLE BORDER=\"0\">" );
					buff.append( "<TR><TD>&nbsp;&nbsp;&nbsp;</TD><TD>TIPO DE EXAME</TD><TD>&nbsp;</TD>" );
					buff.append( "<TD>N\u00BA TOTAL DE EXAMES</TD></TR>" );
					String nomesExamesComp[] = provider.getNomesExames();
//					int countExamesComp[] = provider.countExamesComplementaresEmpresa( idEmpresa, ano );
					int countExamesComp[] = provider.countExamesComplementaresEstabelecimento( estabelecimentos[ n ].getID(), ano );
					for( int nec = 0; nec < nomesExamesComp.length; nec++ )
					{
						buff.append( "<TR>" );
						buff.append( "<TD>&nbsp;&nbsp;&nbsp;</TD><TD>" + nomesExamesComp[nec] + "</TD>" );
						buff.append( "<TD>&nbsp;</TD><TD ALIGN=\"CENTER\"><B>" + countExamesComp[nec] + "</B></TD>" );
						buff.append( "</TR>" );
					}
					buff.append( "</TABLE>" );
					buff.append("<BR><HR><BR>");
				}
				
				resultadoText.setText( buff.toString() );
			}
			catch( Exception ex )
			{
				DialogException.showExceptionMessage( ex, "Erro a carregar dados", true );
				return;
			}
		}
		else if( source.equals( exportarButton ) )
		{
			exportar();
		}
	}
	
	public void exportar()
	{
		FileDialog dialog = new FileDialog( this, "Ficheiro de destino", FileDialog.SAVE );
		dialog.setDirectory( System.getProperty( "user.home" ) );
		dialog.setVisible( true );
		String fileName;
		String dirName;
		fileName = dialog.getFile();
		dirName = dialog.getDirectory();
		if( fileName != null )
		{
			int index = fileName.indexOf( '.' );
			if( index == -1 )
			{
				fileName += ".html";
			}
			if( index == fileName.length() - 1 )
			{
				fileName += "html";
			}
			String fullName = dirName + fileName;
			String text = resultadoText.getText();
			String title = "S.I.P.R.P. - Sociedade Ib&eacute;rica de Preven&ccedil;&atilde;o de Riscos Profissionais";
			String style = "<style type=\"text/css\">\n"
							+ " body,td{font-family: arial;"
							+	"	font-size: 8pt; }\n"
							+ " p{font-family: arial;"
							+	"	font-size: 1pt; }\n"
							+ "</style>";
			text = text.replace( "<head>", "<head>\n\t\t<title>" + title + "</title>\n" + style );
			text = text.replace( "<font size=\"+2\">", "<div style=\"font-family : arial; font-size : 12pt;\">" ); 
			text = text.replace( "</font>", "</div>" ); 
			text = text.replace( "<body>", "<body>\n<div style=\"font-family : arial; font-size : 12pt;\" align=\"center\"><b>Relat&oacute;rio Anual</b></div>" ); 
//			String title = "S.I.P.R.P. - Sociedade Ib&eacute;rica de Preven&ccedil;&atilde;o de Riscos Profissionais";
//			text = text.replace( "<head>", "<head>\n\t\t<title>" + title + "</title>" );
//	System.out.println( text );
		    try
		    {
				FileWriter writer = new FileWriter( new File( fullName ) );
				writer.write( text );
				writer.close();
			}
			catch( IOException ex )
		    {
		    	DialogException.showException( ex );
		    	return;
		    }
		}
	}
}

