/*
 * WizardDialog.java
 *
 * iReport  --  Visual designer for generating JasperReports Documents
 *  Copyright (C) 2002-2003  Giulio Toffoli gt@businesslogic.it
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  Giulio Toffoli
 *  Via T.Aspetti, 233
 *  35100 Padova ITALY
 *  gt@businesslogic.it
 *
 *
 * How this window work.
 * This form has an attribute that rappresents the JReportForm active.
 * If the jrf is null, this frame hides.
 * When something changes, the program can call "updateSelection". This
 * class retrive from jrf the selected elements and update all
 * interface.
 *
 * Created on 30 giugno 2003, 18.26
 */

package it.businesslogic.ireport.gui;
import it.businesslogic.ireport.util.*;
import it.businesslogic.ireport.*;
import it.businesslogic.ireport.connection.*;
import java.sql.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author  Administrator
 */
public class WizardDialog extends javax.swing.JDialog implements Runnable {
    
    Thread t = null;
    File[] templates = null;
    
    /** Creates new form WizardDialog */
    public WizardDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        wzStep = 1;
        this.setStep(wzStep,wzStep);
        this.setSize(470, 340);           
        Misc.centerFrame(this);
        
        this.jRSQLExpressionArea1.getDocument().addDocumentListener( new javax.swing.event.DocumentListener() {
            public void changedUpdate(javax.swing.event.DocumentEvent evt)
            {
                jRSQLExpressionArea1TextConnectionExpressionTextChanged();
            }
            public void insertUpdate(javax.swing.event.DocumentEvent evt) {
                jRSQLExpressionArea1TextConnectionExpressionTextChanged();
            }
            public void removeUpdate(javax.swing.event.DocumentEvent evt) {
                jRSQLExpressionArea1TextConnectionExpressionTextChanged();
            }
        }); 
        
        jList1.setModel(new javax.swing.DefaultListModel());
        jList2.setModel(new javax.swing.DefaultListModel());
        jList3.setModel(new javax.swing.DefaultListModel());
        
        jComboBoxTemplates.addItem("Columnar");
        jComboBoxTemplates.addItem("Tabular");
        
        String templates_dir = System.getProperty("ireport.home",".");
        templates_dir +=  File.separator + "templates";
        //System.out.println("Templates: " + templates_dir);
        //C:\\documenti\\progetti\\ireport\\iReport2\\templates
        
