/*
 * Copyright (C) 2008 Sun Microsystems, Inc. All rights reserved. Use is
 * subject to license terms.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the Lesser GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA.
 */

import org.jdic.web.BrMapBalloonSprite;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.imageio.ImageIO;
import javax.print.*;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.JobName;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import java.awt.*;
import java.awt.print.Printable;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.geom.Point2D;
import java.awt.image.RenderedImage;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStreamReader;
import java.io.FileWriter;
import org.jdic.web.BrMapMousePos;

//import com.TopoLogica.NetCAM.*;


import java.io.BufferedReader;

import java.net.URL;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.Vector;

import org.jdic.web.BrMap;
import org.jdic.web.BrMapSprite;

/**
 * VideoMon Mobile.
 * alvarse@alvarestech.com
 */
public class MapExplorer extends javax.swing.JFrame
{
  
    MapExplorer() {
        BrMap.DESIGN_MODE = false;
        initComponents(); 

        progressBar.setVisible(false);

        //look and fill group
	javax.swing.ButtonGroup group = new javax.swing.ButtonGroup();

	final UIManager.LookAndFeelInfo[] LFs = UIManager.getInstalledLookAndFeels();
	for(int i = 0; i < LFs.length; i++) {
            JRadioButtonMenuItem lfsMenuItem = (JRadioButtonMenuItem)viewMenu.add(
                    new JRadioButtonMenuItem(LFs[i].getName()));
            group.add(lfsMenuItem);
            lfsMenuItem.setSelected(UIManager.getLookAndFeel().getName().equals(LFs[i].getName()));
            lfsMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1 + i, ActionEvent.ALT_MASK));
            lfsMenuItem.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    JRadioButtonMenuItem rb = (JRadioButtonMenuItem) evt.getSource();
                    if(rb.isSelected() ){
                        for(int j = 0; j < LFs.length; j++) {
                            if (rb.getText().equals(LFs[j].getName())) {
                                try {
                                    UIManager.setLookAndFeel(LFs[j].getClassName());
                                    SwingUtilities.updateComponentTreeUI(MapExplorer.this);
                                } catch (Exception ex) {
                                    rb.setEnabled(false);
                                }
                            }
                        }
                    }
                }
            });
	}
        setBounds(-1, -1, 1024, 768);
                     
  final Thread thread = new Thread(){
            @SuppressWarnings("empty-statement")
            @Override
      public void run(){
         double centerLat = 0, centerLng = 0;
        while(true){try{
                URL u = new URL("http://vpn.lab.unb.br:2947/w");
                BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream()));
                br.readLine();
                String dadoGPS = br.readLine();
                    if (dadoGPS.charAt(5) == 'O'){
                	System.out.println(dadoGPS);
                
                double latitude = gps1 (dadoGPS);
                double longitude = gps2 (dadoGPS);
                double distancia = BrMap.getDistance(latitude, longitude, centerLat, centerLng);
                  if ( distancia > 300) {             
                    GPSPoint track = new GPSPoint(); 
                    track.GPSPoint(latitude, longitude);
                    track.add(brMap);
                    System.out.println(centerLat);
                    System.out.println(distancia);
   }
                centerLat=latitude; 
                centerLng=longitude;
                System.out.println(centerLat);
                    }
      }catch(Exception e){
         e.printStackTrace();
                          }
       try{sleep(5000);}catch(Exception e){};
                     }
                	}

   public double gps1(String dado) {

        StringTokenizer tokens = new StringTokenizer(dado, " "); 
    	tokens.nextToken();
		long timemili = Long.parseLong(tokens.nextToken().substring(0, 10));
                double eph, currentLat, currentLng, centerLat, centerLng, angulo;
                Vector<double[]> previousposition = new Vector<double[]>();
		timemili++; //arredondar (tempo em sec)
		timemili-=7200; //-2 horas de greenwitch
		timemili*=1000; //em milisec
		Date date = new Date((long)timemili);
		tokens.nextToken();
		String lat = tokens.nextToken(), lng = tokens.nextToken();
		currentLat=Double.parseDouble(lat);
		currentLng=Double.parseDouble(lng);

  
               System.out.println(currentLat);
               //System.out.println(currentLng);
               return currentLat;  
               //return currentLng; 
   }
  public double gps2(String dado) {
        
        StringTokenizer tokens = new StringTokenizer(dado, " "); 
    	tokens.nextToken();
		long timemili = Long.parseLong(tokens.nextToken().substring(0, 10));
                double eph, currentLat, currentLng, centerLat, centerLng, angulo;
                Vector<double[]> previousposition = new Vector<double[]>();
		timemili++; //arredondar (tempo em sec)
		timemili-=7200; //-2 horas de greenwitch
		timemili*=1000; //em milisec
		Date date = new Date((long)timemili);
		tokens.nextToken();
		String lat = tokens.nextToken(), lng = tokens.nextToken();
		currentLat=Double.parseDouble(lat);
		currentLng=Double.parseDouble(lng);
 
               System.out.println(currentLng);
               //return currentLat;  
               return currentLng; 
                  
  }
      
	//	String altura = tokens.nextToken(), epv = tokens.nextToken();
	//	try{
	//		eph = Double.parseDouble(tokens.nextToken());
	//	}catch(NumberFormatException erro){eph=40.0;}
	//	try{
	//		angulo = Double.parseDouble(tokens.nextToken());
	//		angulo = Math.toRadians(angulo);
	//	}catch(NumberFormatException erro){angulo=0.0;}
	//	//campos[4].setText(tokens.nextToken()); //atualiza o campo da velocidade
	//	tokens = new StringTokenizer(date.toGMTString(), " ");
	//	String sdate = tokens.nextToken()+"-"+tokens.nextToken()+"-"+tokens.nextToken();
	//	String shora = tokens.nextToken();
		//campos[5].setText(sdate);
		//campos[6].setText(shora);
                             
        };
        
        
        thread.start();
                   
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        statusPanel = new javax.swing.JPanel();
        edLng = new javax.swing.JTextField();
        lbLat = new javax.swing.JLabel();
        edLat = new javax.swing.JTextField();
        lbLng = new javax.swing.JLabel();
        cbGrid = new javax.swing.JCheckBox();
        edScale = new javax.swing.JTextField();
        lbMeter = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        cbInGrade = new javax.swing.JCheckBox();
        tbArea = new javax.swing.JToolBar();
        cbSelectWorkingArea = new javax.swing.JToggleButton();
        btResetSelection = new javax.swing.JButton();
        tbMetro = new javax.swing.JToggleButton();
        tbComposite = new javax.swing.JToggleButton();
        lbAddress = new javax.swing.JLabel();
        edAddress = new javax.swing.JTextField();
        bnGo = new javax.swing.JButton();
        pnCentral = new javax.swing.JPanel();
        brMap = new MapClipper();
        mainJMenuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        miOpen = new javax.swing.JMenuItem();
        miSave = new javax.swing.JMenuItem();
        miOZIExport = new javax.swing.JMenuItem();
        miPrint = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JSeparator();
        miExit = new javax.swing.JMenuItem();
        viewMenu = new javax.swing.JMenu();
        toolsMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("VideoMon Mobile");
        setIconImage(new javax.swing.ImageIcon(getClass().getResource("/images/icon.png")).getImage());
        setName("mainFrame"); // NOI18N

        jPanel2.setLayout(new java.awt.BorderLayout(2, 2));

        statusPanel.setRequestFocusEnabled(false);

        lbLat.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbLat.setText("Latitude:");
        lbLat.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);

        lbLng.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lbLng.setText("Longitude:");

        cbGrid.setText("Grid:");
        cbGrid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbGridActionPerformed(evt);
            }
        });

        edScale.setText("10000");

        lbMeter.setText("m");

        cbInGrade.setSelected(true);
        cbInGrade.setText("gg°mm'ss\"");
        cbInGrade.setFocusable(false);
        cbInGrade.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        cbInGrade.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        cbInGrade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbInGradeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(lbLat, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(edLat, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbLng, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(edLng, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbInGrade)
                .addGap(24, 24, 24)
                .addComponent(cbGrid)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(edScale, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbMeter, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lbLat, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .addComponent(edLat, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .addComponent(lbLng, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .addComponent(edLng, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .addComponent(cbInGrade, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(cbGrid, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(edScale, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .addComponent(lbMeter, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
            .addComponent(progressBar, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jPanel2.add(statusPanel, java.awt.BorderLayout.PAGE_END);

        tbArea.setRollover(true);
        tbArea.setMaximumSize(new java.awt.Dimension(506, 27));
        tbArea.setMinimumSize(new java.awt.Dimension(0, 0));
        tbArea.setName("Map Working Area Setup"); // NOI18N

        cbSelectWorkingArea.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/sel_zoom.png"))); // NOI18N
        cbSelectWorkingArea.setFocusable(false);
        cbSelectWorkingArea.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        cbSelectWorkingArea.setMargin(new java.awt.Insets(0, 0, 0, 0));
        cbSelectWorkingArea.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/sel_area.png"))); // NOI18N
        cbSelectWorkingArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbSelectWorkingAreaActionPerformed(evt);
            }
        });
        tbArea.add(cbSelectWorkingArea);

        btResetSelection.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/sel_auto.png"))); // NOI18N
        btResetSelection.setEnabled(false);
        btResetSelection.setFocusable(false);
        btResetSelection.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btResetSelection.setMargin(new java.awt.Insets(0, 0, 0, 0));
        btResetSelection.setMaximumSize(null);
        btResetSelection.setMinimumSize(null);
        btResetSelection.setPreferredSize(null);
        btResetSelection.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btResetSelection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btResetSelectionActionPerformed(evt);
            }
        });
        tbArea.add(btResetSelection);

        tbMetro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/metro.png"))); // NOI18N
        tbMetro.setFocusable(false);
        tbMetro.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbMetro.setMargin(new java.awt.Insets(0, 0, 0, 0));
        tbMetro.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbMetro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tbMetroActionPerformed(evt);
            }
        });
        tbArea.add(tbMetro);

        tbComposite.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/mapover.png"))); // NOI18N
        tbComposite.setFocusable(false);
        tbComposite.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbComposite.setMargin(new java.awt.Insets(0, 0, 0, 0));
        tbComposite.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbComposite.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tbCompositeActionPerformed(evt);
            }
        });
        tbArea.add(tbComposite);

        lbAddress.setText(" Location:");
        tbArea.add(lbAddress);

        edAddress.setText("SAL/SUL, Quadra 01, Bloco M, Sala 801, Edifício Libertas, Brasilia, Brasil");
        edAddress.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                edAddressMouseClicked(evt);
            }
        });
        edAddress.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edAddressActionPerformed(evt);
            }
        });
        edAddress.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                edAddressKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                edAddressKeyTyped(evt);
            }
        });
        tbArea.add(edAddress);

        bnGo.setText("Go");
        bnGo.setFocusable(false);
        bnGo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bnGo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bnGo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bnGoActionPerformed(evt);
            }
        });
        tbArea.add(bnGo);

        jPanel2.add(tbArea, java.awt.BorderLayout.PAGE_START);

        pnCentral.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                pnCentralComponentResized(evt);
            }
        });

        brMap.setPreferredSize(new java.awt.Dimension(0, 0));
        brMap.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                brMapPropertyChange(evt);
            }
        });

        javax.swing.GroupLayout pnCentralLayout = new javax.swing.GroupLayout(pnCentral);
        pnCentral.setLayout(pnCentralLayout);
        pnCentralLayout.setHorizontalGroup(
            pnCentralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(brMap, javax.swing.GroupLayout.DEFAULT_SIZE, 737, Short.MAX_VALUE)
        );
        pnCentralLayout.setVerticalGroup(
            pnCentralLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(brMap, javax.swing.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
        );

        jPanel2.add(pnCentral, java.awt.BorderLayout.CENTER);

        fileMenu.setText("File");
        fileMenu.setToolTipText("File Operations");

        miOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        miOpen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/open.png"))); // NOI18N
        miOpen.setText("Open File...");
        miOpen.setToolTipText("Opens a document in this window");
        miOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miOpenActionPerformed(evt);
            }
        });
        fileMenu.add(miOpen);

        miSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        miSave.setText("Save Page As...");
        miSave.setToolTipText("Saves this document as a file");
        miSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miSaveActionPerformed(evt);
            }
        });
        fileMenu.add(miSave);

        miOZIExport.setText("Export As OZI map...");
        miOZIExport.setToolTipText("Saves this document as a file");
        miOZIExport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miOZIExportActionPerformed(evt);
            }
        });
        fileMenu.add(miOZIExport);

        miPrint.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        miPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/print.png"))); // NOI18N
        miPrint.setText("Print");
        miPrint.setToolTipText("Prints this page");
        miPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miPrintActionPerformed(evt);
            }
        });
        fileMenu.add(miPrint);
        fileMenu.add(jSeparator3);

        miExit.setText("Exit");
        miExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                miExitActionPerformed(evt);
            }
        });
        fileMenu.add(miExit);

        mainJMenuBar.add(fileMenu);

        viewMenu.setText("View");
        mainJMenuBar.add(viewMenu);

        toolsMenu.setText("NetCam");
        toolsMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toolsMenuActionPerformed(evt);
            }
        });

        jMenuItem1.setText("Cameras");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        toolsMenu.add(jMenuItem1);

        mainJMenuBar.add(toolsMenu);

        setJMenuBar(mainJMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 737, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

private void cbInGradeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbInGradeActionPerformed
// TODO add your handling code here:
        
}//GEN-LAST:event_cbInGradeActionPerformed

