/**
 * Displays the location panel information.
 *
 * This includes state, county, longitude and latitude for the
 * location. WINDGEN and CLIGEN stations, including elevation, are
 * displayed or user specified wind and climate files.
 *
 */
package usda.weru.weps;

import com.vividsolutions.jts.geom.Coordinate;
import de.schlichtherle.io.File;
import java.awt.CardLayout;
import java.awt.Event;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import java.beans.*;
import java.util.*;
import javax.help.*;
import org.apache.log4j.Logger;
import usda.weru.gis.GISUtil;
import usda.weru.gis.gui.MapController;
import usda.weru.util.*;
import usda.weru.util.gis.ReadShapefile;

/**
 * The class that shows the location information for a wind or climate station using details such as
 * longitude and latitude parameters.
 */
public class LocPanel extends usda.weru.weps.gui.LocPanel_n implements PropertyChangeListener {

    private static final Logger LOGGER = Logger.getLogger(LocPanel.class);
    String measurementUnits = "";
    Vector V_county = null;
    Vector V_state = null;
    String cliGenStationID = "";
    String cliGenStateID = "";
    String windGenStationID = "";
    String projDir = "";
    LatLongOld latLong = new LatLongOld();
    private int loadFlg = 0;
    public boolean notDoneWithInit = true;
    private Weps c_weps;

    private boolean isLoading() {
        return loadFlg > 0;
    }
    //By Neha-This flag keeps track if the user has changed the elevation manually
    private boolean elevManual = false;
    private MapViewer mv;
    private String c_climateIndex;
    private String c_windIndex;

    /**
     * Default class constructors
     */
    public LocPanel() {
        this(null, null);
    }

    public LocPanel(Weps weps) {
        this(null, null);
        c_weps = weps;
    }

    public LocPanel(String windName, String cliName) {
        super();
        readStateChoices();
        V_mainWinCli = WindCliStation.readWinCli(windName, cliName);
        JP_main.setVisible(true);
//	JCB_WinGen.addActionListener(new JCB_Listener());

        addHelp();
    }

    /**
     * This panel holds all the location information for the wind and climate generation station like
     * the latitudes and longitudes passing through it, the county and state in which they fall, etc.
     * @param sTitle The string that carries the title for the panel.
     */
    /*    public LocPanel(String sTitle) {
    this();
    setTitle(sTitle);
    }*/
    /**
     * help stuff
     */
    private void addHelp() {
        CSH.setHelpIDString(JP_main, "locPanel_html");
        // CSH.setHelpIDString(JL_Title, "choosing a location");
        CSH.setHelpIDString(JL_State, "locState_html");
        CSH.setHelpIDString(JCB_State, "locState_html");
        CSH.setHelpIDString(JL_County, "locCounty_html");
        CSH.setHelpIDString(JCB_County, "locCounty_html");
        CSH.setHelpIDString(JL_Longitude, "locLongitude_html");
        CSH.setHelpIDString(JTF_Longitude, "locLongitude_html");
        CSH.setHelpIDString(JL_Latitude, "locLatitude_html");
        CSH.setHelpIDString(JTF_Latitude, "locLatitude_html");
        CSH.setHelpIDString(JL_Elevation, "locElevation_html");
        CSH.setHelpIDString(JTF_Elevation, "locElevation_html");
        CSH.setHelpIDString(JL_CliGen, "locCliGen_html");
        CSH.setHelpIDString(JCB_CliGen, "locCliGen_html");
        CSH.setHelpIDString(JL_WinGen, "locWinGen_html");
        CSH.setHelpIDString(JCB_WinGen, "locWinGen_html");
        CSH.setHelpIDString(JB_UseMap, "locUseMap_html");
        //For the latitude button
        CSH.setHelpIDString(JL_Lat, "locLatitudeButton_html");
        //For the longitude button
        CSH.setHelpIDString(JL_Lon, "locLongitudeButton_html");
    }

    /**
     * Entry point for testing standalone. Used if this dialog is rum as an independent application.
     * If executed, makes the GUI visible.
     * @param args These are the command line arguments passed to the main method.
     */
    static public void main(String args[]) {
        String projectsDir = "";

        WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.PROJECT, projectsDir,
                WepsFileChooser.SELECT);
        wfc.setCurrentDirectory(new de.schlichtherle.io.File("c:/weps/weps.install/projects"));
        RunFileData rfd = new RunFileData();
        if (wfc.showDialog(null) == JFileChooser.APPROVE_OPTION) {
            File sf = new File(wfc.getSelectedFile());
            try {
                projectsDir = sf.getCanonicalPath();
            } catch (java.io.IOException e) {//System.err.println(
                //  "Error getting canoncial path of projectsDir");
            }
            rfd.readRunData(projectsDir);
//			rfd.showRunFileData("this is a test");
        } else {
            //System.err.println("No project directory selected");
            rfd = new RunFileData();
        }

