 /*
 */
package usda.weru.soil;

import de.schlichtherle.io.File;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.beans.*;
import java.io.FileNotFoundException;
import javax.help.*;
import java.lang.ClassLoader.*;
import usda.weru.util.*;

//main() is in this function
public class Soil extends usda.weru.soil.gui.SoilUI_n implements PropertyChangeListener //implements ActionListener ,ItemListener
//public class SoilUI extends SoilUI_n implements ActionListener ,ItemListener
//,HelpDelegator
//,ItemListener
{

    static {
        openSoilWindows = new Vector<Soil>();
    }
    static Vector<Soil> openSoilWindows;

    public static boolean isOpen() {
        return Soil.openSoilWindows.size() > 0;
    }
    public static final String WindowClosing = "Soil-WindowClosing";
    IFC ifcptr;    //variables for help system
    public HelpBroker hb_soil;
    private String projectsPath = "";
    String inputSoilName;
    String viewitem;
    String dbName = "";
    String prjName = "";
    private String soiluiid = "WEPS Soil User Interface";
    private boolean selFlg;
    private boolean c_readonly = false;
    Grid GridID = null;
    Grid GridSurfProp = null;
    Grid GridLayrProp = null;
//	JPanel tables;

    /**
     *
     * @param fileName
     */
    public Soil(String fileName) {
        this(fileName, "", "");
    }

    /**
     *
     * @param fileName
     * @param prjName
     * @param dbName
     * @param changes
     */
    public Soil(String fileName, String prjName, String dbName) {
        super();
        if (Soil.openSoilWindows.contains(this) == false) {
            Soil.openSoilWindows.add(this);
        }
        this.prjName = prjName;
        this.dbName = dbName;
        this.changes = new PropertyChangeSupport(this);


        inputSoilName = fileName;

        setResizable(true);

        setLocation(50, 50);
        //setSize(getInsets().left + getInsets().right + monitorSize.width - 100,getInsets().top + getInsets().bottom + 530);

//		tables = new JPanel();
        Dimension d = getSize();
        d.height -= 60;
        d.width -= 10;
        setTitle(soiluiid + "Initial Field Conditions " + inputSoilName);
        //Setting the Icon Image in the title bar
        super.setIconImage(About.getWeruIconImage());

        ifcptr = new IFC();
        try {
            ifcptr.readIfc(inputSoilName);
            setMenuEnable("Save", true);
            setMenuEnable("Save As", true);
            setMenuEnable("print", true);
        } catch (FileNotFoundException e) {
        }

        addPopupMenu();
        viewLayers();
        repaint();
        validate();
        Util.loadToolTips((Container) this, new File("cfg", "soiltooltips.cfg"));
//        addHelp();
    }

    @Override
    public void setVisible(boolean b) {
        if (inputSoilName == null || inputSoilName.trim().length() == 0) {
            newFile();
        }
        super.setVisible(b);
    }

    private void commitEdits() {
        GridID.commitEdit(true);
        GridLayrProp.commitEdit(true);
        GridSurfProp.commitEdit(true);
    }

    public void setReadonly(boolean readonly) {
        if (readonly) {
            Soil.openSoilWindows.remove(this);
        } else {
            if (Soil.openSoilWindows.contains(this) == false) {
                Soil.openSoilWindows.add(this);
            }
        }
        c_readonly = readonly;
        //Buttons
        JB_open.setEnabled(!readonly);
        JB_open.setVisible(!readonly);
        JB_save.setEnabled(!readonly);
        JB_save.setVisible(!readonly);
        JB_copy.setEnabled(!readonly);
        JB_copy.setVisible(!readonly);
        JB_cut.setEnabled(!readonly);
        JB_cut.setVisible(!readonly);
        JB_paste.setEnabled(!readonly);
        JB_paste.setVisible(!readonly);
        openItem.setEnabled(!readonly);
        openItem.setVisible(!readonly);

        //Menus
        M_edit.setEnabled(!readonly);
        M_edit.setVisible(!readonly);

        //Menu Items
        newItem.setEnabled(!readonly);
        newItem.setVisible(!readonly);
        saveAsItem.setEnabled(!readonly);
        saveAsItem.setVisible(!readonly);
        saveItem.setVisible(!readonly);
        saveItem.setVisible(!readonly);
        openRemoteDB.setEnabled(!readonly);
        openRemoteDB.setVisible(!readonly);        

        //Pass to tables
        if(GridID != null){
            GridID.setReadonly(readonly);
        }
        if(GridLayrProp != null){
            GridLayrProp.setReadonly(readonly);
        }
        if(GridSurfProp != null){
            GridSurfProp.setReadonly(readonly);
        }

    }

    public boolean getReadonly() {
        return c_readonly;
    }

    /************************************************************************ wjr*/
    private void setupLayout() {
        GridBagLayout gbl = new GridBagLayout();
        gbl.rowHeights = new int[20];
        for (int idx = 0; idx < gbl.rowHeights.length; idx++) {
            gbl.rowHeights[idx] = 25;
        }
        gbl.columnWidths = new int[1];
        Dimension d = getSize();
        Util.debugPrint("sL: " + d.width);
        gbl.columnWidths[0] = d.width - 20;
    }

    /*****************************************************************************/
    /*
    public synchronized void show()
    {
    setLocation(50, 50);
    super.setVisible(true);
    }
     */
    /*****************************************************************************/
    protected void newFile() {
        inputSoilName = "";
        setMenuEnable("Save", false);
        setMenuEnable("Save As", true);
        setMenuEnable("print", true);
        setTitle(soiluiid + "Initial Field Conditions New File");
        ifcptr = new IFC(1);
        viewLayers();
        if (JB_estimate.isVisible()) {
            selFlg = true;
            JB_estimate.setEnabled(selFlg);
            if (GridLayrProp != null) {
                GridID.displayColumns("select");
                GridSurfProp.displayColumns("select");
                GridLayrProp.displayColumns("select");
            }
            all.setState(!selFlg);
            select.setState(selFlg);
        }
    }

    /*****************************************************************************/
    protected void openFile() {

        WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.SOIL,
                projectsPath,
                WepsFileChooser.OPEN);
        wfc.disableNewFolder(wfc);
        wfc.setCurrentDirectory(new de.schlichtherle.io.File((new File(projectsPath)).getAbsolutePath()));
        if (wfc.showDialog(this) == JFileChooser.APPROVE_OPTION) {
            inputSoilName = wfc.getSelectedFile().getAbsolutePath();
            //			changes.firePropertyChange(RunFileData.SoilFile, null,
            //									   wfc.getSelectedFile().getCanonicalPath());
            setMenuEnable("Save", true);
            setMenuEnable("Save As", true);
            setMenuEnable("print", true);
            setTitle(soiluiid + "Initial Field Conditions " + inputSoilName);
            ifcptr = new IFC();
            try {
                ifcptr.readIfc(inputSoilName);
                viewLayers();
            } catch (java.io.FileNotFoundException e) {
                //System.err.println("S_oF: " + e);
            }
        }
    }

    /*****************************************************************************/
    public void progExit() {
        Soil.openSoilWindows.remove(this);
        if (changes != null) {
            changes.firePropertyChange(WindowClosing, null, "true");
        }
        dispose();
        Util.debugPrint("exit called");
    }

    /*****************************************************************************/
    public void saveIfc() {
        commitEdits();
        Util.debugPrint(true, "<< " + inputSoilName);
        String dir = "";
        String outputSoilNm = "";
        if (ifcptr != null && inputSoilName != null) {
            int index = inputSoilName.lastIndexOf('\\');
            if (index > 0) {
                dir = inputSoilName.substring(0, index);
                outputSoilNm = inputSoilName.substring(index);
            }
            Util.debugPrint("SoilUI : saveIfc : Dir name is : " + dir);
            Util.debugPrint("SoilUI : saveIfc : Soil Name ONLY is : " + outputSoilNm);
            Util.debugPrint("SoilUI : saveIfc : Soil Name is : " + inputSoilName);
            ifcptr.writeNewIfc(new File(dir, outputSoilNm).getAbsolutePath(), changes);
//			changes.firePropertyChange(usda.weru.weps.RunFileData.SoilFile, null, outputSoilNm);
        }
    }

    /*****************************************************************************/
    public void saveAsIfc() {
        commitEdits();
        WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.SOIL, projectsPath,
                WepsFileChooser.SAVE);
        Util.debugPrint(true, "saveAs directory: " + projectsPath);
        Util.debugPrint(true, "saveAs directory: " + prjName);
