/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csa.gui;

import csa.Global;
import csa.config.ConfigChangedListener;
import csa.config.Configuration;
import csa.config.ConfigurationPanel;
import csa.config.theme.Theme;
import csa.event.EventSupport;
import csa.gui.bitmapfont.BitmapFont;
import csa.gui.components.CSAInternalFrame;
import csa.gui.components.CSAMacMenuInternalFrame;
import csa.gui.components.CSAView;
import csa.gui.components.ModalInternalFrame;
import csa.gui.dialogs.CreditPanel;
import csa.gui.panels.LogPanel;
import csa.gui.panels.TipOfDayGUI;
import csa.gui.panels.WindowablePanel;
import csa.jmom.game.GameMainMenuPanel;
import csa.jmom.game.GamePanel;
import csa.jmom.unit.UnitDataPanel;
import csa.tiletools.graphics.ImageSourceEdit;
import csa.tiletools.map.MapEdit;
import csa.tiletools.particle.ParticleEngineDataPanel;
import csa.tiletools.sprites.SpriteDataPanel;
import csa.tiletools.tiles.Tile;
import csa.tiletools.tiles.TileDataPanel;
import csa.tiletools.worldgen.heroextant.WorldGenerator;
import csa.tiletools.worldgen.mapgen.MapGen;
import csa.tiletools.worldgen.worldgen.WorldGen;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.util.*;
import javax.help.*;
import javax.swing.*;
import javax.swing.plaf.UIResource;

/**
 *
 * @author salchr
 */