        File f = new File(templates_dir);
        if (f.exists() && f.isDirectory())
        {
            templates  = f.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) 
                {
                    if (name.endsWith("T.xml") || name.endsWith("C.xml"))
                    {
                        return true;
                    }
                    return false;
                }
            });          
        }      
        if (templates == null)
        {
            templates = new File[0];
        }
        
        jComboBoxTemplates.setSelectedIndex(0);
    }
    
    private int wzStep=0;
    
    
    public void updateTemplatesList()
    {
        if (templates == null) return;
        ((javax.swing.DefaultListModel)jList3.getModel()).removeAllElements();
        for (int i=0; i<templates.length; ++i)
        {
            if (jComboBoxTemplates.getItemCount()<2 || (jComboBoxTemplates.getSelectedIndex() == 0 && !templates[i].getName().endsWith("C.xml")) )  continue;
            if (jComboBoxTemplates.getSelectedIndex() == 1 && !templates[i].getName().endsWith("T.xml") )  continue;
            
            TemplateFile tf = new TemplateFile();
            tf.file = templates[i];
            
            tf.name = templates[i].getName().substring(0, templates[i].getName().length()-4);
            
            ((javax.swing.DefaultListModel)jList3.getModel()).addElement(tf);
        }
        if ( ((javax.swing.DefaultListModel)jList3.getModel()).getSize()>0)
            jList3.setSelectedIndex(0);
        jList3.updateUI();
    }
    
    public void jRSQLExpressionArea1TextConnectionExpressionTextChanged()
    {
        if (this.jRSQLExpressionArea1.getText().trim().length() == 0)
        {
            jButtonNext.setEnabled(false);
        }
        else
            jButtonNext.setEnabled( true );
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        jLabelStep1 = new javax.swing.JLabel();
        jLabelStep2 = new javax.swing.JLabel();
        jLabelStep3 = new javax.swing.JLabel();
        jLabelStep4 = new javax.swing.JLabel();
        jLabelStep5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jButtonCancel = new javax.swing.JButton();
        jButtonNext = new javax.swing.JButton();
        jButtonPrev = new javax.swing.JButton();
        jPanelRoot = new javax.swing.JPanel();
        jPanelStep1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jRSQLExpressionArea1 = new it.businesslogic.ireport.gui.JRSQLExpressionArea();
        jLabel3 = new javax.swing.JLabel();
        jSeparator3 = new javax.swing.JSeparator();
        jPanelStep3 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jSeparator5 = new javax.swing.JSeparator();
        jComboBox1 = new javax.swing.JComboBox();
        jLabelG1 = new javax.swing.JLabel();
        jLabelG2 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jLabelG3 = new javax.swing.JLabel();
        jComboBox3 = new javax.swing.JComboBox();
        jLabelG4 = new javax.swing.JLabel();
        jComboBox4 = new javax.swing.JComboBox();
        jPanelStep5 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        jSeparator7 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jPanelStep2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jSeparator4 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jPanelStep4 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        jSeparator6 = new javax.swing.JSeparator();
        jComboBoxTemplates = new javax.swing.JComboBox();
        jScrollPane3 = new javax.swing.JScrollPane();
        jList3 = new javax.swing.JList();
        jLabelImage = new javax.swing.JLabel();

        getContentPane().setLayout(null);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("iReport Wizard");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        getContentPane().add(jSeparator1);
        jSeparator1.setBounds(2, 280, 460, 4);

        jSeparator2.setBackground(new java.awt.Color(204, 204, 255));
        jSeparator2.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator2.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator2.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator2.setPreferredSize(new java.awt.Dimension(1, 1));
        getContentPane().add(jSeparator2);
        jSeparator2.setBounds(8, 28, 98, 2);

        jLabel1.setFont(new java.awt.Font("Dialog", 1, 11));
        jLabel1.setText("Steps");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(8, 10, 84, 16);

        jLabelStep1.setFont(new java.awt.Font("Dialog", 1, 11));
        jLabelStep1.setText("1. Query");
        getContentPane().add(jLabelStep1);
        jLabelStep1.setBounds(8, 34, 110, 16);

        jLabelStep2.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabelStep2.setText("2. Fields selection");
        getContentPane().add(jLabelStep2);
        jLabelStep2.setBounds(8, 52, 110, 16);

        jLabelStep3.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabelStep3.setText("3. Group by ...");
        getContentPane().add(jLabelStep3);
        jLabelStep3.setBounds(8, 70, 110, 16);

        jLabelStep4.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabelStep4.setText("4. Layout");
        getContentPane().add(jLabelStep4);
        jLabelStep4.setBounds(8, 88, 110, 16);

        jLabelStep5.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabelStep5.setText("5. Finish");
        getContentPane().add(jLabelStep5);
        jLabelStep5.setBounds(8, 106, 110, 16);

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/it/businesslogic/ireport/icons/wizard.jpg")));
        getContentPane().add(jLabel7);
        jLabel7.setBounds(0, 0, 132, 284);

        jButtonCancel.setFont(new java.awt.Font("Dialog", 0, 11));
        jButtonCancel.setMnemonic('f');
        jButtonCancel.setText("Cancel");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        getContentPane().add(jButtonCancel);
        jButtonCancel.setBounds(384, 286, 76, 24);

        jButtonNext.setFont(new java.awt.Font("Dialog", 0, 11));
        jButtonNext.setMnemonic('n');
        jButtonNext.setText("Next >");
        jButtonNext.setEnabled(false);
        jButtonNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNextActionPerformed(evt);
            }
        });

        getContentPane().add(jButtonNext);
        jButtonNext.setBounds(302, 286, 76, 24);

        jButtonPrev.setFont(new java.awt.Font("Dialog", 0, 11));
        jButtonPrev.setMnemonic('p');
        jButtonPrev.setText("< Prev");
        jButtonPrev.setEnabled(false);
        jButtonPrev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPrevActionPerformed(evt);
            }
        });

        getContentPane().add(jButtonPrev);
        jButtonPrev.setBounds(220, 286, 76, 24);

        jPanelRoot.setLayout(new java.awt.BorderLayout());

        jPanelStep1.setLayout(null);

        jLabel2.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabel2.setText("Query string");
        jPanelStep1.add(jLabel2);
        jLabel2.setBounds(0, 158, 88, 15);

        jRSQLExpressionArea1.setBorder(new javax.swing.border.EtchedBorder());
        jPanelStep1.add(jRSQLExpressionArea1);
        jRSQLExpressionArea1.setBounds(0, 174, 300, 102);

        jLabel3.setFont(new java.awt.Font("Dialog", 1, 11));
        jLabel3.setText("Step 1: insert the query to retrive report fields");
        jPanelStep1.add(jLabel3);
        jLabel3.setBounds(0, 10, 298, 16);

        jSeparator3.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator3.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator3.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator3.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator3.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep1.add(jSeparator3);
        jSeparator3.setBounds(0, 28, 300, 2);

        jPanelRoot.add(jPanelStep1, java.awt.BorderLayout.CENTER);

        jPanelStep3.setLayout(null);

        jLabel6.setFont(new java.awt.Font("Dialog", 1, 11));
        jLabel6.setText("Step3: group by...");
        jPanelStep3.add(jLabel6);
        jLabel6.setBounds(0, 10, 298, 16);

        jSeparator5.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator5.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator5.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator5.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator5.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep3.add(jSeparator5);
        jSeparator5.setBounds(0, 28, 300, 2);

        jComboBox1.setFont(new java.awt.Font("Dialog", 0, 11));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jPanelStep3.add(jComboBox1);
        jComboBox1.setBounds(6, 102, 290, 24);

        jLabelG1.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabelG1.setText("Group 1");
        jPanelStep3.add(jLabelG1);
        jLabelG1.setBounds(6, 84, 110, 16);

        jLabelG2.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabelG2.setText("Group 2");
        jPanelStep3.add(jLabelG2);
        jLabelG2.setBounds(6, 128, 110, 16);

        jComboBox2.setFont(new java.awt.Font("Dialog", 0, 11));
        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });

        jPanelStep3.add(jComboBox2);
        jComboBox2.setBounds(6, 146, 290, 24);

        jLabelG3.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabelG3.setText("Group 3");
        jPanelStep3.add(jLabelG3);
        jLabelG3.setBounds(6, 172, 110, 16);

        jComboBox3.setFont(new java.awt.Font("Dialog", 0, 11));
        jComboBox3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox3ActionPerformed(evt);
            }
        });

        jPanelStep3.add(jComboBox3);
        jComboBox3.setBounds(6, 190, 290, 24);

        jLabelG4.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabelG4.setText("Group 4");
        jPanelStep3.add(jLabelG4);
        jLabelG4.setBounds(6, 216, 110, 16);

        jComboBox4.setFont(new java.awt.Font("Dialog", 0, 11));
        jPanelStep3.add(jComboBox4);
        jComboBox4.setBounds(6, 234, 290, 24);

        jPanelRoot.add(jPanelStep3, java.awt.BorderLayout.CENTER);

        jPanelStep5.setLayout(null);

        jLabel9.setFont(new java.awt.Font("Dialog", 1, 11));
        jLabel9.setText("Step 5: finish");
        jPanelStep5.add(jLabel9);
        jLabel9.setBounds(0, 10, 298, 16);

        jSeparator7.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator7.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator7.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator7.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator7.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep5.add(jSeparator7);
        jSeparator7.setBounds(0, 28, 324, 2);

        jLabel4.setFont(new java.awt.Font("Dialog", 0, 14));
        jLabel4.setText("Congratulation!");
        jPanelStep5.add(jLabel4);
        jLabel4.setBounds(62, 58, 154, 32);

        jLabel10.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabel10.setText("You have succesfully created a new report.");
        jLabel10.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jPanelStep5.add(jLabel10);
        jLabel10.setBounds(62, 92, 240, 22);

        jLabel11.setFont(new java.awt.Font("Dialog", 0, 11));
        jLabel11.setText("Press 'Finish' to generate it.");
        jLabel11.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jPanelStep5.add(jLabel11);
        jLabel11.setBounds(62, 106, 240, 22);

        jPanelRoot.add(jPanelStep5, java.awt.BorderLayout.CENTER);

        jPanelStep2.setLayout(null);

        jLabel5.setFont(new java.awt.Font("Dialog", 1, 11));
        jLabel5.setText("Step2: select fields");
        jPanelStep2.add(jLabel5);
        jLabel5.setBounds(0, 10, 300, 16);

        jSeparator4.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator4.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator4.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator4.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator4.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep2.add(jSeparator4);
        jSeparator4.setBounds(0, 28, 322, 4);

        jList2.setFont(new java.awt.Font("Dialog", 0, 11));
        jScrollPane1.setViewportView(jList2);

        jPanelStep2.add(jScrollPane1);
        jScrollPane1.setBounds(180, 48, 144, 228);

        jList1.setFont(new java.awt.Font("Dialog", 0, 11));
        jScrollPane2.setViewportView(jList1);

        jPanelStep2.add(jScrollPane2);
        jScrollPane2.setBounds(2, 48, 144, 228);

        jButton4.setFont(new java.awt.Font("Dialog", 1, 14));
        jButton4.setText(">");
        jButton4.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jPanelStep2.add(jButton4);
        jButton4.setBounds(149, 88, 28, 29);

        jButton5.setFont(new java.awt.Font("Dialog", 1, 14));
        jButton5.setText(">>");
        jButton5.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jPanelStep2.add(jButton5);
        jButton5.setBounds(149, 118, 28, 29);

        jButton6.setFont(new java.awt.Font("Dialog", 1, 14));
        jButton6.setText("<");
        jButton6.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jPanelStep2.add(jButton6);
        jButton6.setBounds(149, 154, 28, 29);

        jButton7.setFont(new java.awt.Font("Dialog", 1, 14));
        jButton7.setText("<<");
        jButton7.setMargin(new java.awt.Insets(2, 0, 2, 0));
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jPanelStep2.add(jButton7);
        jButton7.setBounds(149, 184, 28, 29);

        jPanelRoot.add(jPanelStep2, java.awt.BorderLayout.CENTER);

        jPanelStep4.setLayout(null);

        jLabel8.setFont(new java.awt.Font("Dialog", 1, 11));
        jLabel8.setText("Step 4: choose layout");
        jPanelStep4.add(jLabel8);
        jLabel8.setBounds(0, 10, 298, 16);

        jSeparator6.setBackground(new java.awt.Color(204, 204, 204));
        jSeparator6.setForeground(new java.awt.Color(0, 0, 0));
        jSeparator6.setMaximumSize(new java.awt.Dimension(32767, 1));
        jSeparator6.setMinimumSize(new java.awt.Dimension(98, 1));
        jSeparator6.setPreferredSize(new java.awt.Dimension(10, 1));
        jPanelStep4.add(jSeparator6);
        jSeparator6.setBounds(0, 28, 320, 2);

        jComboBoxTemplates.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxTemplatesActionPerformed(evt);
            }
        });

        jPanelStep4.add(jComboBoxTemplates);
        jComboBoxTemplates.setBounds(8, 92, 144, 25);

        jList3.setFont(new java.awt.Font("Dialog", 0, 11));
        jList3.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList3.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList3ValueChanged(evt);
            }
        });

        jScrollPane3.setViewportView(jList3);

        jPanelStep4.add(jScrollPane3);
        jScrollPane3.setBounds(8, 118, 144, 156);

        jPanelStep4.add(jLabelImage);
        jLabelImage.setBounds(156, 118, 166, 158);

        jPanelRoot.add(jPanelStep4, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanelRoot);
        jPanelRoot.setBounds(138, 0, 324, 278);

        pack();
    }//GEN-END:initComponents

    private void jList3ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList3ValueChanged
        
        if (jList3.getSelectedIndex() >= 0)
        {
            TemplateFile tf = (TemplateFile)jList3.getSelectedValue();
            // Take the image...
            String image_name = tf.file.getAbsolutePath();
            image_name = image_name.substring(0, image_name.length()-3)+"gif";
            java.io.File f = new java.io.File(image_name);
            if (f.exists() && f.isFile())
            {
                java.awt.Image icon = new javax.swing.ImageIcon(image_name).getImage();
                java.awt.MediaTracker md = new java.awt.MediaTracker(jComboBoxTemplates);
                md.addImage(icon,1);
                try {
                    md.waitForAll();
                } catch (Exception ex) {}
                this.jLabelImage.setIcon( new javax.swing.ImageIcon(icon) );
                
            }
            else
                this.jLabelImage.setIcon( null );

            this.jLabelImage.updateUI();       
            this.jButtonNext.setEnabled(true);
        }
        else
        {
            this.jLabelImage.setIcon( null );
            this.jButtonNext.setEnabled(false);
        }
    }//GEN-LAST:event_jList3ValueChanged

    private void jComboBoxTemplatesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTemplatesActionPerformed
        updateTemplatesList();
    }//GEN-LAST:event_jComboBoxTemplatesActionPerformed

    private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3ActionPerformed
                // Add to combobox 2 all not selected items...       
        Object obj1 = jComboBox1.getSelectedItem();
        Object obj2 = jComboBox2.getSelectedItem();
        Object obj3 = jComboBox3.getSelectedItem();
        if (jComboBox3.getSelectedIndex() <= 0)
        {
             disableGroups( 4 );
        }
        else
        {
            jComboBox4.setEnabled(true);
            jLabelG4.setEnabled(true);
            javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)jList2.getModel();
            jComboBox4.addItem("");
            for (int i=0; i<dlm.getSize(); ++i)
            {         
                 Object obj = dlm.getElementAt(i);
                 if (obj != obj1 && obj != obj2 && obj != obj3)
                     jComboBox4.addItem( obj );
            }           
        }
    }//GEN-LAST:event_jComboBox3ActionPerformed

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
        // Add to combobox 2 all not selected items...       
        Object obj1 = jComboBox1.getSelectedItem();
        Object obj2 = jComboBox2.getSelectedItem();
        if (jComboBox2.getSelectedIndex() <= 0)
        {
             disableGroups( 3 );
        }
        else
        {
            disableGroups( 4 );
            jComboBox3.setEnabled(true);
            jLabelG3.setEnabled(true);
            javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)jList2.getModel();
            jComboBox3.addItem("");
            for (int i=0; i<dlm.getSize(); ++i)
            {         
                 Object obj = dlm.getElementAt(i);
                 if (obj != obj1 && obj != obj2)
                     jComboBox3.addItem( obj );
            }           
        }
    }//GEN-LAST:event_jComboBox2ActionPerformed

    public void disableGroups(int fromIndex)
    {
        switch (fromIndex)
        {
            case 2:
                   jComboBox2.removeAllItems();
                   jComboBox2.setEnabled(false);
                   jLabelG2.setEnabled(false);
            case 3:
                   jComboBox3.removeAllItems();
                   jComboBox3.setEnabled(false);
                   jLabelG3.setEnabled(false);
            case 4:
                   jComboBox4.removeAllItems();
                   jComboBox4.setEnabled(false);
                   jLabelG4.setEnabled(false);
        }
    }
    
    
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        
        // Add to combobox 2 all not selected items...       
        Object obj1 = jComboBox1.getSelectedItem();
        if (jComboBox1.getSelectedIndex() <= 0)
        {
             disableGroups( 2 );
        }
        else
        {
            disableGroups( 3 );
            jComboBox2.setEnabled(true);
            jLabelG2.setEnabled(true);
            javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)jList2.getModel();
            jComboBox2.addItem("");
            for (int i=0; i<dlm.getSize(); ++i)
            {         
                 Object obj = dlm.getElementAt(i);
                 if (obj != obj1)
                     jComboBox2.addItem( obj );
            }           
        }
        
        
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        
        javax.swing.DefaultListModel list1 = (javax.swing.DefaultListModel)jList1.getModel();
        javax.swing.DefaultListModel list2 = (javax.swing.DefaultListModel)jList2.getModel();
        
        for (int i=0; i< list1.getSize(); ++i)
        {
            list2.addElement(list1.getElementAt(i));
        }
        list1.removeAllElements();
        if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
            jButtonNext.setEnabled(false);
        else
            jButtonNext.setEnabled(true);
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        int index = jList2.getSelectedIndex();
        if (index <0) return;
        
        Object obj = jList2.getSelectedValue();
        ((javax.swing.DefaultListModel)jList1.getModel()).addElement(obj);
        jButtonNext.setEnabled(true);
        ((javax.swing.DefaultListModel)jList2.getModel()).remove(index);
        if ( index < ((javax.swing.DefaultListModel)jList2.getModel()).getSize() )
            jList2.setSelectedIndex(index);
        else if (index-1 >= 0)
        {
            jList2.setSelectedIndex(index-1);
        }
        
        if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
            jButtonNext.setEnabled(false);
        else
            jButtonNext.setEnabled(true);
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        
        int index = jList1.getSelectedIndex();
        if (index <0) return;
        
        Object obj = jList1.getSelectedValue();
        ((javax.swing.DefaultListModel)jList2.getModel()).addElement(obj);
        jButtonNext.setEnabled(true);
        ((javax.swing.DefaultListModel)jList1.getModel()).remove(index);
        if ( index < ((javax.swing.DefaultListModel)jList1.getModel()).getSize() )
            jList1.setSelectedIndex(index);
        else if (index-1 >= 0)
        {
            jList1.setSelectedIndex(index-1);
        }
        if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
            jButtonNext.setEnabled(false);
        else
            jButtonNext.setEnabled(true);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        
        if (t != null && t.isAlive())
        {
            t.interrupt();
        }
        
        if (wzStep == 5)
        {
            //javax.swing.JOptionPane.showMessageDialog(null, ((TemplateFile)jList3.getSelectedValue()).file.getAbsolutePath()+"" );
            try {
                Report report = null;
                if (jComboBoxTemplates.getSelectedIndex() == 0)
                {
                    report = createColumnarReport( ((TemplateFile)jList3.getSelectedValue()).file.getAbsolutePath() );
                }
                else
                {
                    report = createTabularReport( ((TemplateFile)jList3.getSelectedValue()).file.getAbsolutePath() );
                }
                this.setReport(report);
                this.setDialogResult(javax.swing.JOptionPane.OK_OPTION);
            } catch (Exception ex)
            {
                java.io.StringWriter sw = new java.io.StringWriter();
                ex.printStackTrace(new java.io.PrintWriter( sw ));
                javax.swing.JOptionPane.showMessageDialog(null,sw.getBuffer()+"","Wizard Error", javax.swing.JOptionPane.ERROR_MESSAGE);
                return;
            }
        
        }
        else
            this.setDialogResult(javax.swing.JOptionPane.CANCEL_OPTION);
        
        this.setVisible(false);
        this.dispose();
        
    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void jButtonNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNextActionPerformed
        this.nextStep();
    }//GEN-LAST:event_jButtonNextActionPerformed

    private void jButtonPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPrevActionPerformed
         this.prevStep();
    }//GEN-LAST:event_jButtonPrevActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        javax.swing.DefaultListModel list2 = (javax.swing.DefaultListModel)jList1.getModel();
        javax.swing.DefaultListModel list1 = (javax.swing.DefaultListModel)jList2.getModel();
        
        for (int i=0; i< list1.getSize(); ++i)
        {
            list2.addElement(list1.getElementAt(i));
        }
        list1.removeAllElements();
        if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
            jButtonNext.setEnabled(false);
        else
            jButtonNext.setEnabled(true);
    }//GEN-LAST:event_jButton7ActionPerformed
    
    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        setVisible(false);
        dispose();
    }//GEN-LAST:event_closeDialog
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        new WizardDialog(new javax.swing.JFrame(), true).show();
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonNext;
    private javax.swing.JButton jButtonPrev;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JComboBox jComboBox4;
    private javax.swing.JComboBox jComboBoxTemplates;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabelG1;
    private javax.swing.JLabel jLabelG2;
    private javax.swing.JLabel jLabelG3;
    private javax.swing.JLabel jLabelG4;
    private javax.swing.JLabel jLabelImage;
    private javax.swing.JLabel jLabelStep1;
    private javax.swing.JLabel jLabelStep2;
    private javax.swing.JLabel jLabelStep3;
    private javax.swing.JLabel jLabelStep4;
    private javax.swing.JLabel jLabelStep5;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JList jList3;
    private javax.swing.JPanel jPanelRoot;
    private javax.swing.JPanel jPanelStep1;
    private javax.swing.JPanel jPanelStep2;
    private javax.swing.JPanel jPanelStep3;
    private javax.swing.JPanel jPanelStep4;
    private javax.swing.JPanel jPanelStep5;
    private it.businesslogic.ireport.gui.JRSQLExpressionArea jRSQLExpressionArea1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JSeparator jSeparator6;
    private javax.swing.JSeparator jSeparator7;
    // End of variables declaration//GEN-END:variables

    private int status;    
    
    private Report report;    
    
    private int dialogResult;
    
    public void nextStep()
    {
        this.setStep( wzStep+1, wzStep);
    }
    
    public void prevStep()
    {
        this.setStep(wzStep-1, wzStep);
    }
    
    
    public void setStep(int step, int oldStep)
    {
        jButtonCancel.setText("Cancel");
        switch (step)
        {
           case 1:                    
                setViewedPanel(1);
                if (jRSQLExpressionArea1.getText().trim().length() > 0)
                {
                    jButtonNext.setEnabled(true);
                }
                else
                    jButtonNext.setEnabled(false);
                
                jButtonPrev.setEnabled(false);
               break; 
           case 2:                    
                // Read fields.... 
                if (oldStep < step)
                {
                    // We must retrive fields...
                    jButtonNext.setEnabled(false);
                    t = new Thread(this);
                    t.start();
                    return;
                }
                setViewedPanel(2);
                
                if (  ((javax.swing.DefaultListModel)jList2.getModel()).getSize() == 0 )
                    jButtonNext.setEnabled(false);
                else
                    jButtonNext.setEnabled(true);
                
                jButtonPrev.setEnabled(true);
               break; 
           case 3:    
                if (oldStep < step)
                {
                    jComboBox1.removeAllItems();
                    jComboBox2.removeAllItems();
                    jComboBox2.setEnabled(false);
                    jLabelG2.setEnabled(false);
                    jComboBox3.removeAllItems();
                    jComboBox3.setEnabled(false);
                    jLabelG3.setEnabled(false);
                    jComboBox4.removeAllItems();
                    jComboBox4.setEnabled(false);
                    jLabelG4.setEnabled(false);
                    
                    javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)jList2.getModel();
                     jComboBox1.addItem("");
                    for (int i=0; i<dlm.getSize(); ++i)
                    {                       
                        jComboBox1.addItem( dlm.getElementAt(i));
                    }
                }
                setViewedPanel(3);
               break; 
           case 4:     
               
               jButtonNext.setEnabled( jList3.getSelectedIndex()>=0 );
                setViewedPanel(4);
               break; 
           case 5:                
                jButtonNext.setEnabled( false );
                jButtonCancel.setText("Finish");
                setViewedPanel(5);
               break; 
        }
        
        wzStep = step;
    }
    
    public void setViewedPanel(int panel)
    {
        this.jPanelRoot.removeAll();
        java.awt.Font f = new java.awt.Font( jLabelStep1.getFont().getName(), java.awt.Font.PLAIN, 11);
        java.awt.Font f2 = new java.awt.Font( jLabelStep1.getFont().getName(), java.awt.Font.BOLD, 11);
        this.jLabelStep1.setFont(f);
        this.jLabelStep2.setFont(f);
        this.jLabelStep3.setFont(f);
        this.jLabelStep4.setFont(f);
        this.jLabelStep5.setFont(f);
        
        switch (panel)
        {
           case 1:
                this.jPanelRoot.add(jPanelStep1);
                this.jLabelStep1.setFont(f2);
                break;
           case 2:
                
               
                this.jPanelRoot.add(jPanelStep2);
                this.jLabelStep2.setFont(f2);
                break;
           case 3:
                this.jPanelRoot.add(jPanelStep3);
                this.jLabelStep3.setFont(f2);
                break;
           case 4:
                this.jPanelRoot.add(jPanelStep4);
                this.jLabelStep4.setFont(f2);
                break;
           case 5:
                this.jPanelRoot.add(jPanelStep5);
                this.jLabelStep5.setFont(f2);
                break;
        }          
        
        jPanelRoot.updateUI();
    }
    
    /** When an object implementing interface <code>Runnable</code> is used
      * to create a thread, starting the thread causes the object's
      * <code>run</code> method to be called in that separately executing
      * thread.
      * <p>
      * The general contract of the method <code>run</code> is that it may
      * take any action whatsoever.
      *
      * @see     java.lang.Thread#run()
      *
      */
     public void run() {
         
         // This method is invoked to read fields....
         try {
                  IReportConnection irc = (IReportConnection)((MainFrame)this.getParent()).getProperties().get("DefaultConnection");
                  Connection c = irc.getConnection();
                  Statement stmt = c.createStatement();
                  ResultSet rs = stmt.executeQuery( jRSQLExpressionArea1.getText());
         
                  ((javax.swing.DefaultListModel)jList1.getModel()).removeAllElements();
                  ((javax.swing.DefaultListModel)jList2.getModel()).removeAllElements();
                 
                  ResultSetMetaData rsmd = rs.getMetaData();
	
                  javax.swing.DefaultListModel dlm1 =  (javax.swing.DefaultListModel)jList1.getModel();
                  javax.swing.DefaultListModel dlm2 =  (javax.swing.DefaultListModel)jList2.getModel();
                  
                  for (int i=1; i <=rsmd.getColumnCount(); ++i)
                  {
                    it.businesslogic.ireport.JRField field = new it.businesslogic.ireport.JRField(rsmd.getColumnName(i), Misc.getJdbcTypeClass(rsmd.getColumnType(i) ));
                    // Check if parameter already exists...
                    boolean found = false;
                    for (int k=0; i< dlm1.size(); ++k)
                    {
                        it.businesslogic.ireport.JRField f = (it.businesslogic.ireport.JRField)dlm1.getElementAt(k);
                        if (f.getName().equalsIgnoreCase(field.getName()))
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        //this.getJReportFrame().getReport().getFields().addElement(field);
                        dlm1.addElement(field);
                    }
                  }
                  setStep(2, 2);
                  
         } catch (Exception ex)
         {
            java.io.StringWriter sw = new java.io.StringWriter();
            ex.printStackTrace(new java.io.PrintWriter( sw ));
            javax.swing.JOptionPane.showMessageDialog(null,sw.getBuffer()+"","SQL Error", javax.swing.JOptionPane.ERROR_MESSAGE);
            this.cancelElaborationStep1();
            return;
         }
         
         
     }
     
     public void cancelElaborationStep1()
     {
         this.jButtonNext.setEnabled(true);
         this.jButtonPrev.setEnabled(false);
     }
     
     
     /*
      *
      *
      */
     public Report createTabularReport(String templateFileName)
     {
        Report template = new Report(templateFileName);
         
        template.setDirty(true);
        template.setFilename(null);
         
         //2. Find detail and column header bands...
	Band detail=null;
	Band columns=null;
				
	Enumeration enum = template.getBands().elements();
	while (enum.hasMoreElements())
	{
            Band band = (Band)enum.nextElement();
		if (band.getName().equals("detail"))
		{
			detail = band;
		}
		else if (band.getName().equals("columnHeader"))
		{
			columns = band;
		}
	}
         
        // 1. Normalize position to band...
	enum = template.getElements().elements();
	while (enum.hasMoreElements())
	{
            ReportElement rElement = (ReportElement)enum.nextElement();
            rElement.trasform(new java.awt.Point(0,- template.getBandYLocation( rElement.getBand() )),TransformationType.TRANSFORMATION_MOVE );  
	}
        
        //1. Adding groups...
	if (this.jComboBox1.getSelectedIndex() > 0)
	{
		Group g = template.getGroupByName("Group1");
		Group g1 = new Group( template, ""+jComboBox1.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
		g1.setGroupExpression("$F{"+ jComboBox1.getSelectedItem() + "}" );
		template.addGroup(g1);
					
		// Add to g1 all elements attached to g.header and g.footer...
		enum = template.getElements().elements();
		while (enum.hasMoreElements())
		{
			ReportElement rElement = (ReportElement)enum.nextElement();
			if (rElement.getBand() == g.getGroupHeader())
          			rElement.setBand(g1.getGroupHeader() );
			else if (rElement.getBand() == g.getGroupFooter())
				rElement.setBand(g1.getGroupFooter() );
			// Set text to Group1 label...
			if (rElement instanceof StaticTextReportElement)
			{
				StaticTextReportElement stre = (StaticTextReportElement)rElement;
				if (stre.getText().equals("G1Label"))
					stre.setText( ""+jComboBox1.getSelectedItem());
			}
			else if (rElement instanceof TextFieldReportElement)
			{
				TextFieldReportElement tfre = (TextFieldReportElement)rElement;
				if (tfre.getText().equals("G1Field"))
					tfre.setText("$F{"+jComboBox1.getSelectedItem()+"}");
			}
		}
	}
           
	if (this.jComboBox2.getSelectedIndex() > 0)
	{
		Group g = template.getGroupByName("Group2");
		Group g2 = new Group( template, ""+jComboBox2.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
		g2.setGroupExpression("$F{"+ jComboBox2.getSelectedItem() + "}" );
		template.addGroup(g2);
					
		// Add to g2 all elements attached to g.header and g.footer...
		enum = template.getElements().elements();
		while (enum.hasMoreElements())
		{
			ReportElement rElement = (ReportElement)enum.nextElement();
			if (rElement.getBand() == g.getGroupHeader())
          			rElement.setBand(g2.getGroupHeader() );
			else if (rElement.getBand() == g.getGroupFooter())
				rElement.setBand(g2.getGroupFooter() );
			// Set text to Group2 label...
			if (rElement instanceof StaticTextReportElement)
			{
				StaticTextReportElement stre = (StaticTextReportElement)rElement;
				if (stre.getText().equals("G2Label"))
					stre.setText( ""+jComboBox2.getSelectedItem());
			}
			else if (rElement instanceof TextFieldReportElement)
			{
				TextFieldReportElement tfre = (TextFieldReportElement)rElement;
				if (tfre.getText().equals("G2Field"))
					tfre.setText("$F{"+jComboBox2.getSelectedItem()+"}");
			}
		}
	}
        
        if (this.jComboBox3.getSelectedIndex() > 0)
	{
		Group g = template.getGroupByName("Group3");
		Group g3 = new Group( template, ""+jComboBox3.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
		g3.setGroupExpression("$F{"+ jComboBox3.getSelectedItem() + "}" );
		template.addGroup(g3);
					
		// Add to g3 all elements attached to g.header and g.footer...
		enum = template.getElements().elements();
		while (enum.hasMoreElements())
		{
			ReportElement rElement = (ReportElement)enum.nextElement();
			if (rElement.getBand() == g.getGroupHeader())
          			rElement.setBand(g3.getGroupHeader() );
			else if (rElement.getBand() == g.getGroupFooter())
				rElement.setBand(g3.getGroupFooter() );
			// Set text to Group3 label...
			if (rElement instanceof StaticTextReportElement)
			{
				StaticTextReportElement stre = (StaticTextReportElement)rElement;
				if (stre.getText().equals("G3Label"))
					stre.setText( ""+jComboBox3.getSelectedItem());
			}
			else if (rElement instanceof TextFieldReportElement)
			{
				TextFieldReportElement tfre = (TextFieldReportElement)rElement;
				if (tfre.getText().equals("G3Field"))
					tfre.setText("$F{"+jComboBox3.getSelectedItem()+"}");
			}
		}
	}
        
        if (this.jComboBox4.getSelectedIndex() > 0)
	{
		Group g = template.getGroupByName("Group4");
		Group g4 = new Group( template, ""+jComboBox4.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
		g4.setGroupExpression("$F{"+ jComboBox4.getSelectedItem() + "}" );
		template.addGroup(g4);
					
		// Add to g4 all elements attached to g.header and g.footer...
		enum = template.getElements().elements();
		while (enum.hasMoreElements())
		{
			ReportElement rElement = (ReportElement)enum.nextElement();
			if (rElement.getBand() == g.getGroupHeader())
          			rElement.setBand(g4.getGroupHeader() );
			else if (rElement.getBand() == g.getGroupFooter())
				rElement.setBand(g4.getGroupFooter() );
			// Set text to Group4 label...
			if (rElement instanceof StaticTextReportElement)
			{
				StaticTextReportElement stre = (StaticTextReportElement)rElement;
				if (stre.getText().equals("G4Label"))
					stre.setText( ""+jComboBox4.getSelectedItem());
			}
			else if (rElement instanceof TextFieldReportElement)
			{
				TextFieldReportElement tfre = (TextFieldReportElement)rElement;
				if (tfre.getText().equals("G4Field"))
					tfre.setText("$F{"+jComboBox4.getSelectedItem()+"}");
			}
		}
	}
        
        //1. Adding fields...
        int currentx = template.getLeftMargin()+10;
	int currenty = 10;
	enum = template.getElements().elements();
	StaticTextReportElement detailLabel = null;
	TextFieldReportElement detailField = null;
	while (enum.hasMoreElements() && (detailLabel==null || detailField == null) )
        {
		ReportElement rElement = (ReportElement)enum.nextElement();
		if (rElement instanceof StaticTextReportElement)
		{
			StaticTextReportElement stre = (StaticTextReportElement)rElement;
			if (stre.getText().equalsIgnoreCase("DetailLabel"))
                		detailLabel =stre;
		}
		else if (rElement instanceof TextFieldReportElement)
		{
			TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                        if (tfre.getText().equalsIgnoreCase("DetailField"))
					detailField = tfre;
		}
	}
        
        if (detailField != null)
		template.getElements().removeElement(detailField);
	if (detailLabel != null)
		template.getElements().removeElement(detailLabel);
	
	if (detailField == null)
		detailField = new TextFieldReportElement(0,0,100,20); 
	if (detailLabel == null)
		detailLabel = new StaticTextReportElement(0,0,100,18); 
				
	int nfields = jList2.getModel().getSize(); 
	if (jComboBox1.getSelectedIndex()>0) nfields--;
        if (jComboBox2.getSelectedIndex()>0) nfields--;
        if (jComboBox3.getSelectedIndex()>0) nfields--;
        if (jComboBox4.getSelectedIndex()>0) nfields--;

        int fwidth = template.getColumnWidth()/nfields;
				
	for (int i=0; i<jList2.getModel().getSize(); ++i)
	{
		// FIELD
		it.businesslogic.ireport.JRField f = (it.businesslogic.ireport.JRField)jList2.getModel().getElementAt(i);
		template.getFields().addElement(f);
					
		if (jComboBox1.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox1.getSelectedItem() ))
				continue;
		if (jComboBox2.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox2.getSelectedItem() ))
				continue;
		if (jComboBox3.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox3.getSelectedItem() ))
				continue;
                if (jComboBox4.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox4.getSelectedItem() ))
				continue;
                
                
		TextFieldReportElement re = (TextFieldReportElement)detailField.cloneMe();
                re.setPosition(new java.awt.Point(currentx,detailField.getPosition().y));
                re.setWidth( fwidth);
                re.updateBounds();
             	re.setText("$F{"+ f.getName() +"}");
                
		re.setBand(detail);
		re.setClassExpression(f.getClassType());
		template.getElements().addElement(re);
					
		// COLUMN LABEL...
		StaticTextReportElement sre = (StaticTextReportElement)detailLabel.cloneMe();
                sre.setPosition(new java.awt.Point(currentx,detailLabel.getPosition().y));
                sre.setWidth(fwidth);
                sre.updateBounds();
                sre.setText(""+ f.getName() +"");
                sre.setBand(columns);
		template.getElements().addElement(sre);
					
		currentx += fwidth;
		currentx = Math.min(template.getWidth() - template.getRightMargin()+10-30, currentx);
	}
        
        // Remove template groups...****************
	enum = template.getElements().elements();
	Vector elements_to_delete = new Vector();
	while (enum.hasMoreElements())
	{
		ReportElement rElement = (ReportElement)enum.nextElement();
		Group g = null;
		if ((g=template.getGroupByName("Group1"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
			elements_to_delete.addElement(rElement);
		else if ((g=template.getGroupByName("Group2"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
			elements_to_delete.addElement(rElement);
		else if ((g=template.getGroupByName("Group3"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
			elements_to_delete.addElement(rElement);
		else if ((g=template.getGroupByName("Group4"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
			elements_to_delete.addElement(rElement);
	}
	enum =elements_to_delete.elements();
	while (enum.hasMoreElements())
	{
		template.getElements().removeElement(enum.nextElement());
	}
	
        Group g;
	if ((g=template.getGroupByName("Group1"))!=null)
	{
		template.getBands().removeElement(g.getGroupFooter());
		template.getBands().removeElement(g.getGroupHeader());
		template.getGroups().removeElement(g);
	}
	if ((g=template.getGroupByName("Group2"))!=null)
	{
		template.getBands().removeElement(g.getGroupFooter());
		template.getBands().removeElement(g.getGroupHeader());
		template.getGroups().removeElement(g);
        }
	if ((g=template.getGroupByName("Group3"))!=null)
	{
		template.getBands().removeElement(g.getGroupFooter());
		template.getBands().removeElement(g.getGroupHeader());
		template.getGroups().removeElement(g);
	}
	
        if ((g=template.getGroupByName("Group4"))!=null)
	{
		template.getBands().removeElement(g.getGroupFooter());
		template.getBands().removeElement(g.getGroupHeader());
		template.getGroups().removeElement(g);
	}
				
	// Positioning columns band...
	/*
        if ((g=template.getGroupByName("Columns"))!=null)
	{
		template.getGroups().removeElement(g);
		template.getBands().removeElement(g.getGroupHeader());
		template.getBands().removeElement(g.getGroupFooter());
		template.addGroup(g);
		// we must adjust band position...
	}
        */
	// Adjust vertical position of elements
	enum = template.getElements().elements();
	while (enum.hasMoreElements())
	{
		ReportElement rElement = (ReportElement)enum.nextElement();
		rElement.trasform(new java.awt.Point(0,+ template.getBandYLocation( rElement.getBand() )),TransformationType.TRANSFORMATION_MOVE );
	}
				
	template.setQuery( jRSQLExpressionArea1.getText() );
				
	return template;				
     }
     
     /**********************************************************
      *
      */
     public Report createColumnarReport(String templateFileName)
     {
        Report template = new Report(templateFileName);
         
        template.setDirty(true);
        template.setFilename(null);
         
         //2. Find detail and column header bands...
	Band detail=null;
	Band columns=null;
				
	Enumeration enum = template.getBands().elements();
	while (enum.hasMoreElements())
	{
            Band band = (Band)enum.nextElement();
		if (band.getName().equals("detail"))
		{
			detail = band;
		}
		else if (band.getName().equals("columnHeader"))
		{
			columns = band;
		}
	}
         
        // 1. Normalize position to band...
	enum = template.getElements().elements();
	while (enum.hasMoreElements())
	{
            ReportElement rElement = (ReportElement)enum.nextElement();
            rElement.trasform(new java.awt.Point(0,- template.getBandYLocation( rElement.getBand() )),TransformationType.TRANSFORMATION_MOVE );  
	}
        
        //1. Adding groups...
	if (this.jComboBox1.getSelectedIndex() > 0)
	{
		Group g = template.getGroupByName("Group1");
		Group g1 = new Group( template, ""+jComboBox1.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
		g1.setGroupExpression("$F{"+ jComboBox1.getSelectedItem() + "}" );
		template.addGroup(g1);
					
		// Add to g1 all elements attached to g.header and g.footer...
		enum = template.getElements().elements();
		while (enum.hasMoreElements())
		{
			ReportElement rElement = (ReportElement)enum.nextElement();
			if (rElement.getBand() == g.getGroupHeader())
          			rElement.setBand(g1.getGroupHeader() );
			else if (rElement.getBand() == g.getGroupFooter())
				rElement.setBand(g1.getGroupFooter() );
			// Set text to Group1 label...
			if (rElement instanceof StaticTextReportElement)
			{
				StaticTextReportElement stre = (StaticTextReportElement)rElement;
				if (stre.getText().equals("G1Label"))
					stre.setText( ""+jComboBox1.getSelectedItem());
			}
			else if (rElement instanceof TextFieldReportElement)
			{
				TextFieldReportElement tfre = (TextFieldReportElement)rElement;
				if (tfre.getText().equals("G1Field"))
					tfre.setText("$F{"+jComboBox1.getSelectedItem()+"}");
			}
		}
	}
           
	if (this.jComboBox2.getSelectedIndex() > 0)
	{
		Group g = template.getGroupByName("Group2");
		Group g2 = new Group( template, ""+jComboBox2.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
		g2.setGroupExpression("$F{"+ jComboBox2.getSelectedItem() + "}" );
		template.addGroup(g2);
					
		// Add to g2 all elements attached to g.header and g.footer...
		enum = template.getElements().elements();
		while (enum.hasMoreElements())
		{
			ReportElement rElement = (ReportElement)enum.nextElement();
			if (rElement.getBand() == g.getGroupHeader())
          			rElement.setBand(g2.getGroupHeader() );
			else if (rElement.getBand() == g.getGroupFooter())
				rElement.setBand(g2.getGroupFooter() );
			// Set text to Group2 label...
			if (rElement instanceof StaticTextReportElement)
			{
				StaticTextReportElement stre = (StaticTextReportElement)rElement;
				if (stre.getText().equals("G2Label"))
					stre.setText( ""+jComboBox2.getSelectedItem());
			}
			else if (rElement instanceof TextFieldReportElement)
			{
				TextFieldReportElement tfre = (TextFieldReportElement)rElement;
				if (tfre.getText().equals("G2Field"))
					tfre.setText("$F{"+jComboBox2.getSelectedItem()+"}");
			}
		}
	}
        
        if (this.jComboBox3.getSelectedIndex() > 0)
	{
		Group g = template.getGroupByName("Group3");
		Group g3 = new Group( template, ""+jComboBox3.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
		g3.setGroupExpression("$F{"+ jComboBox3.getSelectedItem() + "}" );
		template.addGroup(g3);
					
		// Add to g3 all elements attached to g.header and g.footer...
		enum = template.getElements().elements();
		while (enum.hasMoreElements())
		{
			ReportElement rElement = (ReportElement)enum.nextElement();
			if (rElement.getBand() == g.getGroupHeader())
          			rElement.setBand(g3.getGroupHeader() );
			else if (rElement.getBand() == g.getGroupFooter())
				rElement.setBand(g3.getGroupFooter() );
			// Set text to Group3 label...
			if (rElement instanceof StaticTextReportElement)
			{
				StaticTextReportElement stre = (StaticTextReportElement)rElement;
				if (stre.getText().equals("G3Label"))
					stre.setText( ""+jComboBox3.getSelectedItem());
			}
			else if (rElement instanceof TextFieldReportElement)
			{
				TextFieldReportElement tfre = (TextFieldReportElement)rElement;
				if (tfre.getText().equals("G3Field"))
					tfre.setText("$F{"+jComboBox3.getSelectedItem()+"}");
			}
		}
	}
        
        if (this.jComboBox4.getSelectedIndex() > 0)
	{
		Group g = template.getGroupByName("Group4");
		Group g4 = new Group( template, ""+jComboBox4.getSelectedItem(),  g.getGroupFooter().getHeight(),g.getGroupHeader().getHeight());
		g4.setGroupExpression("$F{"+ jComboBox4.getSelectedItem() + "}" );
		template.addGroup(g4);
					
		// Add to g4 all elements attached to g.header and g.footer...
		enum = template.getElements().elements();
		while (enum.hasMoreElements())
		{
			ReportElement rElement = (ReportElement)enum.nextElement();
			if (rElement.getBand() == g.getGroupHeader())
          			rElement.setBand(g4.getGroupHeader() );
			else if (rElement.getBand() == g.getGroupFooter())
				rElement.setBand(g4.getGroupFooter() );
			// Set text to Group4 label...
			if (rElement instanceof StaticTextReportElement)
			{
				StaticTextReportElement stre = (StaticTextReportElement)rElement;
				if (stre.getText().equals("G4Label"))
					stre.setText( ""+jComboBox4.getSelectedItem());
			}
			else if (rElement instanceof TextFieldReportElement)
			{
				TextFieldReportElement tfre = (TextFieldReportElement)rElement;
				if (tfre.getText().equals("G4Field"))
					tfre.setText("$F{"+jComboBox4.getSelectedItem()+"}");
			}
		}
	}
        
        //1. Adding fields...
        int currentx = template.getLeftMargin()+10;
	int currenty = 10;
	enum = template.getElements().elements();
	StaticTextReportElement detailLabel = null;
	TextFieldReportElement detailField = null;
	while (enum.hasMoreElements() && (detailLabel==null || detailField == null) )
        {
		ReportElement rElement = (ReportElement)enum.nextElement();
		if (rElement instanceof StaticTextReportElement)
		{
			StaticTextReportElement stre = (StaticTextReportElement)rElement;
			if (stre.getText().equalsIgnoreCase("DetailLabel"))
                		detailLabel =stre;
		}
		else if (rElement instanceof TextFieldReportElement)
		{
			TextFieldReportElement tfre = (TextFieldReportElement)rElement;
                        if (tfre.getText().equalsIgnoreCase("DetailField"))
					detailField = tfre;
		}
	}
        
        if (detailField != null)
		template.getElements().removeElement(detailField);
	if (detailLabel != null)
		template.getElements().removeElement(detailLabel);
	
	if (detailField == null)
		detailField = new TextFieldReportElement(0,0,100,20); 
	if (detailLabel == null)
		detailLabel = new StaticTextReportElement(0,0,100,18); 
				
	int nfields = jList2.getModel().getSize(); 
	if (jComboBox1.getSelectedIndex()>0) nfields--;
        if (jComboBox2.getSelectedIndex()>0) nfields--;
        if (jComboBox3.getSelectedIndex()>0) nfields--;
        if (jComboBox4.getSelectedIndex()>0) nfields--;

        int fwidth = template.getColumnWidth()/nfields;
	int ffheight =  detailField.getPosition().y;
        
	for (int i=0; i<jList2.getModel().getSize(); ++i)
	{
		// FIELD
		it.businesslogic.ireport.JRField f = (it.businesslogic.ireport.JRField)jList2.getModel().getElementAt(i);
		template.getFields().addElement(f);
					
		if (jComboBox1.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox1.getSelectedItem() ))
				continue;
		if (jComboBox2.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox2.getSelectedItem() ))
				continue;
		if (jComboBox3.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox3.getSelectedItem() ))
				continue;
                if (jComboBox4.getSelectedIndex()>0 && f.getName().equalsIgnoreCase( ""+jComboBox4.getSelectedItem() ))
				continue;
                
                
		TextFieldReportElement re = (TextFieldReportElement)detailField.cloneMe();
                re.setPosition(new java.awt.Point(detailField.getPosition().x, ffheight));
                re.updateBounds();
             	re.setText("$F{"+ f.getName() +"}");
                
		re.setBand(detail);
		re.setClassExpression(f.getClassType());
		template.getElements().addElement(re);
					
		// COLUMN LABEL...
		StaticTextReportElement sre = (StaticTextReportElement)detailLabel.cloneMe();
                sre.setPosition(new java.awt.Point(detailLabel.getPosition().x,ffheight));
                sre.setWidth(fwidth);
                sre.updateBounds();
                sre.setText(""+ f.getName() +"");
                sre.setBand(detail);
		template.getElements().addElement(sre);
					
		ffheight +=  detailField.position.y+detailField.height-10;	
	}
        
        detail.setHeight(ffheight);
        
        // Remove template groups...****************
	enum = template.getElements().elements();
	Vector elements_to_delete = new Vector();
	while (enum.hasMoreElements())
	{
		ReportElement rElement = (ReportElement)enum.nextElement();
		Group g = null;
		if ((g=template.getGroupByName("Group1"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
			elements_to_delete.addElement(rElement);
		else if ((g=template.getGroupByName("Group2"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
			elements_to_delete.addElement(rElement);
		else if ((g=template.getGroupByName("Group3"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
			elements_to_delete.addElement(rElement);
		else if ((g=template.getGroupByName("Group4"))!=null && (rElement.getBand() == g.getGroupHeader() || rElement.getBand() == g.getGroupFooter()))
			elements_to_delete.addElement(rElement);
	}
	enum =elements_to_delete.elements();
	while (enum.hasMoreElements())
	{
		template.getElements().removeElement(enum.nextElement());
	}
	
        Group g;
	if ((g=template.getGroupByName("Group1"))!=null)
	{
		template.getBands().removeElement(g.getGroupFooter());
		template.getBands().removeElement(g.getGroupHeader());
		template.getGroups().removeElement(g);
	}
	if ((g=template.getGroupByName("Group2"))!=null)
	{
		template.getBands().removeElement(g.getGroupFooter());
		template.getBands().removeElement(g.getGroupHeader());
		template.getGroups().removeElement(g);
        }
	if ((g=template.getGroupByName("Group3"))!=null)
	{
		template.getBands().removeElement(g.getGroupFooter());
		template.getBands().removeElement(g.getGroupHeader());
		template.getGroups().removeElement(g);
	}
	
        if ((g=template.getGroupByName("Group4"))!=null)
	{
		template.getBands().removeElement(g.getGroupFooter());
		template.getBands().removeElement(g.getGroupHeader());
		template.getGroups().removeElement(g);
	}
				
	// Positioning columns band...
	/*
        if ((g=template.getGroupByName("Columns"))!=null)
	{
		template.getGroups().removeElement(g);
		template.getBands().removeElement(g.getGroupHeader());
		template.getBands().removeElement(g.getGroupFooter());
		template.addGroup(g);
		// we must adjust band position...
	}
        */
	// Adjust vertical position of elements
	enum = template.getElements().elements();
	while (enum.hasMoreElements())
	{
		ReportElement rElement = (ReportElement)enum.nextElement();
		rElement.trasform(new java.awt.Point(0,+ template.getBandYLocation( rElement.getBand() )),TransformationType.TRANSFORMATION_MOVE );
	}
				
	template.setQuery( jRSQLExpressionArea1.getText() );
				
	return template;				
     }
     
     
     /** Getter for property dialogResult.
      * @return Value of property dialogResult.
      *
      */
     public int getDialogResult() {
         return dialogResult;
     }
     
     /** Setter for property dialogResult.
      * @param dialogResult New value of property dialogResult.
      *
      */
     public void setDialogResult(int dialogResult) {
         this.dialogResult = dialogResult;
     }
     
     /** Getter for property report.
      * @return Value of property report.
      *
      */
     public it.businesslogic.ireport.Report getReport() {
         return report;
     }
     
     /** Setter for property report.
      * @param report New value of property report.
      *
      */
     public void setReport(it.businesslogic.ireport.Report report) {
         this.report = report;
     }
     
}

class TemplateFile {
 
    public File file = null;
    public String name = "";
    public String toString() { return name; }
}