private void miOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miOpenActionPerformed
    //brMain.open();
}//GEN-LAST:event_miOpenActionPerformed

private void miSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSaveActionPerformed
    //brMain.save();
}//GEN-LAST:event_miSaveActionPerformed

private void miPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miPrintActionPerformed
    //brMain.print();
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(OrientationRequested.LANDSCAPE);
    aset.add(new Copies(1));
    aset.add(new JobName("Map", null));
    // locate a print service that can handle the request
    PrintService[] services =
            PrintServiceLookup.lookupPrintServices(flavor, aset);
    if (services.length > 0) {
            System.out.println("selected printer " + services[0].getName());
            /// create a print job for the chosen service
            DocPrintJob pj = services[0].createPrintJob();
            try {
                    //Create a Doc object to hold the print data.
                    Doc doc = new SimpleDoc(brMap, flavor, null);
                    //print mapM
                    pj.print(doc, aset);
            } catch(PrintException e) {
                    System.err.println(e);
            }
    }
}//GEN-LAST:event_miPrintActionPerformed

private void miExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miExitActionPerformed
    dispose();
}//GEN-LAST:event_miExitActionPerformed

private void btResetSelectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btResetSelectionActionPerformed
    ((MapClipper)brMap).bAutoArea = true;
    ((MapClipper)brMap).rcArea = new Rectangle(
            68, 32, 
            ((MapClipper)brMap).getWidth() - 68 - 2, ((MapClipper)brMap).getHeight() - 32 - 28);
    if(null!=brMapBack){
        brMapBack.setBounds(((MapClipper)brMap).rcArea);
    }
    ((MapClipper)brMap).repaint();    
    btResetSelection.setEnabled(false);
}//GEN-LAST:event_btResetSelectionActionPerformed