public class CSAMainFrame extends javax.swing.JFrame
            implements
                        CSAView,
                        java.awt.event.AWTEventListener,
                        ConfigChangedListener
{
    static boolean isMac = Global.getOSName().toUpperCase().indexOf("MAC")!=-1;
    class JM extends JMenu
    {
        @Override public boolean isTopLevelMenu()
        {
            isRolloverEnabled();
            return true;
        }
        @Override public boolean isRolloverEnabled()
        {
            return false;
        }
    }
    private static int MENU_HIDE_DELAY = 20;
    private static int POP_DISPLAY_START_Y = 10;
    static HashMap <String, UIResource> windowedDefaults;
    static HashMap <String, UIResource> fullscreenDefaults;

    static Color fFontColor;
    static Color fBackColor;
    static
    {
        fFontColor = new Color(100,200,100);
        fBackColor = new Color(00,00,00);
        windowedDefaults = new HashMap <String, UIResource>();
        fullscreenDefaults = new HashMap <String, UIResource>();

        UIDefaults uiDefaults = UIManager.getDefaults();
        Enumeration eenum = uiDefaults.keys();
        while (eenum.hasMoreElements())
        {
            try
            {
                Object key = eenum.nextElement();
                Object val = uiDefaults.get(key);
                String keyString = key.toString();
                if (val == null) continue;
                String valueString = val.toString();
                if (valueString.toUpperCase().indexOf("COLOR") != -1)
                {
                    if (val instanceof UIResource)
                        windowedDefaults.put(keyString, (UIResource)val);
                }

                if (valueString.toUpperCase().indexOf("R=0,G=0,B=0") != -1)
                    fullscreenDefaults.put(keyString, new javax.swing.plaf.ColorUIResource(fFontColor));
                if (keyString.toUpperCase().indexOf("BACKGROUND") != -1)
                    fullscreenDefaults.put(keyString, new javax.swing.plaf.ColorUIResource(fBackColor));
            }
            catch (Throwable e)
            {
                e.printStackTrace();
            }
        }

//        fullscreenDefaults.put("Panel.background", new javax.swing.plaf.ColorUIResource(0,0,0));
        UIManager.put("TabbedPane.tabsOpaque", Boolean.FALSE);
        UIManager.put("TabbedPane.contentOpaque", Boolean.FALSE);


        uiDefaults = UIManager.getDefaults();
        uiDefaults.put("TabbedPane.contentOpaque", Boolean.FALSE);
        uiDefaults.put("TabbedPane.tabsOpaque", Boolean.FALSE);
//        uiDefaults.put("TabbedPane.highlight", new javax.swing.plaf.ColorUIResource(new Color(0,255,0,100)));

        if (Global.mMainWindow != null)
        SwingUtilities.updateComponentTreeUI(  Global.mMainWindow );
    }

    Vector<JPanel> mPanels = new Vector<JPanel>();
    Vector<JInternalFrame> mFrames = new Vector<JInternalFrame>();
    JPanel mCurrentPanel=null;
    int sizeX=1024;
    int sizeY=768;
    HashMap<Object, Boolean> dum = new HashMap<Object, Boolean>();
    HashMap<Object, MouseAdapter> mAdapter = new HashMap<Object, MouseAdapter>();
    HashMap<Object, javax.swing.event.InternalFrameAdapter> fl = new HashMap<Object, javax.swing.event.InternalFrameAdapter>();

    private static Dimension internalFrameDifference=null;
    
    //the original resolution before our program is run.
    private DisplayMode dispModeOld = null;

    //a reference to the GraphicsDevice for changing resolution and making
    //this window fullscreen.
    //get a reference to the device.
    private GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();

    //the resolution in which we want to change the monitor to.
    private DisplayMode dispMode = new DisplayMode(1024, 768, 32, 60);

    private boolean fullscreen=false;
    private int overMenu=0;
    int enterCounter=0;
    private JPopupMenu pop=new JPopupMenu();
    private CSAMacMenuInternalFrame macFrame = null;
    private JMenuBar tmenuBar = new JMenuBar();
    private boolean mDebugDisplayed = false;
    private boolean mLogDisplayed = false;
    private int inEvent=0;

    private JDesktopPane mDesktop = new JDesktopPane();
    public JDesktopPane getDesktop(){return mDesktop;}

    /**
     * Creates new form CSAMainFrame
     */
    public CSAMainFrame() {
        //initComponents();
        Global.mMainWindow = this;

        ToolTipManager.sharedInstance().setDismissDelay(15000);
        Theme t = Configuration.getConfiguration().getCurrentTheme();
        getFrame().setIconImage(t.getImage(("RedIconSmall.png")));
        Configuration.getConfiguration().setMainFrame(getFrame());
        initComponents();

        if (!device.isFullScreenSupported())
        {
            jCheckBoxMenuItem1.setEnabled(false);
        }

        mainPanel.removeAll();
        mainPanel.setLayout(new java.awt.BorderLayout());
        mainPanel.add(mDesktop, java.awt.BorderLayout.CENTER);
        resetMainPanel();

        titlePanel1.setPortalView(this);
        Configuration.getConfiguration().init();
        Configuration.getConfiguration().addConfigListerner(this);
        windowMenu.removeAll();
        windowMenu.add(jMenuItemCloseWin);
        windowMenu.add(jSeparator7);
        windowMenu.add(jMenuItemLogWindow);
        windowMenu.add(jMenuItemDebug);
        windowMenu.add(jSeparator7);
        if (Configuration.getConfiguration().isStartInFullScrren())
        {
            jCheckBoxMenuItem1.setSelected(true);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run()
                {
                    toFullscreen();
                }
            });
        }
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run()
            {
                if (titlePanel1 != null)
                    titlePanel1.sizeChanged();
                Configuration.getConfiguration().fireSizeChanged(false);
                Configuration.getConfiguration().fireConfigChanged();
            }
        });

        getFrame().setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        titlePanel1.playMusic();
        titlePanel1.startGlitter();

    }

    public final JFrame getFrame()
    {
        return this;
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        titlePanel1 = new csa.gui.panels.TitlePanel();
        statusPanel = new javax.swing.JPanel();
        jLabelActivePlayer = new javax.swing.JLabel();
        jLabelActivePlayer1 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        fileMenu = new JM();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItem10 = new javax.swing.JMenuItem();
        jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        toolsMenu = new javax.swing.JMenu();
        jMenuItemParticle = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem9 = new javax.swing.JMenuItem();
        jMenuItemTileResourcer = new javax.swing.JMenuItem();
        jMenuItemMapResourcer = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        jMenuItem3 = new javax.swing.JMenuItem();
        gameMenu = new javax.swing.JMenu();
        jMenuItem11 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenuItem7 = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JPopupMenu.Separator();
        jMenuItem8 = new javax.swing.JMenuItem();
        windowMenu = new javax.swing.JMenu();
        windowMenu = new JM();
        jMenuItemCloseWin = new javax.swing.JMenuItem();
        jSeparator7 = new javax.swing.JPopupMenu.Separator();
        jMenuItemLogWindow = new javax.swing.JMenuItem();
        jMenuItemDebug = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem12 = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        helpMenu = new JM();
        aboutMenuItem = new javax.swing.JMenuItem();
        jMenuItem31 = new javax.swing.JMenuItem();
        jMenuItem19 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TT - Tile Tools");
        setMinimumSize(new java.awt.Dimension(1024, 768));
        setPreferredSize(new java.awt.Dimension(1024, 768));

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

        javax.swing.GroupLayout titlePanel1Layout = new javax.swing.GroupLayout(titlePanel1);
        titlePanel1.setLayout(titlePanel1Layout);
        titlePanel1Layout.setHorizontalGroup(
            titlePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 813, Short.MAX_VALUE)
        );
        titlePanel1Layout.setVerticalGroup(
            titlePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 507, Short.MAX_VALUE)
        );

        mainPanel.add(titlePanel1, java.awt.BorderLayout.CENTER);

        getContentPane().add(mainPanel, java.awt.BorderLayout.CENTER);

        statusPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        statusPanel.setPreferredSize(new java.awt.Dimension(400, 19));

        jLabelActivePlayer.setText("Player: ");
        jLabelActivePlayer.setEnabled(false);

        jLabelActivePlayer1.setText("None");
        jLabelActivePlayer1.setEnabled(false);

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                .addContainerGap(681, Short.MAX_VALUE)
                .addComponent(jLabelActivePlayer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelActivePlayer1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelActivePlayer)
                    .addComponent(jLabelActivePlayer1))
                .addGap(0, 1, Short.MAX_VALUE))
        );

        getContentPane().add(statusPanel, java.awt.BorderLayout.SOUTH);

        fileMenu.setForeground(Color.black);
        fileMenu.setText("File");

        jMenu2.setText("Extra");

        jMenuItem2.setText("Generate XML-Class");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem2);
        jMenu2.add(jSeparator2);

        fileMenu.add(jMenu2);

        jMenuItem10.setText("Configuration");
        jMenuItem10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem10ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem10);

        jCheckBoxMenuItem1.setText("Fullscreen");
        jCheckBoxMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxMenuItem1ActionPerformed(evt);
            }
        });
        fileMenu.add(jCheckBoxMenuItem1);

        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        toolsMenu.setText("Tools");

        jMenuItemParticle.setText("Particle Editor");
        jMenuItemParticle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemParticleActionPerformed(evt);
            }
        });
        toolsMenu.add(jMenuItemParticle);

        jMenuItem1.setText("Image Collector");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        toolsMenu.add(jMenuItem1);

        jMenuItem9.setText("Sprite Manager");
        jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem9ActionPerformed(evt);
            }
        });
        toolsMenu.add(jMenuItem9);

        jMenuItemTileResourcer.setText("Tile Manager");
        jMenuItemTileResourcer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemTileResourcerActionPerformed(evt);
            }
        });
        toolsMenu.add(jMenuItemTileResourcer);

        jMenuItemMapResourcer.setText("Map Maker");
        jMenuItemMapResourcer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemMapResourcerActionPerformed(evt);
            }
        });
        toolsMenu.add(jMenuItemMapResourcer);
        toolsMenu.add(jSeparator3);

        jMenuItem3.setText("Test BitMapFont");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        toolsMenu.add(jMenuItem3);

        menuBar.add(toolsMenu);

        gameMenu.setText("Game");

        jMenuItem11.setText("GAME");
        jMenuItem11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem11ActionPerformed(evt);
            }
        });
        gameMenu.add(jMenuItem11);

        jMenuItem4.setText("Unit Editor");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        gameMenu.add(jMenuItem4);

        jMenuItem5.setText("People Editor");
        gameMenu.add(jMenuItem5);

        jMenuItem6.setText("Building Editor");
        gameMenu.add(jMenuItem6);

        jMenuItem7.setText("Tech-Tree Editor");
        gameMenu.add(jMenuItem7);
        gameMenu.add(jSeparator4);

        jMenuItem8.setText("Battlefield Simulator");
        gameMenu.add(jMenuItem8);

        menuBar.add(gameMenu);

        windowMenu.setForeground(Color.black);
        windowMenu.setText("Window");

        jMenuItemCloseWin.setText("Close current Window");
        jMenuItemCloseWin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemCloseWinActionPerformed(evt);
            }
        });
        windowMenu.add(jMenuItemCloseWin);
        windowMenu.add(jSeparator7);

        jMenuItemLogWindow.setText("Log Window");
        jMenuItemLogWindow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemLogWindowActionPerformed(evt);
            }
        });
        windowMenu.add(jMenuItemLogWindow);

        jMenuItemDebug.setText("Debug Window");
        jMenuItemDebug.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemDebugActionPerformed(evt);
            }
        });
        windowMenu.add(jMenuItemDebug);
        windowMenu.add(jSeparator1);

        jMenuItem12.setText("Dummy Window");
        windowMenu.add(jMenuItem12);

        menuBar.add(windowMenu);

        helpMenu.setForeground(Color.black);
        helpMenu.setText("Help");

        aboutMenuItem.setText("About");
        aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutMenuItemActionPerformed(evt);
            }
        });
        helpMenu.add(aboutMenuItem);

        jMenuItem31.setText("Credits");
        jMenuItem31.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem31ActionPerformed(evt);
            }
        });
        helpMenu.add(jMenuItem31);

        jMenuItem19.setText("Help");
        jMenuItem19.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem19ActionPerformed(evt);
            }
        });
        helpMenu.add(jMenuItem19);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        getAccessibleContext().setAccessibleName("TT - Tile Tool");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void jCheckBoxMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMenuItem1ActionPerformed

        if (inEvent>0) return;
        fullscreen = !jCheckBoxMenuItem1.isSelected();
        // not yet in fullscreen - lets switch
        if (!fullscreen)
        {
            toFullscreen();
        }
        else
        {
            toWindowed();
        }
    }//GEN-LAST:event_jCheckBoxMenuItem1ActionPerformed

    private void jMenuItem10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem10ActionPerformed
        ConfigurationPanel c = new ConfigurationPanel();
        addPanel(c);
        setMainPanel(c);
        windowMe(c,1018,680, "Configuration");
    }//GEN-LAST:event_jMenuItem10ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        csa.util.XMLClassBuilder builder= new csa.util.XMLClassBuilder();
        builder.setVisible(true);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItemTileResourcerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemTileResourcerActionPerformed
        TileDataPanel p = new TileDataPanel();
        addPanel(p);
        setMainPanel(p);
    }//GEN-LAST:event_jMenuItemTileResourcerActionPerformed

    private void jMenuItemMapResourcerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemMapResourcerActionPerformed
        MapEdit p = new MapEdit();
        addPanel(p);
        setMainPanel(p);
    }//GEN-LAST:event_jMenuItemMapResourcerActionPerformed

    private void jMenuItemCloseWinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCloseWinActionPerformed
        if (mCurrentPanel instanceof Windowable)
        {
             removePanel((Windowable)mCurrentPanel);
        }
    }//GEN-LAST:event_jMenuItemCloseWinActionPerformed

    private void jMenuItemDebugActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDebugActionPerformed
        if (Configuration.getConfiguration().isDebugOff()) return;
        if (!(Configuration.getConfiguration().getDebugEntity() instanceof csa.gui.panels.LogPanel)) return;
        LogPanel c = (LogPanel) Configuration.getConfiguration().getDebugEntity();
        if (Configuration.getConfiguration().isDebugWindowFrameable())
        {
            if (mDebugDisplayed)
            {
                return;
            }
            CSAInternalFrame frame = new CSAInternalFrame();
            frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter() {
                @Override
                public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                    mDebugDisplayed = false;
                }
            });
            frame.addPanel(c);
            addInternalFrame(frame);
            frame.setTitle("Debug Window");
            frame.setVisible(true);
            mDebugDisplayed = true;
            return;
        }
        else if (mDebugDisplayed)
        {
            setMainPanel(c);
            mCurrentPanel = c.getPanel();
            return;
        }
        addPanel(c);
        setMainPanel(c);
        mDebugDisplayed = true;
    }//GEN-LAST:event_jMenuItemDebugActionPerformed

    private void jMenuItemLogWindowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLogWindowActionPerformed
        LogPanel c = (LogPanel) Configuration.getConfiguration().getLogEntity();
        if (mLogDisplayed)
        {
            setMainPanel(c);
            mCurrentPanel = c.getPanel();
            return;
        }
        addPanel(c);
        setMainPanel(c);
        windowMe(c, 300, 400, "Log");
        mLogDisplayed = true;
    }//GEN-LAST:event_jMenuItemLogWindowActionPerformed

    private void jMenuItem31ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem31ActionPerformed
        CreditPanel p = new CreditPanel();
        addPanel(p);
        setMainPanel(p);
        windowMe(p,950,650, "Credits");
    }//GEN-LAST:event_jMenuItem31ActionPerformed

    private void jMenuItem19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem19ActionPerformed
        String helpHS = "main.hs";
        HelpSet hs;
        ClassLoader cl = CSAView.class.getClassLoader();
        try {
            java.net.URL hsURL = HelpSet.findHelpSet(cl, helpHS);
            hs = new HelpSet(null, hsURL);
        }
        catch (Exception ee)
        {
            // Say what the exception really is
            System.out.println( "HelpSet " + ee.getMessage());
            System.out.println("HelpSet "+ helpHS +" not found");
            return;
        }
        // Create a HelpBroker object:
        JHelpContentViewer hsv = new JHelpContentViewer(hs);
        HelpBroker hb = hs.createHelpBroker();

        if (hb instanceof DefaultHelpBroker)
        {
            WindowPresentation wp = ((DefaultHelpBroker)hb).getWindowPresentation();
            wp.createHelpWindow();
            java.awt.Window w  = wp.getHelpWindow();
            if (w instanceof JFrame)
            {
                JFrame helpFrame = (JFrame)w;
                // remove printer buttons!
                printComponents(helpFrame,0);

                WindowablePanel wap = new WindowablePanel();
                JRootPane rpane = helpFrame.getRootPane();
                Container cpane = rpane.getContentPane();

                if (cpane instanceof JComponent)
                {
                    wap.setContent((JComponent)cpane, "Help");
                    addPanel(wap);
                    setMainPanel(wap);
                    windowMe(wap, 950, 650, "Help");
                }

            }

        }
    }//GEN-LAST:event_jMenuItem19ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        ImageSourceEdit p = new ImageSourceEdit();
        addPanel(p);
        setMainPanel(p);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
        Configuration C = Configuration.getConfiguration();
        if (C.getMainFrame() == null) {
            return;
        }
        AboutPanel ac = new AboutPanel();
        ModalInternalFrame modal = new ModalInternalFrame("About", C.getMainFrame().getRootPane(), C.getMainFrame(), ac);
        modal.setVisible(true);
    }//GEN-LAST:event_aboutMenuItemActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed

        String text = "Der Fuchs sprang ueber das gelbe Pferd und jauchzte dabei vor Glueck! Das Pferd allerdings wurde ganz Bang vor Schreck und tratt aus - und traf eine entsetzte Maus.";
        try
        {
            BitmapFont digi =  Tile.buildBitmapFont("Font", "CSAFont");
            
            digi.setKerningPercent(10);
            digi.setSpecialKerning(true);
            digi = digi.getDerivat(100);
            
            BufferedImage image = digi.drawText(text, 800);
            titlePanel1.setImage( image );

        }
        catch (Throwable e)
        {
            e.printStackTrace();
        }


    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        UnitDataPanel p = new UnitDataPanel();
        addPanel(p);
        setMainPanel(p);
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed
        SpriteDataPanel p = new SpriteDataPanel();
        addPanel(p);
        setMainPanel(p);
    }//GEN-LAST:event_jMenuItem9ActionPerformed

    boolean gameMode = false;
    csa.event.MasterEventListener keyListener = null;
    private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed
        
        initGame();
    }//GEN-LAST:event_jMenuItem11ActionPerformed

    private void jMenuItemParticleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemParticleActionPerformed
        ParticleEngineDataPanel p = new ParticleEngineDataPanel();
        addPanel(p);
        setMainPanel(p);
    }//GEN-LAST:event_jMenuItemParticleActionPerformed
    
    
    // as of now! -> one way ticket!
    // only in fullscreen
    // to be invoked AFTER toFullscreen()
    // or BEFOR toWindowed()
    private void setMenu(boolean b)
    {
        if ((fullscreen) && (b))
        {
            java.awt.Toolkit.getDefaultToolkit().addAWTEventListener(this, java.awt.AWTEvent.MOUSE_MOTION_EVENT_MASK | java.awt.AWTEvent.MOUSE_EVENT_MASK);
            if (!isMac)
            {
                createPopup();

            }
            else
            {
                createMacPopup();

            }
        }
        else if ((fullscreen) && (!b))
        {
            java.awt.Toolkit.getDefaultToolkit().removeAWTEventListener(this);
            if (!isMac)
            {
                addEnter(pop, false);

                int i=0;
                while (pop.getComponentCount()>0)
                {
                    java.awt.Component m = pop.getComponent(i);
                    pop.remove(m);
                    if (m instanceof JMenu)
                    {
                        menuBar.add((JMenu)m);
                    ((JMenu)m).setMenuLocation(0, m.getPreferredSize().height);
                    }
                }

            }
            else
            {
                addEnter(macFrame, false);
                removeInternalFrame(macFrame);
                macFrame = null;
                int i=0;
                while (tmenuBar.getComponentCount()>0)
                {
                    java.awt.Component m = tmenuBar.getComponent(i);
                    tmenuBar.remove(m);
                    if (m instanceof JMenu)
                    {
                        menuBar.add((JMenu)m);
                    ((JMenu)m).setMenuLocation(0, m.getPreferredSize().height);
                    }
                }

            }
        }
        // no other combination is supported!
    }
    
    void printComponents(Container c, int depth)
    {
//        System.out.println(""+depth+". "+c.getName()+" "+c);
        depth++;
        for (int i=0; i<c.getComponentCount();i++)
        {
            Component com = c.getComponent(i);
            Container parent = com.getParent();
            if (com instanceof Container)
            {
                printComponents((Container) com, depth);
                if (parent instanceof javax.swing.JToolBar)
                {
                    if (i>2)
                    {
                        parent.remove(com);
                        i--;
                    }
                }
            }
            else
            {
                System.out.println(""+depth+". "+com.getName()+" "+com);
            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu gameMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
    private javax.swing.JLabel jLabelActivePlayer;
    private javax.swing.JLabel jLabelActivePlayer1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem10;
    private javax.swing.JMenuItem jMenuItem11;
    private javax.swing.JMenuItem jMenuItem12;
    private javax.swing.JMenuItem jMenuItem19;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem31;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JMenuItem jMenuItem7;
    private javax.swing.JMenuItem jMenuItem8;
    private javax.swing.JMenuItem jMenuItem9;
    private javax.swing.JMenuItem jMenuItemCloseWin;
    private javax.swing.JMenuItem jMenuItemDebug;
    private javax.swing.JMenuItem jMenuItemLogWindow;
    private javax.swing.JMenuItem jMenuItemMapResourcer;
    private javax.swing.JMenuItem jMenuItemParticle;
    private javax.swing.JMenuItem jMenuItemTileResourcer;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private javax.swing.JPopupMenu.Separator jSeparator4;
    private javax.swing.JPopupMenu.Separator jSeparator7;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JPanel statusPanel;
    private csa.gui.panels.TitlePanel titlePanel1;
    private javax.swing.JMenu toolsMenu;
    private javax.swing.JMenu windowMenu;
    // End of variables declaration//GEN-END:variables


    @Override
    public int getUsableFrameHeight()
    {
        int height;
        height = mainPanel.getHeight();
        return height;
    }
    @Override
    public int getUsableFrameWidth()
    {
        int width;
        width = mainPanel.getWidth();
        return width;
    }

    public void addInternalFrame(final CSAInternalFrame frame)
    {
        frame.setParent(this);
        Theme t = Configuration.getConfiguration().getCurrentTheme();
        frame.setFrameIcon( new ImageIcon(t.getImage(("RedIconSmall.png"))));

        mFrames.add(frame);
        getMainPanel().add(frame);
        getMainPanel().setComponentZOrder(frame, 0);
        final javax.swing.event.InternalFrameAdapter l = new javax.swing.event.InternalFrameAdapter()
        {
            javax.swing.event.InternalFrameAdapter ll=this;
            @Override public void internalFrameClosed(javax.swing.event.InternalFrameEvent e)
            {
                removeInternalFrame(frame);
                frame.removeInternalFrameListener(fl.get(frame));
                
            }
        };
        frame.addInternalFrameListener(l);
        fl.put(frame, l);
    }

    @Override
    public void removeInternalFrame(CSAInternalFrame frame)
    {
        mFrames.removeElement(frame);
        getMainPanel().remove(frame);
        
        if (((Windowable)frame.getPanel()) != null)
            ((Windowable)frame.getPanel()).closing();
        
        frame.removeInternalFrameListener(fl.get(frame));
    }

    private void createPopup()
    {
        pop.setLayout(new BoxLayout(pop, BoxLayout.LINE_AXIS));
        dum = new HashMap<Object, Boolean>();
        int i=0;
        int w=0;
        while (menuBar.getMenuCount()>0)
        {
            final JMenu m = menuBar.getMenu(i);
            w+=m.getWidth();
            w++; // GAP of 1
            m.setMenuLocation(0, m.getPreferredSize().height);
            menuBar.remove(m);
            pop.add(m);
        }
        w-=3; // first or last no gap, whatever
        JLabel filler = new JLabel("");

        // TODO take resolution from Configuration
        filler.setPreferredSize(new java.awt.Dimension((dispMode.getWidth())-(w+1),1));
        pop.add(filler);
        addEnter(pop, true);
        java.awt.Toolkit.getDefaultToolkit().addAWTEventListener(this, java.awt.AWTEvent.MOUSE_MOTION_EVENT_MASK | java.awt.AWTEvent.MOUSE_EVENT_MASK);
    }

    private void createMacPopup()
    {
        macFrame = new CSAMacMenuInternalFrame();
        //hide everything
        macFrame.setVisible(false);

        //remove the frame from being displayable.
        macFrame.dispose();

        //remove borders around the frame
        macFrame.setUndecorated(true);

        //show the frame


        // if not 2 buffers switching back to windowed mode
        // results (at least with me) in Exceptions
        //macFrame.createBufferStrategy(2); // 2 buffers


        macFrame.setSize(menuBar.getSize());
        int i=0;
        while (menuBar.getMenuCount()>0)
        {
            final JMenu m = menuBar.getMenu(i);

            menuBar.remove(m);
            tmenuBar.add(m);
        }
        macFrame.getContentPane().add(tmenuBar);
        //macFrame.pack();

        //macFrame.setVisible(false);
        macFrame.setLocation(0, 0);

        macFrame.setParent(this);
        addInternalFrame(macFrame);

        addEnter(macFrame, true);


        java.awt.Toolkit.getDefaultToolkit().addAWTEventListener(this, java.awt.AWTEvent.MOUSE_MOTION_EVENT_MASK | java.awt.AWTEvent.MOUSE_EVENT_MASK);
    }

    private void createMenuBar()
    {
        java.awt.Toolkit.getDefaultToolkit().removeAWTEventListener(this);
        if (!isMac)
        {
            addEnter(pop, false);

            int i=0;
            while (pop.getComponentCount()>0)
            {
                java.awt.Component m = pop.getComponent(i);
                pop.remove(m);
                if (m instanceof JMenu)
                {
                    menuBar.add((JMenu)m);
                ((JMenu)m).setMenuLocation(0, m.getPreferredSize().height);
                }
            }

        }
        else
        {
            addEnter(macFrame, false);
            removeInternalFrame(macFrame);
            macFrame = null;
            int i=0;
            while (tmenuBar.getComponentCount()>0)
            {
                java.awt.Component m = tmenuBar.getComponent(i);
                tmenuBar.remove(m);
                if (m instanceof JMenu)
                {
                    menuBar.add((JMenu)m);
                ((JMenu)m).setMenuLocation(0, m.getPreferredSize().height);
                }
            }

        }


    }

    void addEnter(java.awt.Component c, boolean set)
    {
        if (c instanceof java.awt.Container)
        for (int j=0;j<((java.awt.Container)c).getComponentCount();j++)
        {
            final java.awt.Component mc = ((java.awt.Container)c).getComponent(j);
            if(set)
            {
                dum.put(mc, false);
                MouseAdapter adapter= new java.awt.event.MouseAdapter() {
                    @Override public void mouseEntered(java.awt.event.MouseEvent evt) {
                        enterCounter=MENU_HIDE_DELAY;
                        dum.put(mc, true);}
                    @Override public void mouseExited(java.awt.event.MouseEvent evt) {
                        dum.put(mc, false);}
                };
                mAdapter.put(mc, adapter);

                mc.addMouseListener(adapter);
            }
            else
            {
                mc.removeMouseListener(mAdapter.get(mc));
                dum.remove(mc);
                mAdapter.remove(mc);
            }

            addEnter((java.awt.Container)mc, set);
        }
        if (c instanceof JMenu)
        {
            for (int j=0;j<((JMenu)c).getMenuComponentCount();j++)
            {
                final java.awt.Component mc = ((JMenu)c).getMenuComponent(j);
                if(set)
                {
                    dum.put(mc, false);
                    MouseAdapter adapter= new java.awt.event.MouseAdapter() {
                        @Override public void mouseEntered(java.awt.event.MouseEvent evt) {
                            enterCounter=MENU_HIDE_DELAY;
                            dum.put(mc, true);}
                        @Override public void mouseExited(java.awt.event.MouseEvent evt) {
                            dum.put(mc, false);}
                    };
                    mAdapter.put(mc, adapter);
                    mc.addMouseListener(adapter);
                }
                else
                {
                    mc.removeMouseListener(mAdapter.get(mc));
                    dum.remove(mc);
                    mAdapter.remove(mc);
                }
                addEnter((java.awt.Container)mc, set);
            }
        }
    }

    private void resetOverMenu()
    {
        if (!fullscreen) return;
        Set entries = dum.entrySet();
        Iterator it = entries.iterator();
        while (it.hasNext())
        {
            java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
            dum.put(entry.getKey(), false);
        }
    }

    boolean overMenu()
    {
        Set entries = dum.entrySet();
        Iterator it = entries.iterator();
        while (it.hasNext())
        {
            java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
            Boolean value = (Boolean) entry.getValue();

            if (value)
            {
                return true;
            }
        }
        if (enterCounter>0) enterCounter--;
        if (enterCounter>0) return true;
        return false;
    }

    @Override
    public void eventDispatched(java.awt.AWTEvent event)
    {
        if (!fullscreen) return;

        if (ModalInternalFrame.isModalCount>0) return;

        boolean noPosEvent = false;
        String pos = event.paramString();
        
        int startInString = pos.indexOf("e(");
        int endInString = pos.indexOf("),button");
        
        if (endInString<0)
        {
            endInString = pos.indexOf("),clickCount");
        }
        
        if ((endInString<0) || (startInString<0))
            return;
        
        // System.out.println("Pos " +pos);
        
        pos = pos.substring(startInString+2, endInString);

        String x = pos.substring(0, pos.indexOf(","));
        String y = pos.substring(pos.indexOf(",")+1);
        int Y = Integer.parseInt(y);
        
//        System.out.println("Pos: " +Y);
        
        if (Y>POP_DISPLAY_START_Y)
        {
            if (!overMenu())
            {
                if (!isMac)
                    pop.setVisible(false);
                else
                {



                    Set entries = dum.entrySet();
                    Iterator it = entries.iterator();
                    while (it.hasNext())
                    {
                        java.util.Map.Entry entry = (java.util.Map.Entry) it.next();


                        if (entry.getKey() instanceof JMenu)
                        {
                            JMenu mi= (JMenu)entry.getKey();
                            mi.getPopupMenu().setVisible(false);
                        }

                    }
                    macFrame.setVisible(false);
                }
            }
        }
        else
        {
                if (!isMac)
                {

                    if (pop.isVisible()) return;
                    pop.show(getFrame(), 0, 0);
                }
                else
                {

                macFrame.setVisible(true);

                }
        }
        if (event.paramString().indexOf("button=1") != -1)
        {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run()
                {
                    resetOverMenu();
                }
            });
        }
    }
    void setMySize()
    {
        getFrame().setMinimumSize(new java.awt.Dimension(sizeX,sizeY));
        getFrame().setMaximumSize(new java.awt.Dimension(sizeX,sizeY));
        getFrame().setPreferredSize(new java.awt.Dimension(sizeX,sizeY));
        getFrame().setSize(sizeX,sizeY);
        getFrame().doLayout();
        getFrame().validate();
    }

    public void preStartMatch()
    {
        titlePanel1.stopMusic();
        titlePanel1.stopGlitter();
    }
    public void postMatch()
    {
        titlePanel1.playMusic();
        titlePanel1.startGlitter();
    }

    public void addPanel(final Windowable p)
    {
        ((JPanel)p).setVisible(false);
        mPanels.addElement(p.getPanel());
        mCurrentPanel = p.getPanel();
        javax.swing.JMenuItem jMenuItem = new javax.swing.JMenuItem();
        p.setMenuItem(jMenuItem);
        p.setParentWindow(this);
        jMenuItem.addActionListener(new java.awt.event.ActionListener()
        {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setMainPanel(p.getPanel());
                mCurrentPanel = p.getPanel();
            }
        });
        windowMenu.add(jMenuItem);
        // reset in fullscreen the addEnter Structure
        if (fullscreen)
        {
            addEnter(pop, false);
            addEnter(pop, true);
        }

        ((JPanel)p).setVisible(true);
    }

    public void removePanel(final Windowable p)
    {
        removePanel(p, true);
    }
    public void removePanel(final Windowable p, boolean closing)
    {
        ((JPanel)p).setVisible(false);
        mPanels.removeElement(p.getPanel());
        JMenuItem item = p.getMenuItem();
        if (item!=null)
            windowMenu.remove(item);
        // reset in fullscreen the addEnter Structure
        if (fullscreen)
        {
            addEnter(pop, false);
            addEnter(pop, true);
        }
        if (mPanels.size()>0)
        {
            
            setMainPanel(mPanels.elementAt(0));
            mCurrentPanel = mPanels.elementAt(0);
        }
        else
        {
            mCurrentPanel = null;
            resetMainPanel();
        }
        if (p ==(Windowable) Configuration.getConfiguration().getLogEntity())
        {
            mLogDisplayed = false;
        }
        if (Configuration.getConfiguration().getDebugEntity() instanceof Windowable)
        if (p ==(Windowable) Configuration.getConfiguration().getDebugEntity())
        {
            mDebugDisplayed = false;
        }
        if (closing)
            p.closing();
    }


    private void toFullscreen()
    {

        if (fullscreen) return;
        if (!device.isFullScreenSupported()) return;
        /*
        UIDefaults uiDefaults = UIManager.getDefaults();
        Set entries = fullscreenDefaults.entrySet();
        Iterator it = entries.iterator();
        while (it.hasNext())
        {
            java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
            UIResource value = (UIResource) entry.getValue();
            String key = (String)entry.getKey();
            uiDefaults.put(key, value);
        }
        SwingUtilities.updateComponentTreeUI(  org.jdesktop.application.Application.getInstance(csa.jportal.JPortalApp.class).getMainFrame() );
*/
        fullscreen = true;
        Configuration.getConfiguration().mIsFullscreen = true;
        //save off the old display mode.
        dispModeOld = device.getDisplayMode();
        String dispString = Configuration.getConfiguration().getFullScrrenResString();
        if (dispString.trim().length() != 0)
        {
            DisplayMode d = ConfigurationPanel.getDisplayModeForString(dispString);
            if (d!=null) dispMode = d;
        }

        //hide everything
        getFrame().setVisible(false);

        //remove the frame from being displayable.
        getFrame().dispose();

        //remove borders around the frame
        getFrame().setUndecorated(true);
        
        //needed for tinyLAF - see also MAIN start for Mac
        //JFrame.setDefaultLookAndFeelDecorated(false);	// to decorate frames
        //JDialog.setDefaultLookAndFeelDecorated(false);	// to decorate dialogs 
        //Toolkit.getDefaultToolkit().setDynamicLayout(false);
        //System.setProperty("sun.awt.noerasebackground", "false");
        //JFrame.setDefaultLookAndFeelDecorated(false);
        
        SwingUtilities.updateComponentTreeUI(getFrame());

        //make the window fullscreen.
        device.setFullScreenWindow(getFrame());

        //attempt to change the screen resolution.
        device.setDisplayMode(dispMode);

        //show the frame
        getFrame().setVisible(true);

        // if not 2 buffers switching back to windowed mode
        // results (at least with me) in Exceptions
        getFrame().createBufferStrategy(2); // 2 buffers

        statusPanel.setVisible(false);
        java.awt.Toolkit.getDefaultToolkit().addAWTEventListener(this, java.awt.AWTEvent.MOUSE_MOTION_EVENT_MASK | java.awt.AWTEvent.MOUSE_EVENT_MASK);
        if (!isMac)
        {
            createPopup();

        }
        else
        {
            createMacPopup();

        }

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run()
            {
                Configuration.getConfiguration().setMainSize(mainPanel.getWidth(), mainPanel.getHeight());
                if (titlePanel1 != null)
                    titlePanel1.sizeChanged();
                Configuration.getConfiguration().fireSizeChanged(false);
                Configuration.getConfiguration().fireConfigChanged();
            }
        });
        menuBar.setVisible(false);
    }
  // found somewhere in forums of the www
  void showComponents( java.awt.Container  c, int depth, java.awt.Container  p)
  {
    System.out.println(""+depth+". "+ c+"\n   ->"+p);
    if (c instanceof java.awt.Container)
    for (int j=0;j<((java.awt.Container)c).getComponentCount();j++)
    {
        final java.awt.Component mc = ((java.awt.Container)c).getComponent(j);
        showComponents((java.awt.Container)mc, depth+1, c);
    }
  }

  
    private void toWindowed()
    {
        if (!fullscreen) return;
        fullscreen = false;
        Configuration.getConfiguration().mIsFullscreen = false;
/*
        UIDefaults uiDefaults = UIManager.getDefaults();
        Set entries = windowedDefaults.entrySet();
        Iterator it = entries.iterator();
        while (it.hasNext())
        {
            java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
            UIResource value = (UIResource) entry.getValue();
            String key = (String)entry.getKey();
            uiDefaults.put(key, value);
        }
        SwingUtilities.updateComponentTreeUI(  org.jdesktop.application.Application.getInstance(csa.jportal.JPortalApp.class).getMainFrame() );
*/
        menuBar.setVisible(true);
        java.awt.Toolkit.getDefaultToolkit().removeAWTEventListener(this);
        getFrame().getJMenuBar().setVisible(true);
        statusPanel.setVisible(true);
        //set the display mode back to the what it was when
        //the program was launched.
        device.setDisplayMode(dispModeOld);

        //hide the frame so we can change it.
        getFrame().setVisible(false);

        //remove the frame from being displayable.
        getFrame().dispose();

        //put the borders back on the frame.
        getFrame().setUndecorated(false);
        
        //needed for tinyLAF - see also MAIN start for Mac
        //JFrame.setDefaultLookAndFeelDecorated(true);	// to decorate frames
        //JDialog.setDefaultLookAndFeelDecorated(true);	// to decorate dialogs        
        //SwingUtilities.updateComponentTreeUI(getFrame());
        //Toolkit.getDefaultToolkit().setDynamicLayout(true);
        //System.setProperty("sun.awt.noerasebackground", "true");
        //JFrame.setDefaultLookAndFeelDecorated(true);
		        

        //needed to unset this window as the fullscreen window.
        device.setFullScreenWindow(null);

        //make sure the size of the window is correct.
        // getFrame().setSize(800,600);
        setMySize();

        //recenter window
        getFrame().setLocationRelativeTo(null);

        //reset the display mode to what it was before
        //we changed it.
        getFrame().setVisible(true);
        // if not 2 buffers switching back to windowed mode
        // results (at least with me) in Exceptions
        getFrame().createBufferStrategy(2); // 2 buffers
        createMenuBar();



        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run()
            {
                Configuration.getConfiguration().setMainSize(mainPanel.getWidth(), mainPanel.getHeight());
                if (titlePanel1 != null)
                    titlePanel1.sizeChanged();
                Configuration.getConfiguration().fireSizeChanged(false);
                Configuration.getConfiguration().fireConfigChanged();
            }
        });
    }

    public void desktopMe(Windowable p)
    {
        for (int i = 0; i < mFrames.size(); i++)
        {
            CSAInternalFrame frame = (CSAInternalFrame) mFrames.elementAt(i);
            if (frame.getPanel() == p)
            {
                desktopMe(frame);
                return;
            }
        }
        addPanel(p);
        setMainPanel((JPanel)p);
    }

    public void desktopMe(CSAInternalFrame f)
    {
        JPanel p = f.getPanel();
        ((JPanel)p).setVisible(false);
        f.setVisible(false);
        try
        {
            f.setClosed(true);
        }
        catch (Throwable e){}
        removeInternalFrame(f);
        addPanel((Windowable) p);
        ((JPanel)p).setVisible(true);
        setMainPanel(p);
    }

    public CSAInternalFrame windowMe(Windowable p, int w, int h, String title)
    {
        ((JPanel)p).setVisible(false);
        removePanel(p, false);
        CSAInternalFrame frame = new CSAInternalFrame();
        frame.addPanel((JPanel)p);
        frame.setSize(w, h);

        addInternalFrame(frame);
        
        frame.setTitle(title);
        frame.setVisible(true);
        
        if (internalFrameDifference == null)
        {
            Container c = frame.getContentPane();
            Dimension cc = c.getSize();
            Dimension f = frame.getSize();
            
            internalFrameDifference = new Dimension(f.width-cc.width, f.height-cc.height);
        }
        
        ((JPanel)p).setVisible(true);
        return frame;
    }

    public boolean closeMyWindow(JPanel p)
    {
        for (int i = 0; i < mFrames.size(); i++)
        {
            CSAInternalFrame frame = (CSAInternalFrame) mFrames.elementAt(i);
            if (frame.getPanel() == p)
            {
                try
                {
                    frame.setClosed(true);
                    return true;
                }
                catch(Throwable e) { }
            }
        }
        return false;
    }

    public boolean hideMyPanel(JPanel p)
    {
        removePanel((Windowable) p);
        return true;
    }
    public boolean showMyPanel(JPanel p)
    {
        addPanel((Windowable) p);
        return true;
    }

    public boolean hideMyWindow(JPanel p)
    {
        for (int i = 0; i < mFrames.size(); i++)
        {
            CSAInternalFrame frame = (CSAInternalFrame) mFrames.elementAt(i);
            if (frame.getPanel() == p)
            {
                try
                {
                    frame.setVisible(false);
                    return true;
                }
                catch(Throwable e) { }
            }
        }
        return false;
    }

    public boolean showMyWindow(JPanel p)
    {
        for (int i = 0; i < mFrames.size(); i++)
        {
            CSAInternalFrame frame = (CSAInternalFrame) mFrames.elementAt(i);
            if (frame.getPanel() == p)
            {
                try
                {
                    frame.setVisible(true);
                    return true;
                }
                catch(Throwable e) { }
            }
        }
        return false;
    }

    @Override
    public void configurationChanged()
    {
        if (mCurrentPanel != null)
            setMainPanel(mCurrentPanel);
    }

    public void setMainPanel(javax.swing.JPanel panel)
    {
        if (panel == null) return;
        boolean backdrop = false;
        if (Configuration.getConfiguration().isBackImageShown())
        {
            backdrop = true;
        }
        backdrop = backdrop && (!panel.isOpaque());
        if (!backdrop )
        {
            setMainPanelOld(panel);
        }
        else
        {
            if (Configuration.getConfiguration().getCurrentTheme().getGameImagePath().trim().length() != 0)
            {
                titlePanel1.setImage(Configuration.getConfiguration().getCurrentTheme().getGameImagePath(), Configuration.getConfiguration().getCurrentTheme().getData().getResizeGameImage());
            }
            titlePanel1.setPanel(panel);
            setMainPanelOld(titlePanel1);
        }
        invalidate();
        validate();
        repaint();
    }

    public void setMainPanelOld(javax.swing.JPanel panel)
    {
        panel.setVisible(false);
        mDesktop.setVisible(false);
        
        for (int i = 0;i<mDesktop.getComponentCount();i++)
        {
            mDesktop.getComponent(i).setVisible(false);
        }
        
        
        mDesktop.removeAll();
        for (int i=0; i <  mFrames.size(); i++)
        {
            JInternalFrame f = mFrames.elementAt(i);
            getMainPanel().add(f);
            f.setVisible(true);
            getMainPanel().setComponentZOrder(f, 0);
        }

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mDesktop);
        mDesktop.setLayout(mainPanelLayout);


        synchronized (panel)
        {
            mainPanelLayout.setHorizontalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
            mainPanelLayout.setVerticalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(panel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
            panel.setVisible(true);
        }
        mDesktop.setVisible(true);

    }
    private void resetMainPanel()
    {
        titlePanel1.removePanel();
        setMainPanelOld(titlePanel1);
    }

    public java.awt.Container getMainPanel()
    {
        return mDesktop;
    }

    
    void testFirstTime()
    {
        Configuration C = Configuration.getConfiguration();
        /*
        if (C.isFirstTime())
        {
            StarterKit c = new StarterKit();
            c.setParentWindow(this);
            titlePanel1.add(c);
            titlePanel1.setComponentZOrder(c, 0);
            c.setBounds(100, 100, 500, 400);
        }
        else
        */
        if (C.isShowTOD())
        {
            TipOfDayGUI c = new TipOfDayGUI();
            c.setParentWindow(this);
            titlePanel1.add(c);
            titlePanel1.setComponentZOrder(c, 0);
            c.setBounds(100, 100, 500, 400);
        }
    }