//		wfc.setCurrentDirectory(new de.schlichtherle.io.File(projectsPath));
        wfc.setCurrentDirectory(new de.schlichtherle.io.File(prjName));
        File soilFile = new File(prjName, inputSoilName);
        wfc.setPersitSelectedFile(true);
        wfc.setSelectedFile(soilFile);
        wfc.setText(soilFile.getName());
        if (wfc.showDialog(this) == JFileChooser.APPROVE_OPTION) {
            inputSoilName = wfc.getSelectedFile().getAbsolutePath();
            if (ifcptr != null && inputSoilName != null) {
                ifcptr.writeNewIfc(inputSoilName, changes);
                setTitle(soiluiid + "  " + inputSoilName);
//				changes.firePropertyChange(usda.weru.weps.RunFileData.SoilFile, null, inputSoilNm);
            } else {
            }
        }
    }

    /*****************************************************************************/
    void getSQL() {
        if (dbName.length() == 0) {
            dbName = JOptionPane.showInputDialog(this, "Enter database name (" + this.dbName + ")");
            if (dbName.length() == 0) {
                Util.debugPrint("SUI_gSQL: return null");
                return;
            }
        }
//        if (dbName.trim().length() == 0) {
//            dbName = this.dbName;
//        }

//        SQLTree sqlt = new SQLTree("Select SSURGO Soil", dbName, this);
//        sqlt.setSize(new Dimension(400,400));
//        sqlt.setVisible(true);
        SoilChooser sc = new SoilChooser(this, new File(prjName), new File(dbName), changes);
        sc.setVisible(true);
    }
    /*****************************************************************************/
    // following are cut and paste fix to make soil mart data work
    String workingDirectory = "sweep";
    String soilDB = "db/soil";
    static private String cfgFile = "cfg/sweep.cfg";
    SoilChooser c_soilChooser = null;

    protected void openRemoteDBActionPerformed(java.awt.event.ActionEvent evt) {
        if (c_soilChooser == null) {
            System.out.println("soilDB " + (new File(soilDB)).getAbsolutePath());
            System.out.println("working " + (new File(workingDirectory)).getAbsolutePath());
            c_soilChooser = new SoilChooser(this, new File(workingDirectory), new File(soilDB), changes);
        }
        c_soilChooser.setSize(new java.awt.Dimension(500, 500));
        c_soilChooser.setVisible(true);
        // TODO add your handling code here:
    }

    /*****************************************************************************/
    protected void editCut() {
        if (GridLayrProp.showPopup()) {
            GridLayrProp.cutRow();
            //	pack();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Entire row should be selected", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    /*****************************************************************************/
    protected void editCopy() {
        if (GridLayrProp.showPopup()) {
            GridLayrProp.copyRow();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Entire row should be selected", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    /*****************************************************************************/
    protected void editBeforePaste() {
        if (GridLayrProp.showPopup()) {
            GridLayrProp.pasteBeforeRow();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Entire row should be selected", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    /*****************************************************************************/
    protected void editAfterPaste() {
        if (GridLayrProp.showPopup()) {
            GridLayrProp.pasteAfterRow();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Entire row should be selected", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    /*****************************************************************************/
//This method is now Obsolete - Insert Menu Item removed from under Edit Menu
//delet later when cleaning up - Neha
    protected void editInsert() {
        Util.debugPrint("eI:");
        if (GridLayrProp.showPopup()) {
            GridLayrProp.insertRow();
            validate();
            repaint();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Entire row should be selected", "Error editing layers", JOptionPane.ERROR_MESSAGE);
        }
    }

    /***************************************************************************/
    /* These methods deal with the help in soil screen - Neha */
    @Override
    public void HelpJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        //implementing via addHelp
    }

    @Override
    public void AboutJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        AboutDialog JAboutDialog1 = new AboutDialog(this, usda.weru.util.Application.SOILUI);
        JAboutDialog1.setModal(true);
        JAboutDialog1.setVisible(true);
    }

    protected void addHelp() {
        //Skip loading the helpset if we already have it in memory
        if (Help.hasHelpSet("SOIL") == false) {
            loadHelp();
        }

        addCSH(Help.getHelpSet());
    }

    private void loadHelp() {
        String dirFilePath = "help/soil1/soil.hs";
        String soilJarPath = "jar/SoilHelp.jar";
        String jarFilePath = "jar/MasterHelp.jar";

        if (Help.loadJar(jarFilePath, "soil1/soil.hs")) {
            return;
        } else if (Help.loadJar(soilJarPath)) {
            return;
        } else if (Help.loadDirectory(dirFilePath)) {
            return;
        }
    }

    private void addCSH(HelpSet hs_soil) {
        hb_soil = hs_soil.createHelpBroker();
        hb_soil.enableHelpKey(getRootPane(), "SoilIntro_html", hs_soil);
        hb_soil.enableHelpOnButton(helpJMI, "SoilIntro_html", hs_soil);
        hb_soil.enableHelpOnButton(JB_help, "SoilIntro_html", hs_soil);
        ActionListener helper = new CSH.DisplayHelpFromSource(hb_soil);
        ////System.out.println("I am in the SOIL addHelp()" + helper);
        helpJMI.addActionListener(helper);

        //contextsensitive help
        JB_CSH.addActionListener(new CSH.DisplayHelpAfterTracking(hs_soil, "javax.help.Popup", null));

        CSH.setHelpIDString(MB_main, "soilMenuBar_html");
        CSH.setHelpIDString(M_file, "soilMenuFile_html");
        CSH.setHelpIDString(M_edit, "soilMenuEdit_html");
        CSH.setHelpIDString(M_view, "soilMenuView_html");
        CSH.setHelpIDString(M_help, "soilMenuHelp_html");
        CSH.setHelpIDString(toolbar, "soilButtonBar_html");
        CSH.setHelpIDString(JTB_main, "soilButtonBar_html");
        CSH.setHelpIDString(JB_open, "SoilbuttonOpen_html");
        CSH.setHelpIDString(JB_save, "SoilbuttonSave_html");
        CSH.setHelpIDString(JB_cut, "SoilbuttonCut_html");
        CSH.setHelpIDString(JB_copy, "SoilbuttonCopy_html");
        CSH.setHelpIDString(JB_paste, "SoilbuttonPaste_html");
        CSH.setHelpIDString(JB_print, "SoilbuttonPrint_html");
        CSH.setHelpIDString(JB_close, "SoilbuttonClose_html");
        CSH.setHelpIDString(JP_soilIdentity, "soilIdentification_html");
        CSH.setHelpIDString(JP_soilSurfaceProp, "soilSurface_html");
        CSH.setHelpIDString(JP_soilLayerProp, "soilLayer_html");
//        CSH.setHelpIDString(JP_text,"soilTextArea_html");
        CSH.setHelpIDString(JSP_text, "soilTextArea_html");
        CSH.setHelpIDString(JTA_warningText, "soilTextArea_html");


    }

    /*****************************************************************************/
    /*
    private ActionListener setUpHelp()
    {
    try {
    URL hsURL = new URL((new File(projectsPath)).toURL(), "help2/soilui.hs");
    try {
    hs = new HelpSet(null, hsURL);
    } catch (java.lang.NoClassDefFoundError e) {
    Util.debugPrint("Help system not available");
    return null;
    }
    Util.debugPrint("found help set at " + hsURL);
    }
    catch (Exception ee) {
    Util.debugPrint("help set not found");
    return null;
    }
    hb = hs.createHelpBroker();
    return new CSH.DisplayHelpFromSource(hb);
    }
     */
    /*****************************************************************************/
    /*private	void	displayHelp()
    
    {
    if(hs == null) {
    try {
    URL hsURL = new URL((new File(projectsPath)).toURL(), "help2/soilui.hs");
    hs = new HelpSet(null, hsURL);
    Util.debugPrint("found help set at " + hsURL);
    }
    catch (Exception ee) {
    Util.debugPrint("help set not found");
    return;
    }
    hb = hs.createHelpBroker();
    }
    }*/
//		HelpWindow.ch = new ContextHelp();
//	ContextHelp.showHelp("top");
//1}
/* alternative version
     * {
    HelpWindow hw = new HelpWindow(this,H);
    hw.initHelpWindow();
    }
     */
    /**
     *
     * @param filnam
     */
    public void viewLayers(String filnam) {
        inputSoilName = filnam;
        viewLayers();
    }

    /*****************************************************************************/
    public void viewLayers() {
        if (ifcptr == null) {
            return;
        }
        if (ifcptr.nsl == 0) {
            return;
        }
        setTitle(soiluiid + "  " + inputSoilName);

        //		tables.removeAll();

        JP_soilIdentity.removeAll();
        GridID = new Grid(ifcptr, 1);
        //tables.add(GridID, BorderLayout.NORTH);
        JP_soilIdentity.add(GridID, BorderLayout.CENTER);

        JP_soilSurfaceProp.removeAll();
        GridSurfProp = new Grid(ifcptr, 2);
        //tables.add(GridSurfProp, BorderLayout.NORTH);
        JP_soilSurfaceProp.add(GridSurfProp, BorderLayout.CENTER);

        JP_soilLayerProp.removeAll();
        GridLayrProp = new Grid(ifcptr, 3);
        //tables.add(GridLayrProp, BorderLayout.NORTH);
        JP_soilLayerProp.add(GridLayrProp, BorderLayout.CENTER);
        JP_soilLayerProp.addMouseListener(popupListener);
        GridLayrProp.addMouseListener(popupListener);

//		JTA_warningText.removeAll();
        JTA_warningText.setText(ifcptr.errorsInIfcFile);
//		JSP_text.getVerticalScrollBar().setValue(0);
//		JTA_warningText.insert("", 0);
//		JViewport jvt = JSP_text.getViewport();
//		jvt.setViewPosition(new java.awt.Point(0,0));
        ifcptr.setGrids(GridID, GridSurfProp, GridLayrProp, JTA_warningText);

        getContentPane().invalidate();
        getContentPane().validate();
        getContentPane().repaint();

        JSP_text.getVerticalScrollBar().setValue(0);
        setReadonly(c_readonly);
    }

    /*****************************************************************************/
    public static void main(String[] args) {
        System.setProperty("line.separator", "\n");	// make file line separator unix compatible
        String x = "";
        String mainConfig = "cfg/weps.cfg";
        String userConfig = null;
        //if the user config is not set use the name of the main config file
        if (userConfig == null) {
            userConfig = About.getUserWeps().getAbsolutePath() + "/" + new File(mainConfig).getName();
        }
        ConfigData.getDefault().load(new File(mainConfig), new File(userConfig));

        new Soil(x).setVisible(true);
    }

    /*****************************************************************************/
    @Override
    public void addNotify() {
        // Record the size of the window prior to calling parents addNotify.
        super.addNotify();
    }
    /*****************************************************************************/
    int initflg = 0;

    /**
     * wj
    public void setVisible(boolean b) {
    }
    r a
     */
    protected void printIfc() {
        PrintJob pj = getToolkit().getPrintJob(this,
                "Print IFC file", new Properties());
        if (pj == null) {
            return;
        }
        ifcptr.printIfc(pj);
        pj.end();
    }

    /********************************************************** wjr*/
    void setMenuEnable(String nam, boolean enabled) {
        JMenuBar mb = this.MB_main;
        for (int idx = 0; idx < mb.getMenuCount(); idx++) {
            JMenu menu = mb.getMenu(idx);
            for (int jdx = 0; jdx < menu.getItemCount(); jdx++) {
                JMenuItem mi = menu.getItem(jdx);
                try {
                    if (nam.equalsIgnoreCase(mi.getActionCommand())) {
                        mi.setEnabled(enabled);
                        return;
                    }
                } catch (java.lang.NullPointerException e) {
                }
            }
        }
    }

    /********************************************************** wjr*/
    public void propertyChange(PropertyChangeEvent e) {
////System.out.println("S_pC: propName: " + e.getPropertyName() + " -> " + (String) e.getNewValue());
        if (e.getPropertyName().equals(ConfigData.SoilDB)) {
            //dbName = new String((String) e.getNewValue());
        } else if (e.getPropertyName().equals(ConfigData.CurrentProj)) {
            prjName = Util.parse(e.getNewValue().toString());
//Util.debugPrint(true, "prjName: " + prjName);
        } else if (e.getPropertyName().equals(ConfigData.ProjDir)) {
            projectsPath = (String) e.getNewValue();
            projectsPath = new File(projectsPath).getAbsolutePath();
//Util.debugPrint(true, "projPath: " + projectsPath);
        } else if (e.getPropertyName().equals(ConfigData.SoilEstimate)) {
            if (e.getNewValue().toString().equals("1")) {
                JB_estimate.setVisible(true);
            } else {
                JB_estimate.setVisible(false);
            }
        } else if (e.getPropertyName().equals(ConfigData.SoilDB)) {
            soilDB = (String) e.getNewValue();
        } else if (e.getPropertyName().equals(ConfigData.SWEEPWorkDir)) {
            workingDirectory = (String) e.getNewValue();
        }
    }
    private PropertyChangeSupport changes = new PropertyChangeSupport(this);

    /**
     * Adds listener to changes made on this panel
     *
     * @param l
     */
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    /**
     * Removes listener to changes made on this panel
     *
     * @param l
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }

    /*********************
     ********************* screen handlers
     *********************/
    @Override
    protected void JBClose_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBClose_ActionPerformed
        // TODO add your handling code here:
        progExit();
    }//GEN-LAST:event_JBClose_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void SoilUI_componentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_SoilUI_componentResized
        // Add your handling code here:
        //SoilUI_ComponentResized(evt);
    }//GEN-LAST:event_SoilUI_componentResized

    /**
     *
     * @param evt
     */
    protected void MI_new_ActionPerformed(java.awt.event.ActionEvent evt) {
        // Add your handling code here:
        newFile();
    }

    /**
     *
     * @param evt
     */
    protected void MI_open_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_open_ActionPerformed
        // Add your handling code here:
        openFile();
    }//GEN-LAST:event_MI_open_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_save_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_save_ActionPerformed
        // Add your handling code here:
        saveIfc();
    }//GEN-LAST:event_MI_save_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_saveAs_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_saveAs_ActionPerformed
        // Add your handling code here:
        saveAsIfc();
    }//GEN-LAST:event_MI_saveAs_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_print_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_print_ActionPerformed
        // Add your handling code here:
        printIfc();
    }//GEN-LAST:event_MI_print_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_getSQL_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_getSQL_ActionPerformed
        // Add your handling code here:
        getSQL();
    }//GEN-LAST:event_MI_getSQL_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_batch_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_batch_ActionPerformed
        // Add your handling code here:
//		runBatch();
    }//GEN-LAST:event_MI_batch_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_exit_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_exit_ActionPerformed
        // Add your handling code here:
        progExit();
    }//GEN-LAST:event_MI_exit_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_cut_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_cut_ActionPerformed
        // Add your handling code here:
        editCut();
    }//GEN-LAST:event_MI_cut_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_copy_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_copy_ActionPerformed
        // Add your handling code here:
        editCopy();
    }//GEN-LAST:event_MI_copy_ActionPerformed

    public void pasteBeforeJMI_actionPerformed(java.awt.event.ActionEvent evt) {
        // Add your handling code here:
        editBeforePaste();
    }

    protected void MI_pasteAfter_ActionPerformed(java.awt.event.ActionEvent evt) {
        editAfterPaste();
    }

    /**
     *
     * @param evt
     */
    protected void MI_insNewLayer_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_insNewLayer_ActionPerformed
        // Add your handling code here:
        editInsert();
    }//GEN-LAST:event_MI_insNewLayer_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void MI_help_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MI_help_ActionPerformed
        // Add your handling code here:
//		displayHelp();
    }//GEN-LAST:event_MI_help_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void JB_open_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_open_ActionPerformed
        // Add your handling code here:
        openFile();
    }//GEN-LAST:event_JB_open_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void JB_save_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_save_ActionPerformed
        // Add your handling code here:
        //ifcptr.setGrids(null, null, null, null);		// invalidate grid so that old values won't overwrite estimates
        saveIfc();
    }//GEN-LAST:event_JB_save_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void JB_cut_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_cut_ActionPerformed
        // Add your handling code here:
        editCut();
    }//GEN-LAST:event_JB_cut_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void JB_copy_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_copy_ActionPerformed
        // Add your handling code here:
        editCopy();
    }//GEN-LAST:event_JB_copy_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void JB_paste_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_paste_ActionPerformed
        // Add your handling code here:
        //This is called when the tool button Paste is clicked.
        editBeforePaste();
    }//GEN-LAST:event_JB_paste_ActionPerformed

    /**
     *
     * @param evt
     */
    protected void JB_print_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_print_ActionPerformed
        // Add your handling code here:
        printIfc();
    }//GEN-LAST:event_JB_print_ActionPerformed

    /**
     * Exit the Application
     * @param evt
     */
    protected void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        progExit();
    }//GEN-LAST:event_exitForm

    /**
     *
     * @param evt
     */
    protected void selectItemStateChanged(java.awt.event.ItemEvent evt) {
        if (evt.getStateChange() != java.awt.event.ItemEvent.SELECTED) {
            return;
        }
        selFlg = true;
        JB_estimate.setEnabled(selFlg);
        if (GridLayrProp != null) {
            GridID.displayColumns("select");
            GridSurfProp.displayColumns("select");
            GridLayrProp.displayColumns("select");
        }
        // TODO add your handling code here:
    }

    /**
     *
     * @param evt
     */
    protected void allItemStateChanged(java.awt.event.ItemEvent evt) {
        if (evt.getStateChange() != java.awt.event.ItemEvent.SELECTED) {
            return;
        }
        selFlg = false;
        JB_estimate.setEnabled(selFlg);
        if (GridLayrProp != null) {

            viewLayers();
            GridID.displayColumns("all");
            GridSurfProp.displayColumns("all");
            GridLayrProp.displayColumns("all");
        }

        // TODO add your handling code here:
    }

    protected void JB_estimateActionPerformed(java.awt.event.ActionEvent evt) {
        commitEdits();
        try {
            ifcptr.estimateFactors();
        } catch (IllegalStateException ise) {
            return;
        }
        selFlg = false;
        JB_estimate.setEnabled(selFlg);
        all.setState(!selFlg);
        select.setState(selFlg);
        if (GridLayrProp != null) {
            viewLayers();
            GridID.displayColumns("all");
            GridSurfProp.displayColumns("all");
            GridLayrProp.displayColumns("all");
        }
    }
    private JPopupMenu popup;
    private Vector popupVec;
    private MouseListener popupListener;

    private void addPopupMenu() {
        MenuElement[] menuElements;

        popup = new JPopupMenu();

        popupVec = new Vector();

        JMenuItem jmi = new javax.swing.JMenuItem();
        // Now follws multiple row operations
        jmi.setText("Cut Row");
        jmi.setActionCommand("Cut ");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editCut();
            }
        });
        popup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Copy Row");
        jmi.setActionCommand("Copy");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editCopy();
            }
        });
        popup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Paste Before Row");
        jmi.setActionCommand("Paste Before Row");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editBeforePaste();
            }
        });
        popup.add(jmi);

        jmi = new javax.swing.JMenuItem();
        jmi.setText("Paste After Row");
        jmi.setActionCommand("Paste After Row");
        jmi.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editAfterPaste();
            }
        });
        popup.add(jmi);

        /* No need of Insert Row menu item in the popup menu - neha
        jmi = new javax.swing.JMenuItem();
        jmi.setText("Insert Row");
        jmi.setActionCommand("Insert");
        popup.add(jmi);
        jmi.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
        editInsert();
        }
        });
        popup.add(jmi);
         */

        menuElements = popup.getSubElements();
        for (int i = 0; i < menuElements.length; i++) {
            popupVec.add(menuElements[i]);
        }

        Util.debugPrint(true, "popup menu added");
        popupListener = new PopupListener();
        JP_soilLayerProp.addMouseListener(popupListener);

    }

    class PopupListener extends MouseAdapter {

        public void mousePressed(MouseEvent e) {

            ////System.out.println("Mcrew: mousepressed:");
            maybeShowPopup(e);
            Util.debugPrint(true, "mouse pressed -- current row " + GridLayrProp.getCurrentRow());
        }

        public void mouseReleased(MouseEvent e) {
            ////System.out.println("Mcrew: released:");
            maybeShowPopup(e);
        }

        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                e.consume();
                //Show the popup menu only when the entire row is selected - neha
                if (GridLayrProp.showPopup()) {
                    popup.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        }
    }
}