private void cbSelectWorkingAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSelectWorkingAreaActionPerformed
    ((MapClipper)brMap).setSelectionMode(cbSelectWorkingArea.isSelected());
    
    
}//GEN-LAST:event_cbSelectWorkingAreaActionPerformed

private void tbMetroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbMetroActionPerformed
    brMap.getSprites().clear();
    if( tbMetro.isSelected() ){
        SPBMetro mt = new SPBMetro();    
        mt.add(brMap);
    }    
    brMap.repaint();    
}//GEN-LAST:event_tbMetroActionPerformed

private void miOZIExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miOZIExportActionPerformed
    JFileChooser fc = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
      "Map Files", "bmp");
    fc.setFileFilter(filter);
    if( JFileChooser.APPROVE_OPTION == fc.showDialog(MapExplorer.this, "Export As OZI Map") ){
        ((MapClipper)brMap).saveMap(fc.getSelectedFile().getAbsolutePath());
        ((MapClipper)brMap).addBoundAsSprite();
        ((MapClipper)brMap).repaint();                            
    }
}//GEN-LAST:event_miOZIExportActionPerformed

private void pnCentralComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_pnCentralComponentResized
    //((MapClipper)brMap).setSize(pnCentral.getSize());    
}//GEN-LAST:event_pnCentralComponentResized