        LocPanel lp = new LocPanel();
        lp.setVisible(true);
        rfd.addPropertyChangeListener(lp);
        lp.addPropertyChangeListener(rfd);
        rfd.fireAll(lp);
    }

    private void loadData() {
        notDoneWithInit = false;
        loadFlg++;
        V_Win = null;
        V_Cli = null;
        JCB_CliGen.removeAllItems();
        JCB_WinGen.removeAllItems();

        setCliFlag(ht.get(RunFileData.ClimateFlag));
        setWindFlag(ht.get(RunFileData.WindFlag));

        setLatLong(ht.get(RunFileData.LatLong));
        getCounty();
        //setSite(ht.get(RunFileData.Site));
        setWindFile(ht.get(RunFileData.WindFile));
//        setWinShapefileFlg(ht.get(ConfigData.NRCSWinFlg));
//        setWinShapefile(ht.get(ConfigData.NRCSWinShape));

        setWindGenStationID(ht.get(RunFileData.WinGenStation));
        setWinStation(ht.get(RunFileData.WindGenStationName), true);
        setCliFile(ht.get(RunFileData.ClimateFile));
        setCliGenStateID(ht.get(RunFileData.CliGenState));
        setCliGenStationID(ht.get(RunFileData.CliGenStation));
        setCliStation(ht.get(RunFileData.CliGenStationName), true);
        setElevation(ht.get(RunFileData.Elevation));

//        setCliShapefileFlg(ht.get(ConfigData.NRCSCliFlg));
//        setCliShapefile(ht.get(ConfigData.NRCSCliShape));

        loadFlg--;
        manualLatLong = false;
    }
    /**
     * Property change handler.
     */
    double elevation;
    String county = "";
    private String windFile = "";
    private String climateFile = "";
    private Hashtable<String, PropertyChangeEvent> ht = new Hashtable<String, PropertyChangeEvent>();
    private boolean initFlg = false;
    //This string keeps track of the last run made/restored in the project - neha
    private String lastRun = "";
    private String currentProj = "";

    /**
     * Recognizes and takes appropriate actions on registered properties from different
     * screens to update and synchronize data and GUI screens as needed.
     * @param e The event itself that is responsible for triggering the change required for registered
     * properties/components.
     */
    @Override
    public void propertyChange(PropertyChangeEvent e) {

        // init properties
        if (e.getPropertyName().equals(RunFileData.LoadData)) {
            initFlg = e.getNewValue().equals("1");
            if (initFlg) {
                ht = new Hashtable<String, PropertyChangeEvent>();
            } else {
                loadData();
            }
        } else if (initFlg) {
            ht.put(e.getPropertyName(), e);
        // runfiledata properties
        } else if (e.getPropertyName().equals(RunFileData.ClimateFile)) {
            setCliFile(e);
        } else if (e.getPropertyName().equals(RunFileData.CliGenState)) {
            setCliGenStateID(e);
        } else if (e.getPropertyName().equals(RunFileData.CliGenStation)) {
            setCliGenStationID(e);
        } else if (e.getPropertyName().equals(RunFileData.CliGenStationName)) {
            setCliStation(e, true);
        } else if (e.getPropertyName().equals(RunFileData.Elevation)) {
            setElevation(e);
        } else if (e.getPropertyName().equals(RunFileData.LatLong)) {
            
            if (e.getSource() instanceof MapViewer) {
                //pass the change up
                this.changes.firePropertyChange(e);
                manualLatLong = true;
                getCounty();
                manualLatLong = false;
            }
            else{
                setLatLong(e);
            }
        } else if (e.getPropertyName().equals(RunFileData.Site)) {
            setSite(e);
        } else if (e.getPropertyName().equals(RunFileData.WindFile)) {
            setWindFile(e);
        } else if (e.getPropertyName().equals(RunFileData.WinGenStation)) {
            setWindGenStationID(e);
        } else if (e.getPropertyName().equals(RunFileData.WindGenStationName)) {
            setWinStation(e, true);

        // configdata properties

        } else if (e.getPropertyName().equals(ConfigData.ProjDir)) {
            projDir = (String) e.getNewValue();
        } else if (e.getPropertyName().equals(ConfigData.CurrentProj)) {
            currentProj = Util.parse(e.getNewValue().toString());
        } else if (e.getPropertyName().equals(ConfigData.WindRadius)) {
            setWindRadius(e);
        } else if (e.getPropertyName().equals(ConfigData.ClimateRadius)) {
            setClimateRadius(e);
        } else if (e.getPropertyName().equals(ConfigData.Units)) {
            setUnits(e);
        } else if (e.getPropertyName().equals(ConfigData.UseMap)) {
            JB_UseMap.setVisible(((String) e.getNewValue()).equals("1"));
        } else if (e.getPropertyName().equals(ConfigData.DispStCty)) {
            setDispStCty(e);
        } else if (e.getPropertyName().equals(ConfigData.DispLatLon)) {
            setDispLatLon(e);
        } else if (e.getPropertyName().equals(ConfigData.DispElevation)) {
            setDispElevation(e);
        } else if (e.getPropertyName().equals(RunFileData.WindFlag)) {
            setWindFlag(e);
        } else if (e.getPropertyName().equals(RunFileData.ClimateFlag)) {
            setCliFlag(e);
        }

//        else if (e.getPropertyName().equals(ConfigData.NRCSCliFlg)) {
//            setCliShapefileFlg(e);
//        } else if (e.getPropertyName().equals(ConfigData.NRCSCliShape)) {
//            setCliShapefile(e);
//        } else if (e.getPropertyName().equals(ConfigData.NRCSWinFlg)) {
//            setWinShapefileFlg(e);
//        } else if (e.getPropertyName().equals(ConfigData.NRCSWinShape)) {
//            setWinShapefile(e);
//        }

        else if (e.getPropertyName().equals(RunFileData.LastRun)) {
            lastRun = (String) e.getNewValue();
        //System.out.println(lastRun);
        //TODO: move into worker threads
        } else if (e.getPropertyName().equals(ConfigData.CliIndex)) {
            if (c_climateIndex != null && c_climateIndex.equals(e.getNewValue().toString())) {
                return;
            }
            c_climateIndex = e.getNewValue().toString();
            V_mainWinCli = WindCliStation.readWinCli(c_windIndex, c_climateIndex);
            makeCliList(latLong.getSignedLatitude(), latLong.getSignedLongitude());
        } else if (e.getPropertyName().equals(ConfigData.WinIndex)) {
            if (c_windIndex != null && c_windIndex.equals(e.getNewValue().toString())) {
                return;
            }
            c_windIndex = e.getNewValue().toString();
            V_mainWinCli = WindCliStation.readWinCli(c_windIndex, c_climateIndex);
            makeWindList(latLong.getSignedLatitude(), latLong.getSignedLongitude());
        } else if (ConfigData.ShowWeatheFilerCheckboxes.equals(e.getPropertyName())) {
            setShowWeatherCheckboxes(e);
        }
        int a = 0;
    }
    /**
     * private methods to set values in display fields from runfiledata
     */
    private String cliShapefileName = null;
    private String useCliShapefileFlg = "0";
    private ReadShapefile cliShapefile = null;

    private void setShowWeatherCheckboxes(PropertyChangeEvent e) {
        boolean show = "1".equals(e.getNewValue());
        JXB_climateFlag.setVisible(show);
        JXB_windFlag.setVisible(show);
    }

    private void setCliShapefile(PropertyChangeEvent e) {
        if (e == null) {
            return;
        }
        String fileName = e.getNewValue().toString();
        cliShapefileName = fileName;
        if ("1".equals(useCliShapefileFlg) && cliShapefileName.trim().length() != 0) {
            cliShapefile = new ReadShapefile(cliShapefileName);
        }
    }

    private void setCliShapefileFlg(PropertyChangeEvent e) {
        if (e == null) {
            return;
        }
        String flg = e.getNewValue().toString();
        useCliShapefileFlg = flg;
        if ("1".equals(flg) && cliShapefileName != null && cliShapefileName.trim().length() != 0) {
            cliShapefile = new ReadShapefile(cliShapefileName);
            JCB_CliGen.setEnabled(false);
        } else {
            JCB_CliGen.setEnabled(true);
            cliShapefile = null;
        }
    }
    private String winShapefileName = null;
    private String useWinShapefileFlg = "0";
    private ReadShapefile winShapefile = null;

    private void setWinShapefile(PropertyChangeEvent e) {
        if (e == null) {
            return;
        }
        String fileName = e.getNewValue().toString();
        winShapefileName = fileName;
        if ("1".equals(useWinShapefileFlg) && winShapefileName.trim().length() != 0) {
            winShapefile = new ReadShapefile(winShapefileName);
        }
    }

    private void setWinShapefileFlg(PropertyChangeEvent e) {
        if (e == null) {
            return;
        }
        String flg = e.getNewValue().toString();
        useWinShapefileFlg = flg;
        if ("1".equals(flg) && winShapefileName != null && winShapefileName.trim().length() != 0) {
            winShapefile = new ReadShapefile(winShapefileName);
            JCB_WinGen.setEnabled(false);
        } else {
            JCB_WinGen.setEnabled(true);
            winShapefile = null;
        }
    }

    private void setCliFile(PropertyChangeEvent e) {
        climateFile = (String) e.getNewValue();
        JTF_climateFile.setText(new File(climateFile).getName());
    }

    private void setCliGenStateID(PropertyChangeEvent e) {
        cliGenStateID = (String) e.getNewValue();
    }

    private void setCliGenStationID(PropertyChangeEvent e) {
        cliGenStationID = (String) e.getNewValue();
    }

    private void setLat(LatLongOld latLong) {
    }

    private void setLon(LatLongOld latLong) {
        JTF_Longitude.setText(latLong.getLongitude());
        JL_Lon.setText(latLong.getLongitudeSign());
        CardLayout cards = (CardLayout) JP_windCards.getLayout();
        if (winShapefile != null && useWinShapefileFlg.equals("1")) {
            JXB_windFlag.setVisible(false);
            JB_windFile.setVisible(false);
            double y = latLong.getLat() * 100000;
            double x = latLong.getLon() * 100000;
            final String stationName = winShapefile.findHoleyPolygon(x, y);
            if (stationName == null || "|out".equalsIgnoreCase(stationName)) {  // in a polygon where normal selection is enabled
                cards.show(JP_windCards, "stations");
                makeWindList(latLong.getSignedLatitude(), latLong.getSignedLongitude());
                JCB_WinGen.setEnabled(true);
                System.out.println("in out");
            } else if ("|int".equalsIgnoreCase(stationName)) {                  // in interpolated region
                cards.show(JP_windCards, "file");
                changes.firePropertyChange(RunFileData.WindFlag, null, "1");
                WindCliStation wcs = new WindCliStation();
                wcs.station = "Interpolated";
                JTF_windFile.setText("Interpolated");
                String fileName = "I~" + latLong.getSignedLatitude() + "~" + latLong.getSignedLongitude();
                fileName = fileName.replace('.', '#');
                wcs.stationID = fileName;
                fireWinGen(wcs);
            } else {                                                            // in polygon where specific station is mapped
                System.out.println("not out, not int");
                cards.show(JP_windCards, "file");
                System.out.println("we're in a shape " + stationName);
//                eol:
                for (WindCliStation wcs : V_mainWinCli) {
                    if (wcs.type == WindCliStation.CliStation) {
                        continue;
                    }
                    if (wcs.getStateStation().equals(stationName)) {
                        JTF_windFile.setText(wcs.getStation());
                        fireWinGen(wcs);
                        return;
                    }
                }
                //Okay, this is bad.  The shapefile wants a station not in the index.
                //Per Mike, we show a choice list of nearest stations.
                LOGGER.error(stationName + " not in windgen index.");
                cards.show(JP_windCards, "stations");
                makeWindList(latLong.getSignedLatitude(), latLong.getSignedLongitude());
                JCB_WinGen.setEnabled(true);
                if(loadFlg == 0){
                    JOptionPane.showMessageDialog(null, "Windgen station not found in index.\n" + stationName, "Error", JOptionPane.ERROR_MESSAGE);
                }


            }
        } else {
            JB_windFile.setVisible(true);
            JXB_windFlag.setVisible(true);
            JXB_windFlag.setSelected(false);
            JCB_WinGen.setVisible(true);
            cards.show(JP_windCards, "stations");
            System.out.println("not in out");
            makeWindList(latLong.getSignedLatitude(), latLong.getSignedLongitude());
            JCB_WinGen.setEnabled(true);
        }
    }

    private void setLatLong(PropertyChangeEvent e) {
        String sLatLong = (String) e.getNewValue();
        latLong = new LatLongOld(sLatLong);
        JTF_Latitude.setText(latLong.getLatitude());
        JL_Lat.setText(latLong.getLatitudeSign());
        makeCliList(latLong.getSignedLatitude(), latLong.getSignedLongitude());
        JCB_CliGen.setEnabled(true);
        if (cliShapefile != null && useCliShapefileFlg.equals("1")) {
            double y = latLong.getLat() * 100000;
            double x = latLong.getLon() * 100000;
            String stationName = cliShapefile.findHoleyPolygon(x, y);
            if (stationName == null || stationName.contains("Out")) {
//                JOptionPane.showMessageDialog(this, "Location not mapped in shapefile\nPick a climate station to use");
            } else {
                DefaultComboBoxModel dcbm = (DefaultComboBoxModel) JCB_CliGen.getModel();
                for (int idx = 0; idx < dcbm.getSize(); idx++) {
                    WindCliStation wcs = (WindCliStation) dcbm.getElementAt(idx);
                    if (wcs.getStateStation().equals(stationName)) {
                        JCB_CliGen.setSelectedItem(wcs);
//                        dcbm.removeAllElements();
//                        dcbm.addElement(wcs);
                        JCB_CliGen.setEnabled(false);
                        break;
                    }
                }
            }
        }
        setLon(latLong);
    }

    private void setWindFile(PropertyChangeEvent e) {
        windFile = (String) e.getNewValue();
        JTF_windFile.setText(new File(windFile).getName());
    }

    private void setWindFlag(PropertyChangeEvent e) {
        JXB_windFlag.setSelected("1".equals(e.getNewValue()));

        //select the type of fields to show
        CardLayout cards = (CardLayout) JP_windCards.getLayout();
        cards.show(JP_windCards, JXB_windFlag.isSelected() ? "file" : "stations");
    }

    private void setCliFlag(PropertyChangeEvent e) {
        //update the checkbox
        JXB_climateFlag.setSelected("1".equals(e.getNewValue()));

        //select the type of fields to show
        CardLayout cards = (CardLayout) JP_climateCards.getLayout();
        cards.show(JP_climateCards, JXB_climateFlag.isSelected() ? "file" : "stations");

    }

    private void setWindGenStationID(PropertyChangeEvent e) {
        windGenStationID = (String) e.getNewValue();
        if (windGenStationID.startsWith("I~")) {
            CardLayout cards = (CardLayout) JP_windCards.getLayout();
            cards.show(JP_windCards, "file");
            JXB_windFlag.setVisible(false);
            JB_windFile.setVisible(false);
            JTF_windFile.setText("Interpolated");
        }
//        Util.debugPrint(true, windGenStationID);
    }

    private void setWinStation(PropertyChangeEvent e, boolean chgFlg) {
        if (notDoneWithInit) {
            return;
        } else if (e == null) {
            return;
        }

        if (useWinShapefileFlg.equals("1")) {
            return;
        }

        if (JCB_WinGen.getItemCount() > 0) {
            String windStat = (String) e.getNewValue();
            LOGGER.debug("setWinStation: " + windStat);
            WindCliStation cws = new WindCliStation(WindCliStation.WinStation, windStat);
            for (int idx = 0; idx < JCB_WinGen.getItemCount(); idx++) {
                if (cws.equals(JCB_WinGen.getItemAt(idx))) {
                    JCB_WinGen.setSelectedIndex(idx);
                    //fireWinGen((WindCliStation) JCB_WinGen.getItemAt(idx));
                    break;
                }

                if (idx == (JCB_WinGen.getItemCount() - 1)) {
                    for (int jdx = 0; jdx < V_mainWinCli.size(); jdx++) {
                        WindCliStation tcws = V_mainWinCli.elementAt(jdx);
                        if (cws.equals(tcws)) {
                            int cdx = JCB_County.getSelectedIndex();
                            CountyMap sc = (CountyMap) V_countyInfo.elementAt(cdx);
                            try {
                                lon = Double.parseDouble(sc.longitude.trim());
                                lat = Double.parseDouble(sc.latitude.trim());
                                tcws.distance = Util.polarDistance(lat, lon, tcws.lat, tcws.lon);
                            } catch (NumberFormatException g) {
                                //System.err.println("LP_sWS " + g);
                            }
                            JCB_WinGen.addItem(tcws);
                            V_Win.add(tcws);
                            JCB_WinGen.setSelectedIndex(idx);
                            //fireWinGen(tcws);
                            break;
                        }
                        if (jdx == V_mainWinCli.size() && chgFlg) {
                            JOptionPane.showMessageDialog(this,
                                    "Wind station name not found\nPerhaps the database has been changed",
                                    "Station not found",
                                    JOptionPane.ERROR_MESSAGE);
                            JCB_WinGen.setSelectedIndex(0);
                        }
                    }
                }
            }
        }
    }

    private void setCliStation(PropertyChangeEvent e, boolean chgFlg) {
        if (notDoneWithInit) {
            return;
//        Util.debugPrint(true, e + " " + JCB_CliGen.getItemCount());
        }
        if (e == null) {
            return;
        }
        if (JCB_CliGen.getItemCount() > 0) {
            String cliStat = (String) e.getNewValue();
            WindCliStation cws = new WindCliStation(WindCliStation.CliStation, cliStat);
            for (int idx = 0; idx < JCB_CliGen.getItemCount(); idx++) {
                if (cws.equals(JCB_CliGen.getItemAt(idx))) {
                    JCB_CliGen.setSelectedIndex(idx);
                    //fireCliGen((WindCliStation) JCB_CliGen.getItemAt(idx));
                    break;
                }

                if (idx == (JCB_CliGen.getItemCount() - 1)) {
                    for (int jdx = 0; jdx < V_mainWinCli.size(); jdx++) {
                        WindCliStation tcws = V_mainWinCli.elementAt(jdx);
                        if (cws.equals(tcws)) {
                            int cdx = JCB_County.getSelectedIndex();
                            if (cdx < 0) {
                                return; // there is no clistation selected
                            }
                            CountyMap sc = (CountyMap) V_countyInfo.elementAt(cdx);
                            try {
                                lon = Double.parseDouble(sc.longitude.trim());
                                lat = Double.parseDouble(sc.latitude.trim());
                                tcws.distance = Util.polarDistance(lat, lon, tcws.lat, tcws.lon);
                            } catch (NumberFormatException g) {
                                //System.err.println("LP_sWS " + g);
                            }
                            JCB_CliGen.addItem(tcws);
                            V_Cli.add(tcws);
                            JCB_CliGen.setSelectedIndex(idx);
                            //fireCliGen(tcws);
                            break;
                        }
                        if (jdx == V_mainWinCli.size() && chgFlg) {
                            JOptionPane.showMessageDialog(this,
                                    "Climate station name not found\nPerhaps the database has been changed",
                                    "Station not found",
                                    JOptionPane.ERROR_MESSAGE);
                            JCB_CliGen.setSelectedIndex(0);
                        }
                    }
                }
            }
        }
    }

    private void setUnits(PropertyChangeEvent e) {
        measurementUnits = (String) e.getNewValue();
        WindCliStation.setMeasurementUnits(measurementUnits);
        JCB_CliGen.repaint();
        JCB_WinGen.repaint();
        boolean flg = measurementUnits.equals(Util.USUnits);
        JL_ft.setText(flg ? "ft" : "m");
        JL_climateMi.setText(flg ? "mi" : "km");
        JL_windMi.setText(flg ? "mi" : "km");
        JTF_Elevation.setText(Util.convertMetersToFeet(elevation,
                flg ? Util.USUnits : Util.SIUnits));
        String dist = "" + climateLimit;
        JL_cliDistance.setText(Util.convertKMToMiles(dist,
                flg ? Util.USUnits : Util.SIUnits));
        dist = "" + windLimit;
        JL_windDistance.setText(Util.convertKMToMiles(dist,
                flg ? Util.USUnits : Util.SIUnits));
    }

    private void setWindRadius(PropertyChangeEvent e) {
        try {
            double tmp = Double.parseDouble((String) e.getNewValue());
            if (tmp == windLimit) {
                return;
            }
            windLimit = tmp;
            String val = Util.convertKMToMiles(windLimit, measurementUnits);
            JL_windDistance.setText(val);
            loadFlg++;
            makeWindList(latLong.getSignedLatitude(), latLong.getSignedLongitude());
            loadFlg--;
            ;
//			JCBCounty_itemStateChanged(new ItemEvent(JCB_County, 0, null, ItemEvent.SELECTED));
        } catch (NumberFormatException k) {
            //System.err.println("LP-pC: bad distance limit from cd " + k);
        }
    }

    private void setClimateRadius(PropertyChangeEvent e) {
        try {
            double tmp = Double.parseDouble((String) e.getNewValue());
            //Since we display climate stations within the climateLimit already
            // we can ignore if the climate radius is set to climateLimit.
            if (climateLimit == tmp) {
                return;
            //set the climateLimit to the desired value
            }
            climateLimit = tmp;
            String val = Util.convertKMToMiles(climateLimit, measurementUnits);
            JL_cliDistance.setText(val);
            loadFlg++;
            //makeCliList() will load all the climate stations that fall within this climateLimit.
            makeCliList(latLong.getSignedLatitude(), latLong.getSignedLongitude());
            loadFlg--;
//			JCBCounty_itemStateChanged(new ItemEvent(JCB_County, 0, null, ItemEvent.SELECTED));
        } catch (NumberFormatException k) {
            //System.err.println("LP-pC: bad distance limit from cd " + k);
        }
    }

    private void setElevation(PropertyChangeEvent e) {
        try {
            elevation = Double.parseDouble((String) e.getNewValue());
            JTF_Elevation.setText(Util.convertMetersToFeet(elevation,
                    measurementUnits));
//            Util.debugPrint(true, JTF_Elevation.getText());
        } catch (NumberFormatException k) {
            //System.err.println("LP-pC: bad elevation from rfd " + k);
        } catch (NullPointerException np) {
            //System.err.println("LP-pC: elevation value null " + np);
        }
    }

    private void setDispStCty(PropertyChangeEvent e) {
        boolean flg = ((String) e.getNewValue()).equals("1");
        JL_State.setVisible(flg);
        JL_County.setVisible(flg);
        JCB_State.setVisible(flg);
        JCB_County.setVisible(flg);
    }

    private void setDispElevation(PropertyChangeEvent e) {
        boolean flg = ((String) e.getNewValue()).equals("1");
        JL_Elevation.setVisible(flg);
        JTF_Elevation.setVisible(flg);
        JL_ft.setVisible(flg);
    }

    private void setDispLatLon(PropertyChangeEvent e) {
        boolean flg = ((String) e.getNewValue()).equals("1");
        JL_Longitude.setVisible(flg);
        JL_Latitude.setVisible(flg);
        JTF_Longitude.setVisible(flg);
        JTF_Latitude.setVisible(flg);
        JL_Lon.setVisible(flg);
        JL_Lat.setVisible(flg);
        JL_degLong.setVisible(flg);
        JL_degLat.setVisible(flg);
    }
    private String oldSite = null;

    private void setSite(PropertyChangeEvent e) {
        //if (isLoading() || manualLatLong) return;
        if (e.getNewValue() == null) {
            getCounty();
            return;
        }
        String site = (String) e.getNewValue();
        if (site.trim().equals(oldSite)) {
            return;
        }
        oldSite = site.trim();
        StringTokenizer st = new StringTokenizer(site, ",");
        int numTokens = st.countTokens();
        if (numTokens != 2) {
            //System.err.println("LP_sS: odd site name " + site);
        }
        StringBuffer sb = new StringBuffer();
        for (int idx = 1; idx < numTokens; idx++) {
            sb.append(st.nextToken().trim() + " ");
        }

        String state = st.nextToken().trim();

        JCB_State.setSelectedItem(state);
        JCB_County.removeAllItems();
        StateMap sm = (StateMap) HT_stateIndex.get(state.trim());
        V_countyInfo = sm.countyVec;
        JCB_County.addItem("none selected");
        for (Iterator scvi = V_countyInfo.iterator(); scvi.hasNext();) {
            CountyMap cm = (CountyMap) scvi.next();
            JCB_County.addItem(cm.name);
        }
        JCB_County.setSelectedItem(sb.toString().trim());
        this.JP_main.repaint();
    }
    private PropertyChangeSupport changes = new PropertyChangeSupport(this);

    /**
     * Allows the container to add or register some other components to recognize the changes that occur
     * on this component.
     * @param l The listener that listens and reacts towards the the changes to be reflected.
     */
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    /**
     * Allows the container to remove or de-register some other components and stop recognizing the
     * changes that occur on this component.
     * @param l The listener that does not listen and react towards the the changes to be reflected.
     */
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }
    /* section of code that reads states and counties, incl lat & lon */
    Hashtable HT_stateIndex = null;

    private void readStateChoices() {

        V_state = StateMap.loadFile();
        V_state.add(0, new StateMap("none selected", "dy", "X0"));
        V_county = CountyMap.loadFile(StateMap.ht);
        Collections.sort(V_county, new CountyMap());
        for (Iterator vci = V_county.iterator(); vci.hasNext();) {
            CountyMap cm = (CountyMap) vci.next();
            cm.setLonLat();
        }
        HT_stateIndex = StateMap.ht;

        for (Iterator si = V_state.iterator(); si.hasNext();) {
            JCB_State.addItem(((StateMap) si.next()).name);
        }

        JCB_State.setSelectedIndex(0);
    }
    Vector<WindCliStation> V_mainWinCli = new Vector<WindCliStation>();
    double lat = 0;
    double lon = 0;
    double elv = 0;

    private void getCounty() {

        CountyMap cm = CountyMap.getCounty(JTF_Longitude.getText(), JTF_Latitude.getText(), latLong.getLongitudeSign(), latLong.getLatitudeSign(), V_county);
        if (cm == null) {
            if (JTF_Longitude.getText().trim().length() != 0 &&
                    JTF_Latitude.getText().trim().length() != 0) {
                /* Commenting out the Message Dialog
                JOptionPane.showMessageDialog(this,"Coordinates specified are not within map area",
                "Out of range",JOptionPane.ERROR_MESSAGE);
                 */
                JCB_State.setSelectedIndex(0);
                if (JCB_County.getItemCount() > 0) {
                    JCB_County.removeAllItems();
                    JCB_County.addItem(" ");
                }
            }
        } else {

            JCB_State.setSelectedItem(cm.state);
            JCB_County.setSelectedItem(cm.name);
        }
    }

    public void JTFLongitude_focusLost(java.awt.event.FocusEvent event) {
        JTFLongitude_actionPerformed(null);
    }

    public void JTFLatitude_focusLost(java.awt.event.FocusEvent event) {
        JTFLatitude_actionPerformed(null);
    }

    public void JTFElevation_focusLost(java.awt.event.FocusEvent event) {
        //if (event.isTemporary()) return;
        //Since the user may change the elevation manually here by not pressing the "Enter",
        //button and by just pressing "tab" or shifting focus to some other field, this flag is made true
        elevManual = true;
        Util.checkNumericJTF(JP_main, JTF_Elevation, elv,
                RunFileData.Elevation,
                changes, measurementUnits);
    }

    protected void climateFlag_actionPerformed(java.awt.event.ActionEvent evt) {
        changes.firePropertyChange(RunFileData.ClimateFlag, null, JXB_climateFlag.isSelected() ? "1" : "0");

    }

    protected void windFlag_actionPerformed(java.awt.event.ActionEvent evt) {
        changes.firePropertyChange(RunFileData.WindFlag, null, JXB_windFlag.isSelected() ? "1" : "0");
    }
    private WindCliStation old_climate;

    void fireCliGen(WindCliStation wcs) {
        if (old_climate != null && old_climate.equals(wcs)) {
            return;
        }

        if (wcs != null) {
            changes.firePropertyChange(RunFileData.Elevation, null, wcs.elevation);
            changes.firePropertyChange(RunFileData.CliGenState, null, wcs.stateID);
            changes.firePropertyChange(RunFileData.CliGenStation, null, wcs.stationID);
            changes.firePropertyChange(RunFileData.CliGenStationName, null, wcs.station);
        }
    }

    @Override
    public void JCBCliGen_itemStateChanged(java.awt.event.ItemEvent event) {
        if (V_Cli == null) {
            return;
        }
        if (JCB_CliGen.getSelectedIndex() < 0) {
            return;
        }
        WindCliStation wcs = (WindCliStation) V_Cli.elementAt(
                JCB_CliGen.getSelectedIndex());
//		JTF_Elevation.setText(wcs.elevation);
        boolean flg = measurementUnits.equals(Util.USUnits);
        JTF_Elevation.setText(Util.convertMetersToFeet(wcs.elevation,
                flg ? Util.USUnits : Util.SIUnits));
        fireCliGen(wcs);
    }
    private WindCliStation old_wind;

    void fireWinGen(WindCliStation wcs) {
        if (old_wind != null && old_wind.equals(wcs)) {
            return;
        }
        if (wcs != null) {
            old_wind = wcs;
            changes.firePropertyChange(RunFileData.WinGenStation, null, wcs.stationID);
            changes.firePropertyChange(RunFileData.WindGenStationName, null, wcs.station);
        }
    }

    public void JCBWinGen_itemStateChanged(java.awt.event.ItemEvent event) {
        if (V_Win == null) {
            return;
        }
        System.out.println("JCBWG_iSC: " + event);
        WindCliStation iwcs = (WindCliStation) event.getItem();
        if (iwcs.interpFlg) {
            return;
        }
        if (JCB_WinGen.getSelectedIndex() < 0) {
            return;
        }
        WindCliStation wcs = (WindCliStation) V_Win.elementAt(JCB_WinGen.getSelectedIndex());
        LOGGER.debug("JCBWinGen_itemStateChanged: " + wcs.station);
        fireWinGen(wcs);
    }

    @Override
    public void JBUseMap_actionPerformed(java.awt.event.ActionEvent event) {

        //If you hold down shift it uses the new MapViewer
        if((event.getModifiers() & Event.SHIFT_MASK) == Event.SHIFT_MASK){

            final usda.weru.gis.gui.MapViewer viewer = new usda.weru.gis.gui.MapViewer();
            MapController control = viewer.getMapController();
            Coordinate center = new Coordinate(latLong.getLon(), latLong.getLat());
            control.setCenter(center);
            control.setZoomFactor(30.0d);
            viewer.demoMetaData(GISUtil.toLatLong(center));
            viewer.addPropertyChangeListener(usda.weru.gis.gui.MapViewer.PROP_SELECTEDLATLONG, new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    viewer.setVisible(false);
                    viewer.dispose();
                    if(c_weps != null){
                        manualLatLong = true;
//                        c_weps.rfd.setLatLong(viewer.getSelectedLatLong());
                        getCounty();
                        manualLatLong = false;
                        
                    }


                }
            });
            viewer.setVisible(true);

            return;
        }
        if (mv == null) {
            //			(new NotImplemented("Map")).setVisible(true);
            mv = new MapViewer();

            //hanlde the clean up
            mv.addWindowListener(new WindowAdapter() {

                @Override
                public void windowClosing(WindowEvent e) {
                    MapViewer temp = mv;
                    if(temp != null){
                        temp.removePropertyChangeListener(LocPanel.this);
                        temp.dm = null;
                        mv = null;
                    }
                }
            });

            mv.addPropertyChangeListener(this);
            DrawMap dm = new DrawMap(V_county, V_mainWinCli);
            dm.setLatLong(latLong.getLat(), latLong.getLon());
            dm.setSize(mv.JP_map.getSize());
            dm.addPropertyChangeListener(mv);
            mv.JP_map.add(dm);
            mv.dm = dm;
            mv.setSize(640, 480);
            mv.setVisible(true);


        } else {
            if (mv.getState() == MapViewer.ICONIFIED) {
                mv.setState(MapViewer.NORMAL);
            }
            mv.dm.setLatLong(latLong.getLat(), latLong.getLon());
            mv.setVisible(true);
            mv.requestFocus();
        }

    }
    public boolean manualLatLong = true;

    public void JTFLongitude_actionPerformed(java.awt.event.ActionEvent event) {
        try {
            manualLatLong = true;
            Util.checkNumericJTF(JP_main, JTF_Longitude, lon, RunFileData.Longitude, changes, Util.NoUnits);
            getCounty();
            latLong.setLongitude(JTF_Longitude.getText());
            latLong.setLongitudeSign(JL_Lon.getText());
            changes.firePropertyChange(RunFileData.LatLong, null, latLong.toString());
        } finally {
            manualLatLong = false;
        }
    }

    public void JTFLatitude_actionPerformed(java.awt.event.ActionEvent event) {
        try {
            manualLatLong = true;
            Util.checkNumericJTF(JP_main, JTF_Latitude, lat, RunFileData.Latitude, changes, Util.NoUnits);
            getCounty();
            latLong.setLatitude(JTF_Latitude.getText());
            latLong.setLatitudeSign(JL_Lat.getText());
            changes.firePropertyChange(RunFileData.LatLong, null, latLong.toString());
        } finally {
            manualLatLong = false;
        }

    }

    public void JTFElevation_actionPerformed(java.awt.event.ActionEvent event) {
        //Since the user has changed the elevation manually here, this flag is made true
        elevManual = true;
        Util.checkNumericJTF(JP_main, JTF_Elevation, elv,
                RunFileData.Elevation,
                changes, measurementUnits);

    }
    Vector V_countyInfo;

    protected void JCBStateActionPerformed(java.awt.event.ActionEvent evt) {
        //if (event.getStateChange() != ItemEvent.SELECTED) return;        

        if (JCB_State.getSelectedIndex() <= 0) { // none selected
            if (JCB_County.getItemCount() > 0) {
                JCB_County.removeAllItems();
            }
            return;
        }

        StateMap sm = null;
        Object o = JCB_State.getSelectedItem();
        if (o instanceof StateMap) {
            sm = (StateMap) o;
        } else if (o instanceof String) {
            String st = ((String) o).trim();
            sm = (StateMap) StateMap.ht.get(st);
        } else {
            //System.err.println("LP_JCBS_iSC: bad event class " + o.getClass());
        }
        if (sm == null) {
            //System.err.println("LP_JCBS_iSC: state not found " + o);
            return;
        }

        if (JCB_County.getItemCount() > 0) {
            JCB_County.removeAllItems();
        }
        V_countyInfo = (Vector) sm.countyVec.clone();
        if (V_countyInfo != null) {
            Collections.sort(V_countyInfo, new CountyMap());
        }
        if (V_countyInfo == null || V_countyInfo.size() == 0) {
            JCB_County.addItem("no data available");
        } else {
            JCB_County.addItem("none selected");
            for (Iterator scvi = V_countyInfo.iterator();
                    scvi.hasNext();) {
                CountyMap sc = (CountyMap) scvi.next();
                JCB_County.addItem(sc.name);
            }
        }
    }

    @Override
    protected void JCBCountyActionPerformed(java.awt.event.ActionEvent evt) {
        if (isLoading()) {
            return;
        }
        int cdx = JCB_County.getSelectedIndex();
        if (cdx == -1) {
            return;	// none selected, should not happen
        }
        if (cdx == 0) {
            if (manualLatLong) {
                return;
            }
            JTF_Latitude.setText("");
            changes.firePropertyChange(RunFileData.Latitude, null, "");
            JTF_Longitude.setText("");
            changes.firePropertyChange(RunFileData.Longitude, null, "");
            return;
        }


        CountyMap cm = (CountyMap) V_countyInfo.elementAt(cdx - 1);

        String countyState = cm.name + ", " + cm.state;

        changes.firePropertyChange(RunFileData.Site, oldSite, countyState.trim());

        if (manualLatLong) {
            return;
        }

        latLong.setLongitude(cm.longitude);
        latLong.setLatitude(cm.latitude);
        latLong.setLongitudeSign(cm.longitudeSign);
        latLong.setLatitudeSign(cm.latitudeSign);
        //The user has not changed the elevation manually here.
        // A Cligen station is being loaded and its default elevation will be loaded.
        elevManual = false;
        changes.firePropertyChange(RunFileData.LatLong, null, latLong.toString());
    }
    Vector<WindCliStation> V_Win = null;
    Vector<WindCliStation> V_Cli = null;

    private void makeCliList(String lat, String lon) {
        // reset distance to big number
//		for (Iterator wci = V_mainWinCli.iterator(); wci.hasNext();) {
//			WindCliStation rcws = (WindCliStation) wci.next();
//			rcws.distance = rcws.polarDistance;
//		}


        V_Cli = makeCliWinVector(lat, lon, WindCliStation.CliStation);

        // turn off listeners to avoid spurious changing of station

        java.awt.event.ItemListener[] lisarr = JCB_CliGen.getItemListeners();
//		Util.debugPrint(true, "JCB_iSC: " + lisarr.length);
        for (int idx = 0; idx < lisarr.length; idx++) {
            JCB_CliGen.removeItemListener(lisarr[idx]);
        }

        JCB_CliGen.removeAllItems();

        int selIdx = 0;
        int cnt = 0;
        for (Iterator wcsvi = V_Cli.iterator(); wcsvi.hasNext(); cnt++) {
            WindCliStation wcs = (WindCliStation) wcsvi.next();
            JCB_CliGen.addItem(wcs);
            if (wcs == null) {
                break; // empty climate file
            }
            if (cliGenStationID.equals(wcs.stationID) &&
                    cliGenStateID.equals(wcs.stateID) && isLoading()) {
                selIdx = cnt;
            }
        }
        if (selIdx >= JCB_CliGen.getItemCount()) {
            JCB_CliGen.setSelectedIndex(-1);
        } else {
            JCB_CliGen.setSelectedIndex(selIdx);
        }

        if (!notDoneWithInit) {
            fireCliGen((WindCliStation) JCB_CliGen.getItemAt(selIdx));
        }

        // turn on listeners
        for (int idx = 0; idx < lisarr.length; idx++) {
            JCB_CliGen.addItemListener(lisarr[idx]);
        }

        if (V_Cli.size() > 0) {
            WindCliStation wcs = (WindCliStation) JCB_CliGen.getSelectedItem();
            if (wcs == null) {
                return;
            }
            boolean flg = measurementUnits.equals(Util.USUnits);
            JTF_Elevation.setText(Util.convertMetersToFeet(wcs.elevation,
                    flg ? Util.USUnits : Util.SIUnits));
        }
        //Here we call setElevation again so that if the user has manually changed the
        //Elevation to another value, we can load it from the RunFileData i.e. weps.run
        //System.out.println("LocPanel-makeCliList:elevManual:"+elevManual);
        if (elevManual == true) {
            setElevation((PropertyChangeEvent) ht.get(RunFileData.Elevation));
        }
    }

    private void makeWindList(String lat, String lon) {

        V_Win = makeCliWinVector(lat, lon, WindCliStation.WinStation);

        // turn off listeners to avoid spurious changing of station

        java.awt.event.ItemListener[] lisarr = JCB_WinGen.getItemListeners();
//        Util.debugPrint(true, "JCB_iSC: " + lisarr.length);
        for (int idx = 0; idx < lisarr.length; idx++) {
            JCB_WinGen.removeItemListener(lisarr[idx]);
        }

        JCB_WinGen.removeAllItems();

        int selIdx = 0;
        int cnt = 0;
//Util.debugPrint(true, "LP_C_iSC: " + V_Win.size());
        for (Iterator wcsvi = V_Win.iterator(); wcsvi.hasNext(); cnt++) {
            WindCliStation wcs = (WindCliStation) wcsvi.next();
            if (wcs == null) {
                continue;
            }
            JCB_WinGen.addItem(wcs);
            if (windGenStationID.equals(wcs.stationID) && isLoading()) {
                selIdx = cnt;
            }
//Util.debugPrint(true, "LP_C_iSC: " + wcs);
        }
        if (selIdx >= JCB_WinGen.getItemCount()) {
            JCB_WinGen.setSelectedIndex(-1);
        } else {
            JCB_WinGen.setSelectedIndex(selIdx);
        }

        if (!notDoneWithInit) {
            fireWinGen((WindCliStation) JCB_WinGen.getItemAt(selIdx));
        }

        // turn on listeners
        for (int idx = 0; idx < lisarr.length; idx++) {
            JCB_WinGen.addItemListener(lisarr[idx]);
        }

    }
    private double windLimit = 160.0;
    private double climateLimit = 80.0;

    private Vector<WindCliStation> makeCliWinVector(String inpLat, String inpLon, int type) {

        //Util.debugPrint(true, "LP_mCWV: type = " + type);
//        Util.debugPrint(true, inpLat + " " + inpLon);
        Vector<WindCliStation> rtnvec = new Vector<WindCliStation>();

        double lon = 0.0;
        double lat = 0.0;
        double distanceLimit = 0;

        distanceLimit = (type == WindCliStation.CliStation) ? climateLimit : windLimit;

        /** It is an error to take absolute value of lat & long
         * Therefore take the values of latitude and longitude
         * as they are with their signs [positive or negative]
         */
        try {
            lon = Double.parseDouble(inpLon.trim());
            lat = Double.parseDouble(inpLat.trim());

        //   //System.out.println("makeCliWinVector:lon:"+lon+" lat:"+lat);
        } catch (NumberFormatException e) {
            //System.err.println("mCWV: " + e);
        }

        // establish distance from 0.0,0.0 to our station

        double stationDistance = Util.polarDistance(lat, lon, 0.0, 0.0);
        ////System.out.println("polar distance of the location from (0,0):"+stationDistance);
        WindCliStation cws = new WindCliStation();
        cws.distance = stationDistance;

        // find the station that is closest to our distance less the
        // radius from 0.0,0.0 -- if sdx < 0 indicates non-exact match

        cws.polarDistance = stationDistance - distanceLimit;
        int sdx = Collections.binarySearch(V_mainWinCli, cws, new WindCliStation.PolarCompareDistance());
        if (sdx < 0) {
            sdx *= -1;
        }

        // find the station that is closest to our distance plus the
        // radius from 0.0,0.0 -- if edx < 0 indicates non-exact match

        // find the station that is closest to our distance plus the
        // radius from 0.0,0.0 -- if edx < 0 indicates non-exact match

        cws.polarDistance = stationDistance + distanceLimit;
        int edx = Collections.binarySearch(V_mainWinCli, cws, new WindCliStation.PolarCompareDistance());
        if (edx < 0) {
            edx *= -1;
        }
        //If we give a very large search radius, then the edx value will be
        // size of V_mainWinCli vector's size + 1. so set edx back to the size of V_mainWinCli.size()
        if (edx > V_mainWinCli.size()) {
            edx = V_mainWinCli.size();
        }
//		java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
//		nf.setMinimumFractionDigits(2);
//		nf.setMaximumFractionDigits(2);
//		nf.format((double) Math.abs(cws.distance));

        // sdx > 0 indicates exact match, sdx < 0 is closest station

        double minDistance = Double.MAX_VALUE;
        WindCliStation closestWcs = null;

        /**
         * the algorithm used here is simple. each wind or cli station
         * has a distance from lat 0.0, lon 0.0 stored. if the distance
         * to a wcs differs from our lat & lon by more than the limit
         * distance then it cannot be close enough to us to appear in
         * our list. so, we only look at stations in that band. but
         * this only limits the scope of stations we have to look at
         * since stations as far apart as montana and arizona can be
         * roughly the same distance from 0.0, 0.0. so after limiting
         * the stations to a band, we then look at the circle that
         * surrounds us. finally, we keep track of the closest wind or
         * cli station since there is no guarantee that even one will
         * be within our distance limit.
         */        // look through windcli station list, sorted by distance from
        // 0.0, 0.0 (i.e their polar distance)and add those stations within radius of lat & lon
        for (int jdx = sdx; jdx < edx; jdx++) {
//			try {
            cws = V_mainWinCli.elementAt(jdx);

//			} catch (java.lang.ArrayIndexOutOfBoundsException e) {
//				break;
//			}

            //If we are searching for a climate station and
            // find a wind station, then ignore and vice versa
            if (cws.type != type) {
                continue;
            }

            cws.distance = Util.polarDistance(lat, lon, cws.lat, cws.lon);

            if (cws.distance < distanceLimit) {
                //Util.debugPrint(true, "LP_mCWV: adding station " + cws);
                rtnvec.add(cws);
            }
        }
        //  //System.out.println("distanceLimit:"+distanceLimit+" sdx-min:"+sdx+"  edx-max:"+edx+"   rtnvec size:"+rtnvec.size());
        // if nothing is close, search the entire list for the closest
        // station

        if (rtnvec.size() == 0) {
            for (int jdx = 0; jdx < V_mainWinCli.size(); jdx++) {
                cws = V_mainWinCli.elementAt(jdx);

                if (cws.type != type) {
                    continue;
                }

                cws.distance = Util.polarDistance(lat, lon, cws.lat, cws.lon);

                // track closest station in case none is within limit
                if (cws.distance < minDistance) {
                    minDistance = cws.distance;
                    closestWcs = cws;
                }
            }
            rtnvec.add(closestWcs);
        //  //System.out.println("rtnvec size zero-so minDistance:"+minDistance);
        }

        // loadFlg indicates load in process
        // must preserve selected stations

        if (cliGenStationID.length() > 0 && windGenStationID.length() > 0) {
            if (isLoading()) {
//                Util.debugPrint(true, "loadFlag == true");
                // check that current is in list
                int jdx = 0;
                for (jdx = 0; jdx < rtnvec.size(); jdx++) {
                    cws = rtnvec.elementAt(jdx);

                    if (cws == null) {
                        continue;
                    }

                    if (type == WindCliStation.CliStation) {
                        if (cliGenStationID.equals(cws.stationID) && cliGenStateID.equals(cws.stateID)) {
                            break;
                        }
                    } else {
                        if (windGenStationID.equals(cws.stationID)) {
                            break;
                        }
                    }
                }
//                Util.debugPrint(true, "jdx = " + jdx + " size = " + rtnvec.size() + " " + cws);

                /** station that has been selected i.e the station
                 *  matching the cliGenStationID or windGenStationID is not
                 *  in the rtnvec Vector -- add this station to rtnvec vector
                 */
                if (jdx == rtnvec.size()) {
//                    Util.debugPrint(true, "station not in list");
                    for (jdx = 0; jdx < V_mainWinCli.size(); jdx++) {
                        cws = (WindCliStation) V_mainWinCli.elementAt(jdx);
                        if (cws.type != type) {
                            continue;
                        }
                        if (type == WindCliStation.CliStation) {
                            if (cliGenStationID.equals(cws.stationID) &&
                                    cliGenStateID.equals(cws.stateID)) {
                                cws.distance = Util.polarDistance(lat, lon, cws.lat, cws.lon);
                                rtnvec.add(cws);
                                break;
                            }
                        } else {
                            if (windGenStationID.equals(cws.stationID)) {
                                cws.distance = Util.polarDistance(lat, lon, cws.lat, cws.lon);
                                rtnvec.add(cws);
                                break;
                            }
                        }
                    }
                }
            }
        }
        //Sort the rtnvec Vector according to the polar distance
        Collections.sort(rtnvec, new WindCliStation.CompareDistance());

        if (rtnvec.size() == 0) {
            rtnvec.add(closestWcs);
        }
        return rtnvec;
    }

    public void JLLon_mouseClicked(java.awt.event.MouseEvent event) {
        String hemi = JL_Lon.getText();

        // note this is backwards because we have not yet changed the display

        changes.firePropertyChange(RunFileData.LongitudeSign, null,
                (hemi.equals("E")) ? "-" : "+");

        JL_Lon.setText((hemi.equals("E")) ? "W" : "E");
        latLong.setLongitudeSign(JL_Lon.getText());
        loadFlg++;
        cliGenStationID = "";
        cliGenStateID = "";
        windGenStationID = "";
        changes.firePropertyChange(RunFileData.LatLong, null, latLong.toString());
        getCounty();
        loadFlg--;
    // changes.firePropertyChange(RunFileData.LatLong, null, latLong.toString());
    }

    public void JLLat_mouseClicked(java.awt.event.MouseEvent event) {
        String hemi = JL_Lat.getText();

        // note this is backwards because we have not yet changed the display

        changes.firePropertyChange(RunFileData.LatitudeSign, null,
                (hemi.equals("N")) ? "-" : "+");
        JL_Lat.setText((hemi.equals("N")) ? "S" : "N");
        latLong.setLatitudeSign(JL_Lat.getText());
        loadFlg++;
        cliGenStationID = "";
        cliGenStateID = "";
        windGenStationID = "";
        changes.firePropertyChange(RunFileData.LatLong, null, latLong.toString());
        getCounty();
        loadFlg--;
    //  changes.firePropertyChange(RunFileData.LatLong, null, latLong.toString());

    }

    public void JCBState_mousePressed(java.awt.event.MouseEvent event) {
//Util.debugPrint(true, "JCBS_mP:");
    }
    String runFilePath = "";

    public void JBWindFile_actionPerformed(java.awt.event.ActionEvent event) {
        WepsFileChooser jpc = new WepsFileChooser(WepsFileChooser.WIND, projDir,
                WepsFileChooser.SELECT);

        //System.out.println("projDir:"+projDir+"--currentProj:"+currentProj+"--lastRun:"+lastRun);
        runFilePath = currentProj + "\\" + lastRun;
        //Look for the windFile in this path and if it exists,
        //open the filechooser in this path
        String windFilePath = "";
        if (new File(windFile).isAbsolute()) {
            windFilePath = windFile;
        } else {
            windFilePath = runFilePath + "\\" + windFile;
        ////System.out.println("runFilePath:"+runFilePath+"--windFilePath:"+windFilePath);
        }
        if (windFilePath.length() > 0 && new File(windFilePath).exists()) {
            jpc.setCurrentDirectory(new de.schlichtherle.io.File(windFilePath));
        } else {
            jpc.setCurrentDirectory(new de.schlichtherle.io.File(projDir));
        }
        //set the tooltip of "home" button to "Home" instead of "Desktop"
        jpc.homeToolTip(jpc);
        //remove the NewFolder button
        jpc.disableNewFolder(jpc);

        if (jpc.showDialog(this.JP_main) == JFileChooser.APPROVE_OPTION) {
            // work with the picked item
            try {
                windFile = jpc.getSelectedFile().getCanonicalPath();
            } catch (java.io.IOException e) {
                //System.err.println("CP-SFap: " + e);
            }
            JTF_windFile.setText(new File(windFile).getName());
            changes.firePropertyChange(RunFileData.WindFile, null, windFile);
            changes.firePropertyChange(RunFileData.WindGenStationName, null, new File(windFile).getName());
        }

    }

    public void JBClimateFile_actionPerformed(java.awt.event.ActionEvent event) {
        WepsFileChooser jpc = new WepsFileChooser(WepsFileChooser.CLIMATE, projDir, WepsFileChooser.SELECT);

        //System.out.println("projDir:"+projDir+"--currentProj:"+currentProj+"--lastRun:"+lastRun);
        runFilePath = currentProj + "\\" + lastRun;
        //Look for the cliamteFile in this path and if it exists,
        //open the filechooser in this path
        String climateFilePath = "";
        if (new File(climateFile).isAbsolute()) {
            climateFilePath = climateFile;
        } else {
            climateFilePath = projDir;        //climateFilePath = runFilePath;
        ////System.out.println("runFilePath:"+runFilePath+"--climateFilePath:"+climateFilePath);
        }
        if (climateFilePath.length() > 0 && new File(climateFilePath).exists()) {
            jpc.setCurrentDirectory(new de.schlichtherle.io.File(climateFilePath));
        } else {
            jpc.setCurrentDirectory(new de.schlichtherle.io.File(projDir));
        }

        //set the tooltip of "home" button to "Home" instead of "Desktop"
        jpc.homeToolTip(jpc);
        //remove the NewFolder button
        jpc.disableNewFolder(jpc);

        if (jpc.showDialog(this.JP_main) == JFileChooser.APPROVE_OPTION) {
            // work with the picked item
            try {
                climateFile = jpc.getSelectedFile().getCanonicalPath();
            } catch (java.io.IOException e) {
                //System.err.println("CP-SFap: " + e);
            }

            //System.out.println(climateFilePath);

            JTF_climateFile.setText(new File(climateFile).getName());
            changes.firePropertyChange(RunFileData.ClimateFile, null, climateFile);
            changes.firePropertyChange(RunFileData.CliGenStationName, null, new File(climateFile).getName());
        }
    }
}