/*
    public void removeStarter(StarterKit starter)
    {
        titlePanel1.remove(starter);
        starter.deinit();
        titlePanel1.invalidate();
        titlePanel1.validate();
        titlePanel1.repaintAll();
        Configuration C = Configuration.getConfiguration();
        C.setFirstTime(false);
        C.save();
    }
*/
    @Override
    public void removeTOD(TipOfDayGUI starter)
    {
        titlePanel1.remove(starter);
        starter.deinit();
        titlePanel1.invalidate();
        titlePanel1.validate();
        titlePanel1.repaintAll();
    }
    public void showPanelModal(JPanel c, String name)
    {
        showPanelModal(c, name, 550, 400);
    }

    @Override
    public void showPanelModal(JPanel c, String name, int w, int h)
    {
        JPanel all = new JPanel();
        all.setLayout(new BorderLayout());
        all.add(c, BorderLayout.CENTER);
        JButton close = new JButton("Ok");
        all.add(close, BorderLayout.SOUTH);

        final JInternalFrame modal = new ModalInternalFrame(name, getFrame().getRootPane(), getFrame(), all, close);

        close.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try
                {
                    modal.setVisible(false);
                }
                catch (Throwable ex){}
            }
        });
        modal.setSize(w, h);

        int x = (getFrame().getRootPane().getWidth() - w) / 2;
        int y = (getFrame().getRootPane().getHeight() - h) / 2;
        modal.setLocation(x, y);
        modal.setVisible(true);
    }
    
    public void correctGarbledDisplay()
    {
        invalidate();
        validate();
        repaint();
        /*
        for (int i = 0; i < mFrames.size(); i++) {
            JInternalFrame frame = mFrames.elementAt(i);
            frame.invalidate();
            frame.validate();
            frame.repaint();
        }
        */
    }
    public static Dimension getInternalFrameDifference()
    {
        if (internalFrameDifference != null) return internalFrameDifference;
        else
        {
            CSAInternalFrame frame = new CSAInternalFrame();
            frame.setSize(100, 100);
            ((CSAMainFrame)Global.mMainWindow).getMainPanel().add(frame);


            frame.setTitle("Test");
            frame.setVisible(true);
            frame.invalidate();
            frame.validate();
            frame.repaint();

            Container c = frame.getContentPane();
            Dimension cc = c.getSize();
            Dimension f = frame.getSize();
            
            internalFrameDifference = new Dimension(f.width-cc.width, f.height-cc.height);
            
            frame.setVisible(false);

            ((CSAMainFrame)Global.mMainWindow).getMainPanel().remove(frame);
            
        }
        return internalFrameDifference;
    }

    
    
    
    
    private void initGame()
    {
        inEvent++;
        gameMode = !gameMode;
        if (gameMode != fullscreen)
        {
            if (!fullscreen)
            {
                jCheckBoxMenuItem1.setSelected(gameMode);
// FULLSCREEN               toFullscreen();
                setMenu(false);
                keyListener = new  csa.event.MasterEventListener()
                {
                    public void eventOccured(csa.event.MasterEvent e)
                    {
                        if (e.eventHandled) return;
                        if (e.keyboardState == e.KBD_STATE_RELEASED)
                        {

                            if (e.keyCode == KeyEvent.VK_ESCAPE)
                            {
                                e.eventHandled=true;
                                jMenuItem11ActionPerformed(null);
                                return;
                            }
                        }
                        // send key events to game!
                    }
                };
                EventSupport.getEventSupport().addKeyEventListener(keyListener);
                
                
                if (matchStartPanel == null)
                {
                    matchStartPanel = new GameMainMenuPanel(this);
                }
                preStartMatch();
                addPanel(matchStartPanel);
                setMainPanel(matchStartPanel);
                //windowMe(matchStartPanel, 950, 720, "Start game!");
            }
            else
            {
                
                if (matchStartPanel != null)
                {
                    removePanel((Windowable)matchStartPanel);
                }
                postMatch();
                EventSupport.getEventSupport().removeKeyEventListener(keyListener);
                keyListener = null;
                setMenu(true);
                toWindowed();
            }
        }
        else if ((!fullscreen) && (!gameMode))
        {
            if (matchStartPanel != null)
            {
                removePanel((Windowable)matchStartPanel);
            }
            if (matchPanel != null)
            {
                removePanel((Windowable)matchPanel);
            }
            postMatch();
            EventSupport.getEventSupport().removeKeyEventListener(keyListener);
            keyListener = null;
            setMenu(true);
        }
        inEvent--;
    }    
    public void doGameAction(String action)
    {
        if (action.equals("Start"))
        {
            if (matchStartPanel != null)
            {
                removePanel((Windowable)matchStartPanel);
            }
            doStartMatch();
        }
    }
    public void doStartMatch()
    {
        if (matchPanel == null)
        {
            matchPanel = new GamePanel(this);
        }
        preStartMatch();
        addPanel(matchPanel);
        setMainPanel(matchPanel);
        
        //desktopMe(windowMe(matchPanel, 10,10,"böla"));
    }
    GamePanel matchPanel = null;
    GameMainMenuPanel matchStartPanel = null;
}