private void tbCompositeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbCompositeActionPerformed
    if( tbComposite.isSelected() ){
        brMapBack = new org.jdic.web.BrMapOver();
        brMapBack.setMapProvider(brMap.getMapProvider());        
        brMapBack.setSyncMap(brMap);        
        brMapBack.bnZoomMinus.setVisible(false);
        brMapBack.bnZoomPlus.setVisible(false);
        brMapBack.sbZoomLevel.setVisible(false);
        brMap.getCentralPanel().add(brMapBack);
   //brMap.setZoomLevel(16);
   //brMap.setViewCenter("-15.763088, -47.872657");
        if(((MapClipper)brMap).bAutoArea){
            ((MapClipper)brMap).rcArea.width /= 2;
            ((MapClipper)brMap).rcArea.height /= 2;
            ((MapClipper)brMap).bAutoArea = false;
            btResetSelection.setEnabled(true);
        }
        brMapBack.setBounds( ((MapClipper)brMap).rcArea );  
        brMap.repaint();        
    } else {
        brMap.getCentralPanel().remove(brMapBack);
        brMap.validate();
        brMapBack = null;
        brMap.repaint();
    }    
}//GEN-LAST:event_tbCompositeActionPerformed

private void bnGoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bnGoActionPerformed
    if( brMap.isMapReady() ){
        brMap.execJS( ":_findAddress(\"" + edAddress.getText().replace("\'", "\\\'") +   "\")" );
    }
}//GEN-LAST:event_bnGoActionPerformed

private void edAddressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edAddressActionPerformed
    bnGoActionPerformed(evt);
}//GEN-LAST:event_edAddressActionPerformed

private void edAddressKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_edAddressKeyPressed
}//GEN-LAST:event_edAddressKeyPressed

private void edAddressKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_edAddressKeyTyped
    //BasicLookAndFeel
    edAddress.setBackground(UIManager.getColor("text"));
}//GEN-LAST:event_edAddressKeyTyped

private void edAddressMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_edAddressMouseClicked
    // TODO add your handling code here:
}//GEN-LAST:event_edAddressMouseClicked

private void toolsMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toolsMenuActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_toolsMenuActionPerformed

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    // TODO add your handling code here:
  // netcam();
    System.out.println("entrou menu");
  // com.TopoLogica.NetCAM.Main netcam = new com.TopoLogica.NetCAM.Main();
     System.out.println("saiu menu");
}//GEN-LAST:event_jMenuItem1ActionPerformed

    private void brMapPropertyChange(java.beans.PropertyChangeEvent evt) {
            String stPN = evt.getPropertyName();
            if(stPN.equals("securityIcon")
              || stPN.equals("navigatedURL")
              || stPN.equals("progressBar")
            ){
                String stNV = (String)evt.getNewValue();
                if(null==stNV)
                    stNV = "";
                String st[] = stNV.split(",");
                /*
                if(stPN.equals("navigatedURL")) {
                    edAddress.setText( st[0] );
                    stOldParams = "";
                    brXMLTree.empty();
                } else*/ if(stPN.equals("progressBar")) {
                    int iMax = Integer.parseInt(st[0]),
                        iPos = Integer.parseInt(st[1]);
                    if(0==iMax){
                        progressBar.setVisible(false);
                    } else {
                        progressBar.setMaximum(iMax);
                        progressBar.setValue(iPos);
                        progressBar.setVisible(true);
                    }
                } /*else if(stPN.equals("securityIcon")) {
                    bnLocker.setVisible(!stNV.equals("0"));
                } */
            } else if( stPN.equals("mouseGeoPos") ){
               Point2D gp = ((BrMapMousePos)evt.getNewValue()).getMouseGeoPos();
               Double Latitude = gp.getX();
               Double Longitude = gp.getY();
               edLat.setText( cbInGrade.isSelected() ? BrMap.getGrade(Latitude, BrMap.LAT) : ("" + Latitude));
               edLng.setText( cbInGrade.isSelected() ? BrMap.getGrade(Longitude, BrMap.LNG) : ("" + Longitude));
            }
             // brMap.setZoomLevel(16);
              brMap.setViewCenter("-15.763088, -47.872657");
              
 /*      new Thread(){
            @Override
            @SuppressWarnings("empty-statement")
      public void run(){
        while(true){try{
                URL u = new URL("http://vpn.lab.unb.br:2947/w");
                BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream()));
                br.readLine();
                String dadoGPS = br.readLine();
                    if (dadoGPS.charAt(5) == 'O'){
                	System.out.println(dadoGPS);
                	                          }else{
                	                          continue;
                	                               }
                	 }catch(Exception e){
                	e.printStackTrace();
                	                    }try{sleep(5000);}catch(Exception e){};}
                	}
                }.start();         
    */
              
    }

    private void cbGridActionPerformed(java.awt.event.ActionEvent evt) {
        brMap.repaint();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {public void run() {
                new MapExplorer().setVisible(true);
            
            
                
        }});
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    javax.swing.JButton bnGo;
    org.jdic.web.BrMap brMap;
    javax.swing.JButton btResetSelection;
    javax.swing.JCheckBox cbGrid;
    javax.swing.JCheckBox cbInGrade;
    javax.swing.JToggleButton cbSelectWorkingArea;
    javax.swing.JTextField edAddress;
    javax.swing.JTextField edLat;
    javax.swing.JTextField edLng;
    javax.swing.JTextField edScale;
    javax.swing.JMenu fileMenu;
    javax.swing.JMenuItem jMenuItem1;
    javax.swing.JPanel jPanel2;
    javax.swing.JSeparator jSeparator3;
    javax.swing.JLabel lbAddress;
    javax.swing.JLabel lbLat;
    javax.swing.JLabel lbLng;
    javax.swing.JLabel lbMeter;
    javax.swing.JMenuBar mainJMenuBar;
    javax.swing.JMenuItem miExit;
    javax.swing.JMenuItem miOZIExport;
    javax.swing.JMenuItem miOpen;
    javax.swing.JMenuItem miPrint;
    javax.swing.JMenuItem miSave;
    javax.swing.JPanel pnCentral;
    javax.swing.JProgressBar progressBar;
    javax.swing.JPanel statusPanel;
    javax.swing.JToolBar tbArea;
    javax.swing.JToggleButton tbComposite;
    javax.swing.JToggleButton tbMetro;
    javax.swing.JMenu toolsMenu;
    javax.swing.JMenu viewMenu;
    // End of variables declaration//GEN-END:variables
    
    org.jdic.web.BrMapOver brMapBack;
    
    class MapClipper extends BrMap  implements Printable {
        public Rectangle rcArea;

        public MapClipper(){
            super();
        }
        public MapClipper(
            int _iMapIndex,
            double _viewCenterLatitude,
            double _viewCenterLongitude,
            int _viewZoomLevel,
            int _viewType)
        {
            super(
                _iMapIndex,
                _viewCenterLatitude,
                _viewCenterLongitude,
                _viewZoomLevel,
                _viewType);
        }
        public void addBoundAsSprite()
        {
            if(null!=rcArea){
                BrMapSprite pg = new BrMapSprite();
                pg.createFromPoints(this, new Point[] {
                    new Point(rcArea.x, rcArea.y),
                    new Point(rcArea.x + rcArea.width, rcArea.y),
                    new Point(rcArea.x + rcArea.width, rcArea.y + rcArea.height),
                    new Point(rcArea.x, rcArea.y + rcArea.height)
                });
               getSprites().add(pg);
            }
        }
        public void paintGrid(Graphics g) {
            if(isMapReady() && cbGrid.isSelected()){
                Graphics2D g2 = (Graphics2D)g;
                try{
                    double gridStep = Double.parseDouble(edScale.getText());

                    String result = execJS( "_fromPointToLatLng("
                        + (rcArea.x + rcArea.width/2) + ","
                        + (rcArea.y + rcArea.height/2) + ")" );
                    double m2p = getMeter2pixel( Double.parseDouble( result.split(",")[0]) );

                    double step = gridStep/m2p;
                    if( (step >= 3.0) && ((rcArea.height/step)<1000.0) ){
                        //the number of point in grid is big enouth
                        double iX0 = rcArea.x;
                        double iY0 = rcArea.y;
                        if(true){
                            //grid lines
                            final Color colorsR[] = new Color[] {
                                new Color(1.0F, 0.0F, 0.0F, 1.0F),
                                new Color(0.0F, 1.0F, 0.0F, 1.0F),
                                new Color(0.0F, 0.0F, 1.0F, 1.0F),
                                new Color(1.0F, 1.0F, 0.0F, 1.0F),
                                new Color(0.0F, 1.0F, 1.0F, 1.0F),

                                new Color(0.5F, 0.0F, 0.0F, 1.0F),
                                new Color(0.0F, 0.5F, 0.0F, 1.0F),
                                new Color(0.0F, 0.0F, 0.5F, 1.0F),
                                new Color(0.5F, 0.5F, 0.0F, 1.0F),
                                new Color(0.0F, 0.5F, 0.5F, 1.0F)
                            };

                            int iC = 0;
                            for(double iX = iX0; iX<(rcArea.x + rcArea.width); iX += step){
                                g2.setColor( colorsR[ iC % colorsR.length ] );
                                g2.drawLine((int)iX, rcArea.y, (int)iX, rcArea.y + rcArea.height - 1);
                                ++iC;
                            }
                            iC = 0;
                            for(double iY = iY0; iY<(rcArea.y + rcArea.height); iY += step){
                                g2.setColor( colorsR[ iC % colorsR.length ] );
                                g2.drawLine(rcArea.x, (int)iY, rcArea.x + rcArea.width - 1, (int)iY);
                                ++iC;
                            }
                        } else {
                            final Color colorsR[] = new Color[] {
                                new Color(1.0F, 0.0F, 0.0F, 0.15F),
                                new Color(0.0F, 1.0F, 0.0F, 0.15F),
                                new Color(0.0F, 0.0F, 1.0F, 0.15F)
                            };

                            final Color colorsC[] = new Color[] {
                                new Color(0.5F, 0.5F, 0.0F, 0.15F),
                                new Color(0.0F, 0.5F, 0.5F, 0.15F),
                                new Color(0.5F, 0.0F, 0.5F, 0.15F)
                            };

                            boolean bStartLine = false;
                            int iRow = 0;
                            for(double iX = iX0; iX<(rcArea.x + rcArea.width); iX += step){
                                ++iRow;
                                int iCol = 0;
                                bStartLine = !bStartLine;
                                boolean bDraw = bStartLine;
                                for(double iY = iY0; iY<(rcArea.y + rcArea.height); iY += step){
                                   ++iCol;
                                   g2.setColor( bDraw
                                     ? colorsR[ iRow % colorsR.length ]
                                     : colorsC[ iCol % colorsC.length ]);
                                   Rectangle rc = new Rectangle(
                                           (int)iX, (int)iY,
                                           (int)Math.min( step - 0.5, rcArea.x + rcArea.width - iX),
                                           (int)Math.min( step - 0.5, rcArea.y + rcArea.height - iY) );
                                   g2.fill(rc);
                                   bDraw = !bDraw;
                                }
                            }
                        }
                    }
                }catch(Exception e){}
            }
        }

        @Override
        public void paintContent(Graphics g) {
            super.paintContent(g);
            if(null!=rcArea){
                paintGrid(g);
                Graphics2D g2 = (Graphics2D)g;
                g2.setColor(Color.BLACK);
                g2.drawRect(
                    rcArea.x, rcArea.y,
                    rcArea.width-1, rcArea.height-1
                );
            }
        }
        
        public boolean bAutoArea = true;

        @Override
        public void onSelectionRectChanged(Rectangle rc, boolean bShow)
        {
            if(cbSelectWorkingArea.isSelected()){
                ((MapClipper)brMap).rcArea = rc;
                if(!bShow){
                    SwingUtilities.invokeLater(new Runnable(){ public void run() {                    
                        bAutoArea = false;                    
                        btResetSelection.setEnabled(true);
                        if(null!=brMapBack){
                            brMapBack.setBounds(((MapClipper)brMap).rcArea);
                        }
                        repaint();                                        
                    }});
                } else {
                    repaint();
                }        
            }
        }
        public void saveMap(String stFN)
        {
            System.out.println("save to " + stFN);
            if(null!=rcArea){
                Image im = new BufferedImage(
                        rcArea.width, 
                        rcArea.height, 
                        BufferedImage.TYPE_INT_BGR);
                if(null!=im){
                    Graphics g = im.getGraphics();
                    try{
                       g.translate(-rcArea.x, -rcArea.y); 
                       paintClientArea(g, true);
                    } finally {
                       g.dispose(); 
                    }
                    try{
                        stFN = stFN.toLowerCase();
                        if(!stFN.endsWith(".bmp")){
                           stFN += ".bmp";
                        }
                        File fn = new File(stFN);
                        ImageIO.write((RenderedImage)im, "BMP", fn);

                        int read = 1024;
                        InputStreamReader rd = new InputStreamReader(
                                getClass().getResourceAsStream("temp_ozf.map"));
                        char[] buf = new char[read];
                        StringBuffer sb = new StringBuffer(read);
                        while( -1 != (read = rd.read(buf, 0, read)) ){
                           sb.append(buf, 0, read);
                        }
                        rd.close();
                        String stFormat = sb.toString();


                        String result = execJS("_fromPointToLatLng("
                            + rcArea.x + "," + rcArea.y + ","
                            + (rcArea.x + rcArea.width) + "," + rcArea.y + ","
                            + (rcArea.x + rcArea.width) + "," + (rcArea.y + rcArea.height) + ","
                            + rcArea.x + "," + (rcArea.y + rcArea.height)+ ");"
                        );
                        String args[] = result.split(",");
                        for(int i=0; i<4; ++i){
                            double d = Double.parseDouble(args[i*2]);
                            String toRepl = String.format("$(4lt%d)", i+1);
                            stFormat = stFormat.replace(toRepl, "" + (int)Math.floor(d));

                            toRepl = String.format("$(mlat%d)", i+1);
                            String that = String.format("%2.6f", ((d - Math.floor(d))*60.0));
                            stFormat = stFormat.replace(toRepl, that );

                            d = Double.parseDouble(args[i*2+1]);
                            toRepl = String.format("$(4ln%d)", i+1);
                            stFormat = stFormat.replace(toRepl, "" + (int)Math.floor(d));

                            toRepl = String.format("$(mlng%d)", i+1);
                            that = String.format("%2.6f", ((d - Math.floor(d))*60.0));
                            stFormat = stFormat.replace(toRepl, that );
                        }

                        stFormat = stFormat.replace("$(8lat1)", args[0]);
                        stFormat = stFormat.replace("$(8lng1)", args[1]);
                        stFormat = stFormat.replace("$(8lat2)", args[2]);
                        stFormat = stFormat.replace("$(8lng2)", args[3]);
                        stFormat = stFormat.replace("$(8lat3)", args[4]);
                        stFormat = stFormat.replace("$(8lng3)", args[5]);
                        stFormat = stFormat.replace("$(8lat4)", args[6]);
                        stFormat = stFormat.replace("$(8lng4)", args[7]);

                        stFormat = stFormat.replace("$(scale)", "not impl yet");//scale in metters/pixel

                        String w5 = String.format("%5d", rcArea.width);
                        stFormat = stFormat.replace("$(5w)", w5);
                        String h5 = String.format("%5d", rcArea.height);
                        stFormat = stFormat.replace("$(5h)", h5);
                        stFormat = stFormat.replace("$(w)", ""+ rcArea.width);
                        stFormat = stFormat.replace("$(h)", ""+ rcArea.height);

                        stFormat = stFormat.replace("$(BMP)", fn.getName());

                        int iPos = stFN.lastIndexOf('.');
                        String stBMP = stFN.substring(0, iPos);
                        String stOZF2 = stBMP;
                        stBMP += "_ozf.map";
                        stOZF2 += ".ozf2";

                        stFormat = stFormat.replace("$(OZF2)", stOZF2);

                        FileWriter wt = new FileWriter(stBMP);

                        wt.write(stFormat);
                        wt.close();
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                }
            }
        }

        @Override
        public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
            if(pageIndex == 0 && null!=rcArea) {
                    Graphics2D g2d = (Graphics2D)g;
                    g2d.translate(
                       pf.getImageableX() - rcArea.x, 
                       pf.getImageableY() - rcArea.y);
                    g2d.scale(
                            pf.getImageableWidth()/rcArea.width, 
                            pf.getImageableHeight()/rcArea.height);
                    paintClientArea(g2d, true);
                    return Printable.PAGE_EXISTS;
            }
            return Printable.NO_SUCH_PAGE;
        }

        @Override
        public void reshape(int x, int y, int width, int height)
        {
            super.reshape(x, y, width, height);
            if( bAutoArea ){
                rcArea = new Rectangle(68, 32, width - 68 - 2, height - 32 - 28);
            }
            if(null!=brMapBack){
                brMapBack.setBounds(rcArea);
            }    
        }

        final Color colorSuccess = new Color(128, 255, 128);
        final Color colorFail = new Color(255, 128, 128);
        @Override
        public void onFoundAddress(final String[] args) {
            SwingUtilities.invokeLater(new Runnable(){ public void run() {
                edAddress.setBackground(
                   ( 4 == args.length)
                   ? colorSuccess
                   : colorFail);
                if(4 == args.length){
                    setZoomLevel(Math.max(14, getZoomLevel()));
                    setViewCenter(args[2] + "," + args[3]);
                    BrMapBalloonSprite bl = new BrMapBalloonSprite(
                        "<html><b>Location:</b><br><b style=\"color:green\">" + edAddress.getText() + "</b></html>",
                        getPoint(getViewCenter())
                    );
                    bl.add(brMap);
                }        
            }});//end posponed operation
        }

      //  public void netcam(){
  //         com.TopoLogica.NetCAM.Main NetCam = new com.TopoLogica.NetCAM.Main();
       // }
        
    }
          

}


