// Yura Mamyrin, Group D

package risk.ui.FlashGUI;

import risk.engine.*;
import risk.engine.core.Country;
import risk.engine.core.RiskGame;

import javax.swing.JFrame;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.Toolkit;
import java.awt.Dimension;
import javax.swing.JLayeredPane;
import javax.swing.event.MouseInputListener;

import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.Insets;
import java.awt.event.*;

import java.awt.font.TextLayout;
import java.awt.font.FontRenderContext;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.AlphaComposite;

import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import java.awt.RenderingHints;
import javax.swing.JOptionPane;

import java.util.Iterator;
import java.util.List;
import java.util.Arrays;
import java.util.Vector;

/**
 * <p> Game Frame for FlashGUI </p>
 * @author Yura Mamyrin
 */

public class GameFrame extends JFrame implements MouseInputListener,KeyListener {

	private BufferedImage game;
	private Risk myrisk;
	private PicturePanel pp;
	private GameMenuPanel gm;
	private int mapView;
	private String gameStatus;
	private boolean localGame;
	private int gameState;
	private String note;
	private boolean setupDone;

	private JButton cardsbutton;
	private JButton missionbutton;
	private JButton undobutton;
	private JButton menubutton;
	private JButton graphbutton;
	private JButton gobutton;

	private java.util.ResourceBundle resb;
	private StatsDialog graphdialog;

	private boolean menuOn;
	private boolean graphOn;

	private Color[] colors;
	private CardsDialog cardsDialog;

	private int c1Id;
	private MoveDialog movedialog;


	private JButton savebutton;
	private JButton resumebutton;

	private JCheckBox AutoEndGo;
	private JCheckBox AutoDefend;

	private JButton helpbutton;
	private JButton closebutton;


	public GameFrame(Risk r, PicturePanel p) {

		setResizable(false);

		colors = new Color[] { Color.GRAY };

		myrisk=r;
		pp=p;

		menuOn=false;
		graphOn=false;

		try {
			game = ImageIO.read( this.getClass().getResource("game.jpg") );
		}
		catch (Exception e) { }

		initGUI();

		setIconImage(Toolkit.getDefaultToolkit().getImage( Risk.class.getResource("icon.gif") ));

		pack();

		graphdialog = null;
	}

	public void setup(boolean s) {

		gameState=0; // -1 or 0 means no input needed
		mapView=1;
		gameStatus="";
		note="";
		setupDone=true;
		c1Id = -1;

		localGame = s;

		if (localGame) { closebutton.setText(resb.getString("game.menu.close")); }
		else { closebutton.setText(resb.getString("game.menu.leave")); }

		repaintCountries();

	}

	/** This method is called from within the constructor to initialize the form. */

	/**
	 * Initialises the GUI
	 */
	private void initGUI()
	{

		resb = risk.engine.translation.TranslationBundle.getBundle();

		// set title
		setTitle("yura.net " + resb.getString("game.title"));

		Dimension d = new Dimension(740, 600);

		JLayeredPane layeredPane = new JLayeredPane();
		layeredPane.setPreferredSize(d);
		layeredPane.setMinimumSize(d);
		layeredPane.setMaximumSize(d);

		FlashPanel fp = new FlashPanel();
		fp.setBounds(0,0, (int)d.getWidth() , (int)d.getHeight() );
		fp.addMouseListener(this);
		fp.addMouseMotionListener(this);
		fp.setLayout(null);

		int w=114;
		int h=66;
		// normal - pressed - rollover - disabled
		int x=63;
		int y=77;

		graphbutton = makeRiskButton(game.getSubimage(x, y, w, h), game.getSubimage(x, y+230, w, h), game.getSubimage(x, y+164, w, h), game.getSubimage(x, y+98, w, h), true );
		graphbutton.setBounds(x-63, y+425, w , h );
		graphbutton.addActionListener( buttonActionListener );
		graphbutton.setToolTipText( resb.getString("game.button.statistics") );

		x=x+w;

		cardsbutton = makeRiskButton(game.getSubimage(x, y, w, h), game.getSubimage(x, y+230, w, h), game.getSubimage(x, y+164, w, h), game.getSubimage(x, y+98, w, h), false );
		cardsbutton.setBounds(x-63, y+425, w , h );
		cardsbutton.addActionListener( buttonActionListener );
		cardsbutton.setToolTipText(resb.getString("game.button.cards"));

		x=x+w;

		missionbutton = makeRiskButton(game.getSubimage(x, y, w, h), game.getSubimage(x, y+230, w, h), game.getSubimage(x, y+164, w, h), game.getSubimage(x, y+98, w, h), false );
		missionbutton.setBounds(x-63, y+425, w , h );
		missionbutton.addActionListener( buttonActionListener );
		missionbutton.setToolTipText(resb.getString("game.button.mission"));

		x=x+w;

		undobutton = makeRiskButton(game.getSubimage(x, y, w, h), game.getSubimage(x, y+230, w, h), game.getSubimage(x, y+164, w, h), game.getSubimage(x, y+98, w, h), false );
		undobutton.setBounds(x-63, y+425, w , h );
		undobutton.addActionListener( buttonActionListener );
		undobutton.setToolTipText(resb.getString("game.button.undo"));

		x=x+w;

		menubutton = makeRiskButton(game.getSubimage(x, y, w, h), game.getSubimage(x, y+230, w, h), game.getSubimage(x, y+164, w, h), game.getSubimage(x, y+98, w, h), true );
		menubutton.setBounds(x-63, y+425, w , h );
		menubutton.addActionListener( buttonActionListener );
		menubutton.setToolTipText( resb.getString("game.button.menu") );



		w=115;
		h=31;
		gobutton = makeRiskButton(game.getSubimage(663, 128, w, h), game.getSubimage(412, 394, w, h), game.getSubimage(296, 394, w, h), game.getSubimage(180, 394, w, h), false );
		gobutton.setBounds(600, 553, w , h );
		gobutton.addActionListener( buttonActionListener );

		fp.add(graphbutton);
		fp.add(cardsbutton);
		fp.add(missionbutton);
		fp.add(undobutton);
		fp.add(menubutton);
		fp.add(gobutton);

		pp.setBounds(31, 54, PicturePanel.PP_X , PicturePanel.PP_Y);
		pp.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0,0,0),1));
		pp.addMouseListener(this);
		pp.addMouseMotionListener(this);

		gm = new GameMenuPanel();
		gm.setVisible(false);
		gm.setBounds(285, 141, 170 , 250);
		//gm.addMouseListener(this);
		//gm.addMouseMotionListener(this);

		layeredPane.add(gm, 0);
		layeredPane.add(pp, 1);
		layeredPane.add(fp, 2);

		getContentPane().add(layeredPane);

		setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

		addWindowListener(
			new java.awt.event.WindowAdapter() {
				public void windowClosing(java.awt.event.WindowEvent evt) {
					closeleave();
				}
			}
		);

		this			.addKeyListener( this);
		cardsbutton		.addKeyListener( this);
		missionbutton		.addKeyListener( this);
		undobutton		.addKeyListener( this);
		menubutton		.addKeyListener( this);
		graphbutton		.addKeyListener( this);
		gobutton		.addKeyListener( this);

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

		cardsDialog = new CardsDialog(GameFrame.this, true, myrisk, pp);

		Dimension frameSize = cardsDialog.getSize();
		frameSize.height = ((frameSize.height > screenSize.height) ? screenSize.height : frameSize.height);
		frameSize.width = ((frameSize.width > screenSize.width) ? screenSize.width : frameSize.width);
		cardsDialog.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);


		movedialog = new MoveDialog(GameFrame.this, true);

		frameSize = movedialog.getSize();
		frameSize.height = ((frameSize.height > screenSize.height) ? screenSize.height : frameSize.height);
		frameSize.width = ((frameSize.width > screenSize.width) ? screenSize.width : frameSize.width);
		movedialog.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);

	}

	ActionListener buttonActionListener = new ActionListener() {
		public void actionPerformed(ActionEvent e) {

			if (e.getSource()==cardsbutton) {
				displayCards();
			}
			else if (e.getSource()==missionbutton) {
				displayMission();
			}
			else if (e.getSource()==undobutton) {
				doUndo();
			}
			else if (e.getSource()==menubutton) {
				displayMenu();
			}
			else if (e.getSource()==graphbutton) {

				displayGraph();

			}
			else if (e.getSource()==gobutton) {
				goOn();
			}
			else if (e.getSource()==savebutton) {

				JFileChooser fc = new JFileChooser("saves/");
				RiskFileFilter filter = new RiskFileFilter(RiskFileFilter.RISK_SAVE_FILES);
				fc.setFileFilter(filter);

				int returnVal = fc.showSaveDialog(GameFrame.this);
				if (returnVal == JFileChooser.APPROVE_OPTION) {

					try {

						java.io.File file = fc.getSelectedFile();
						// Write your code here what to do with selected file

						String fileName = file.getAbsolutePath();

						if (!(fileName.endsWith( "." + RiskFileFilter.RISK_SAVE_FILES ))) {
							fileName = fileName + "." + RiskFileFilter.RISK_SAVE_FILES;
						}

						go("savegame " + fileName );
					}

					catch(Exception error) {
						//System.out.print("ERROR WITH SAVE (GUI SIDE)\n"); //testing
					}

				} else {
					// Write your code here what to do if user has canceled Save dialog
				}


			}
			else if (e.getSource()==resumebutton) {

				displayMenu();

			}
			else if (e.getSource()==AutoEndGo) {

				if ( AutoEndGo.isSelected() ) {
					go("autoendgo on");
				}
				else {
					go("autoendgo off");
				}

			}
			else if (e.getSource()==closebutton) {

				closeleave();

			}
			else if (e.getSource()==AutoDefend) {

				if ( AutoDefend.isSelected() ) {
					go("autodefend on");
				}
				else {
					go("autodefend off");
				}

			}
			else if (e.getSource()==helpbutton) {

				try {
					Risk.openDocs( resb.getString("helpfiles.flash") );
				}
				catch(Exception er) {
					JOptionPane.showMessageDialog(GameFrame.this,"Unable to open manual: "+er.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
				}

			}
		}
	};

	/** Exit the Application */

	public void closeleave() {

		if (graphOn) { graphdialog.setVisible(false); graphOn=false; }

		//if (localGame) {
			go("closegame");
		//}
		//else {
		//	go("leave");
		//}
	}

	public void repaintCountries() {

		if (mapView==1) {
			pp.repaintCountries( PicturePanel.VIEW_CONTINENTS );
		}
		else if (mapView==2) {
			pp.repaintCountries( PicturePanel.VIEW_OWNERSHIP );
		}
		else if (mapView==3) {
			pp.repaintCountries( PicturePanel.VIEW_BORDER_THREAT );
		}
		else if (mapView==4) {
			pp.repaintCountries( PicturePanel.VIEW_CARD_OWNERSHIP );
		}
		else if (mapView==5) {
			pp.repaintCountries( PicturePanel.VIEW_TROOP_STRENGTH );
		}
		else if (mapView==6) {
			pp.repaintCountries( PicturePanel.VIEW_CONNECTED_EMPIRE );
		}

	}

	public void setGameStatus(String state) {

		gameStatus=state;

		// the colors for the bottom display r collected here
		colors = myrisk.getPlayerColors();

		repaint();

	}

	public void needInput(int s) {

		gameState=s;

		if (gameState==RiskGame.STATE_TRADE_CARDS) {

			// after wiping out someone if you go into trade mode
			pp.setC1(255);
			pp.setC2(255);

			gobutton.setText(resb.getString("game.button.go.endtrade"));
		}
		else if (gameState==RiskGame.STATE_PLACE_ARMIES) {
			if (setupDone==false) { gobutton.setText(resb.getString("game.button.go.autoplace")); }
			else { gobutton.setText(""); }
		}
		else if (gameState==RiskGame.STATE_ATTACKING) {

			pp.setC1(255);
			pp.setC2(255);

			note=resb.getString("game.note.selectattacker");
			gobutton.setText(resb.getString("game.button.go.endattack"));
		}
		// for gameState 4 look in FlashRiskAdapter.java
		else if (gameState == RiskGame.STATE_BATTLE_WON) {
			movedialog.setVisible(true);
		}
		else if (gameState==RiskGame.STATE_FORTIFYING) {
			note=resb.getString("game.note.selectsource");
			gobutton.setText(resb.getString("game.button.go.nomove"));
		}
		else if (gameState==RiskGame.STATE_END_TURN) {
			gobutton.setText(resb.getString("game.button.go.endgo"));
		}
		else if (gameState==RiskGame.STATE_GAME_OVER) {

			if (localGame) {
				gobutton.setText(resb.getString("game.button.go.closegame"));
			}
			else {
				gobutton.setText(resb.getString("game.button.go.leavegame"));
			}

		}
		else if (gameState == RiskGame.STATE_SELECT_CAPITAL) {

			note=resb.getString("game.note.happyok");
			gobutton.setText(resb.getString("game.button.go.ok"));

		}
		// for gameState 10 look in FlashRiskAdapter.java
		else {
			gobutton.setText("");
		}



		if (!(gobutton.getText().equals(""))) {
			gobutton.setEnabled(true);
		}
		else {
			gobutton.setEnabled(false);
		}

		if (gameState!=RiskGame.STATE_DEFEND_YOURSELF) {

			cardsbutton.setEnabled(true);
			missionbutton.setEnabled(true);

			if (localGame) {

			    undobutton.setEnabled(true);
			    savebutton.setEnabled(true);

			}

			AutoEndGo.setEnabled(true);
			AutoEndGo.setBackground( Color.white );
			AutoEndGo.setSelected( myrisk.getAutoEndGo() );

			AutoDefend.setEnabled(true);
			AutoDefend.setBackground( Color.white );
			AutoDefend.setSelected( myrisk.getAutoDefend() );

		}

		repaint(); // SwingGUI has this here, if here then not needed in set status


	}

	public void armiesLeft(int l, boolean s) {

		note = resb.getString("game.note.armiesleft").replaceAll( "\\{0\\}", "" + l);
		setupDone = s;

	}

	/**
	 * checks if the coordinates are in one of the
	 * tabs at the top of the window
	 */
	public int insideButton(int x, int y) {

		int B=0;

		if (y >=9 && y < 32 ) {

			int W=115;

			if (x >= 24 && x < (24 + W)) {
				B=1;
			}
			else if (x >= 139 && x < (139 + W)) {
				B=2;
			}
			else if (x >= 254 && x < (254 + W)) {
				B=3;
			}
			else if (x >= 369 && x < (369 + W)) {
				B=4;
			}
			else if (x >= 484 && x < (484 + W)) {
				B=5;
			}
			else if (x >= 599 && x < (599 + W)) {
				B=6;
			}

		}

		return B;

	}

	/** calls the parser with the command  */

	/**
	 * calls the parser
	 * @param command sends the input command to the parser via a string
	 */
	public void go(String command) {

		pp.setHighLight(255);

		c1Id = -1;
		if (gameState!=2 || !myrisk.getGame().getSetup() ) { noInput(); }

		myrisk.parser(command);

	}

	public void noInput() {

		cardsbutton.setEnabled(false);
		missionbutton.setEnabled(false);
		undobutton.setEnabled(false);

		savebutton.setEnabled(false);

		AutoEndGo.setEnabled(false);
		AutoEndGo.setBackground( Color.lightGray );

		AutoDefend.setEnabled(false);
		AutoDefend.setBackground( Color.lightGray );

		gobutton.setText("");
		gobutton.setEnabled(false);

		note="";
		gameState=0;

	}

	/**
	 * Returns an image of a given country
	 * @param a Index position of country
	 */
	public BufferedImage getCountryImage(int a) {

		return pp.getCountryImage(a, true);

	}

	public void openMove(int min, int c1num, int c2num, boolean tacmove) {

		int src = myrisk.hasArmiesInt( c1num );
		int des = myrisk.hasArmiesInt( c2num );
		BufferedImage c1img = pp.getCountryImage(c1num ,true);
		BufferedImage c2img = pp.getCountryImage(c2num ,true);
		Country country1 = myrisk.getGame().getCountryInt( c1num);
		Country country2 = myrisk.getGame().getCountryInt( c2num);

		Color color = myrisk.getCurrentPlayerColor();

		movedialog.setup(tacmove,       min,      src, des, c1img, c2img, country1, country2, color);

	}

	//**********************************************************************
	//                     MouseListener Interface
	//**********************************************************************

	public void mouseClicked(MouseEvent e) {
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {

		if (e.getComponent() == gm) {
		}
		else if (e.getComponent() == pp) {

			if (pp.getHighLight() != 255) {
				pp.setHighLight(255);
				pp.repaint();
			}

			e.consume();

		}
		else {

		}

	}

	public void mousePressed(MouseEvent e) {
	}

	/**
	 * Used in the playing of the game
	 * @param e The MouseEvent object
	 */
	public void mouseReleased(MouseEvent e) {

		if (e.getComponent() == gm) { // click on the menu


		}
		else if (e.getComponent() == pp) { // click on the picture panel

			//System.out.print("Map Click\n");

			if ((e.getX() < PicturePanel.PP_X) && (e.getY() < PicturePanel.PP_Y) && (e.getX() >= 0) && (e.getY() >= 0) ) {

				int pixColor = pp.getCountryNumber(e.getX(),e.getY());

				if ( e.getModifiers() == java.awt.event.InputEvent.BUTTON1_MASK ) {

					if (pixColor == 255 ) {

					}
					else if (gameState == 2) {
						if ( myrisk.isOwnedCurrentPlayerInt(pixColor) && (setupDone || myrisk.hasArmiesInt(pixColor) == 0) ) {
							go( "placearmies " + pixColor + " 1" );
						}
					}
					else if (gameState == 3) {

						if ( pixColor == c1Id ) {
							c1Id = -1;
							note=resb.getString("game.note.selectattacker");
							pp.setC1(255);
							pp.setC2(255);
							repaint();
						}
						else if ( myrisk.isOwnedCurrentPlayerInt(pixColor) && ( myrisk.hasArmiesInt(pixColor) > 1) ) {
							note=resb.getString("game.note.selectdefender");

							c1Id = pixColor;
							pp.setC1(pixColor);
							pp.setC2(255);
							repaint();
						}
						else if ( c1Id != -1 && !(myrisk.isOwnedCurrentPlayerInt(pixColor)) && myrisk.canAttack( c1Id , pixColor) ) {
							pp.setC2(pixColor);
							go("attack " + c1Id + " " + pixColor);
							note=resb.getString("game.note.selectattacker");
							repaint();
						}

					}
					else if (gameState == 6) {

						if ( pixColor == c1Id ) {

							c1Id = -1;
							note=resb.getString("game.note.selectsource");
							pp.setC1(255);
							pp.setC2(255);
							repaint();
						}
						else if ( myrisk.isOwnedCurrentPlayerInt(pixColor) && ( myrisk.hasArmiesInt(pixColor) > 1) && c1Id == -1) {

							note=resb.getString("game.note.selectdestination");

							c1Id = pixColor;
							pp.setC1(pixColor);
							pp.setC2(255);
							repaint();
						}
						else if ( c1Id != -1 && (myrisk.isOwnedCurrentPlayerInt(pixColor)) && myrisk.canAttack( c1Id , pixColor) ) {

							pp.setC2(pixColor);
							note="";
							repaint();

							openMove(1, pp.getC1() , pixColor, true);

							movedialog.setVisible(true);

							pp.setC1(255);
							pp.setC2(255);

							c1Id = -1;
							note=resb.getString("game.note.selectsource");
							repaint();
						}

					}
					else if (gameState == 9) {
						c1Id = pixColor;
						pp.setC1(pixColor);
						pp.repaint();
					}

				}
				else if ( e.getModifiers() == java.awt.event.InputEvent.BUTTON3_MASK ) {

					if (pixColor == 255 ) {

					}
					else if (gameState == 2) {
						if ( myrisk.isOwnedCurrentPlayerInt(pixColor) && (setupDone || myrisk.hasArmiesInt(pixColor) == 0) ) {
							go( "placearmies " + pixColor + " 10" );
						}
					}
				}
			}
		}
		else { // click in the window

			int click=insideButton(e.getX(),e.getY());

			if (click > 0 && click < 7) { // this means it was one of the view buttons

				if (mapView !=click) {

					setMapView(click);

				}

			}

		}

	}//public void mouseReleased()

	public void mouseDragged(MouseEvent e) {
	}

	/**
	 * This method is used in the general playing of the game
	 * It highlights the country the mouse is over
	 * @param e The Mousevent object
	 */
	public void mouseMoved(MouseEvent e) {

		if (e.getComponent() == gm) { // move on the menu

		}
		else if (e.getComponent() == pp) { // move on the picture panel

			//System.out.print("Map Move\n");

			int pixColor = pp.getCountryNumber(e.getX(),e.getY());
			int cc;

			if (pixColor == 255 ) {
				cc = 255;
			}
			else if (gameState == 2) {
				if ( myrisk.isOwnedCurrentPlayerInt(pixColor) && (setupDone || myrisk.hasArmiesInt(pixColor) == 0) ) {
					cc = pixColor;
				}
				else {
					cc = 255;
				}
			}
			else if ( gameState == 3) {

				if ( myrisk.isOwnedCurrentPlayerInt(pixColor) && (myrisk.hasArmiesInt(pixColor) > 1) ) {
					cc = pixColor;
				}
				else if ( !(myrisk.isOwnedCurrentPlayerInt(pixColor)) && c1Id != -1 && myrisk.canAttack( c1Id , pixColor) ) {
					cc = pixColor;
				}
				else {
					cc = 255;
				}

			}
			else if ( gameState == 6) {

				if ( myrisk.isOwnedCurrentPlayerInt(pixColor) && (myrisk.hasArmiesInt(pixColor) > 1 && c1Id == -1 ) ) {
					cc = pixColor;
				}
				else if ( myrisk.isOwnedCurrentPlayerInt(pixColor) && c1Id != -1 && myrisk.canAttack( c1Id , pixColor) ) {
					cc = pixColor;
				}
				else {
					cc = 255;
				}

			}
			else if (gameState == 9) {
				if ( myrisk.isOwnedCurrentPlayerInt(pixColor) ) {
					cc = pixColor;
				}
				else {
					cc = 255;
				}
			}
			else {
				cc = 255;

			}

			if (pp.getHighLight() != cc) {
				pp.setHighLight(cc);
				pp.repaint();
			}

			e.consume();


		}
		else { // move on the window

		}


	}//public void mouseMoved(...)



	/**
	 * the map view has changed
	 * (normal, border threat, ...)
	 * @param click		The tab number the user has clicked on
	 */
	private void setMapView(int click)
	{
		mapView = click;
		repaintCountries();
		repaint();
	}//private void setMapView(int click)



	/**
	 * displays the cards dialog
	 */
	private void displayCards() {

		cardsDialog.setup( (gameState==1) );

		cardsDialog.setVisible(true);

	}



	/**
	 * displays the mission window
	 */
	private void displayMission()
	{
		MissionDialog missiondialog = new MissionDialog(GameFrame.this, true, myrisk);

		Dimension frameSize = getSize();
		Dimension aboutSize = missiondialog.getSize();
		int x = getLocation().x + (frameSize.width - aboutSize.width) / 2;
		int y = getLocation().y + (frameSize.height - aboutSize.height) / 2;
		if (x < 0) x = 0;
		if (y < 0) y = 0;
		missiondialog.setLocation(x, y);

		missiondialog.setVisible(true);
	}//private void displayMission()



	/**
	 * does an "undo"
	 */
	private void doUndo()
	{
		go("undo");
	}//private void doUndo()



	/**
	 * displays the menu
	 */
	private void displayMenu() {

	    if(menuOn) {

		gm.setVisible(false);
		pp.addMouseListener(GameFrame.this);
		pp.addMouseMotionListener(GameFrame.this);

		menuOn=false;

	    }
	    else {

		pp.removeMouseListener(GameFrame.this);
		pp.removeMouseMotionListener(GameFrame.this);

		if (myrisk.getGame().getCurrentPlayer()!=null) {

			AutoEndGo.setSelected( myrisk.getAutoEndGo() );
			AutoDefend.setSelected( myrisk.getAutoDefend() );

		}

		gm.setVisible(true);
		menuOn=true;
	    }

	}

	public void displayGraph() {

		if (graphOn) {
			graphdialog.setVisible(false);
			graphOn=false;
		}
		else {

			if (graphdialog==null) {

				graphdialog = new StatsDialog(GameFrame.this, false, myrisk);

				Dimension frameSize = (GameFrame.this).getPreferredSize();
				Dimension graphSize = graphdialog.getSize();
				int a = (GameFrame.this).getLocation().x + (frameSize.width - graphSize.width) / 2;
				int b = (GameFrame.this).getLocation().y + (frameSize.height - graphSize.height) / 2;
				if (a < 0) a = 0;
				if (b < 0) b = 0;
				graphdialog.setLocation(a, b);

			}

			graphdialog.setVisible(true);
			graphOn=true;
		}

	}

	/**
	 * the user has clicked the "go" button
	 */
	private void goOn()
	{
		if (gameState==1) {
			go("endtrade");
		}
		else if (gameState==2) {
			go("autoplace");
		}
		else if (gameState==3) {
			pp.setC1(255);
			go("endattack");
		}
		else if (gameState==6) {
			pp.setC1(255);
			go("nomove");
		}
		else if (gameState==7) {
			go("endgo");
		}
		else if (gameState==8) {
			closeleave();
		}
		else if (gameState == 9) {
			pp.setC1(255);
			go("capital " + c1Id);
		}
	}//private void goOn()



	public static JButton makeRiskButton(Image gobutton1, Image gobutton2, Image gobutton3, Image gobutton4, boolean startstate) {

		JButton button = new JButton();

		NewGameFrame.sortOutButton( button, gobutton1, gobutton3, gobutton2 );

		button.setDisabledIcon( new ImageIcon( gobutton4 ) );
		button.setEnabled(startstate);

		return button;

	}



	/**
	 * The user has released a key
	 */
	public void keyReleased( KeyEvent event ) {

		//if (event.isControlDown()) {

			//with CTRL down

			// when the ctrl+number bit was here is gave the "?" key when the number 6 was pressed

		//} else {

			switch (event.getKeyCode())
			{
				case KeyEvent.VK_1:
				case KeyEvent.VK_2:
				case KeyEvent.VK_3:
				case KeyEvent.VK_4:
				case KeyEvent.VK_5:
				case KeyEvent.VK_6:
					this.setMapView( Integer.parseInt( event.getKeyChar() + ""));
					break;
			}

			//no modifier button pressed
			switch (event.getKeyCode())
			{
				case KeyEvent.VK_C:
					//cards
					if (gameState!=0) this.displayCards();
					break;
				case KeyEvent.VK_M:
					//mission
					if (gameState!=0) this.displayMission();
					break;
				case KeyEvent.VK_U:
					//undo
					if (gameState!=0 && gameState!=10) this.doUndo();
					break;
				case KeyEvent.VK_F10:
					this.displayMenu();
					//menu
					break;
				case KeyEvent.VK_G:
					//go button
					if (gameState!=0) this.goOn();
					break;
			}
		//}
	}//public void keyReleased( KeyEvent event )

	public void keyTyped( KeyEvent event ) {}
	public void keyPressed( KeyEvent event ) {}




	/**
	 * The tabs for the map views
	 */
	class FlashPanel extends JPanel {

		public void paintComponent(Graphics g) {

//			  destination		source
			g.drawImage(game,0,0,740,54,     63,0,803,54,this); // top
			g.drawImage(game,0,479,740,600,  63,54,803,175,this); // bottom
			g.drawImage(game,0,54,31,479,    0,0,31,425,this); // left
			g.drawImage(game,708,54,740,479, 31,0,63,425,this); // right


			Graphics2D g2 = (Graphics2D)g;

			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

			FontRenderContext frc = g2.getFontRenderContext();
			Font font = g2.getFont();
			g2.setColor( Color.black );
			TextLayout tl;

			tl = new TextLayout( resb.getString("game.tabs.continents") , font, frc);
			tl.draw( g2, (float) (81-tl.getBounds().getWidth()/2), (float)26 );

			tl = new TextLayout( resb.getString("game.tabs.ownership") , font, frc);
			tl.draw( g2, (float) (196-tl.getBounds().getWidth()/2), (float)26 );

			tl = new TextLayout( resb.getString("game.tabs.borderthreat") , font, frc);
			tl.draw( g2, (float) (311-tl.getBounds().getWidth()/2), (float)26 );

			tl = new TextLayout( resb.getString("game.tabs.cardownership") , font, frc);
			tl.draw( g2, (float) (426-tl.getBounds().getWidth()/2), (float)26 );

			tl = new TextLayout( resb.getString("game.tabs.troopstrength") , font, frc);
			tl.draw( g2, (float) (541-tl.getBounds().getWidth()/2), (float)26 );

			tl = new TextLayout( resb.getString("game.tabs.connectedempire") , font, frc);
			tl.draw( g2, (float) (656-tl.getBounds().getWidth()/2), (float)26 );

			Color[] colorss = colors;

			for (int c=0; c<colorss.length; c++) {

				Color col = colorss[c];

				g.setColor( new Color(col.getRed(),col.getGreen(),col.getBlue(), 100) );

				if (c==0) {
					g.fillArc(8, 568, 24 , 24, 90, 180);
					g.fillRect( 20 , 568 , 24 + (543 - (24*(colorss.length-c))) , 24);
				}
				else {
					g.fillRect( (563 - (24*(colorss.length-c))) , 568 , 24 , 24);
				}

			}

			g.setColor( Risk.getTextColorFor( colors[0] ) );
			g.setFont( new java.awt.Font("SansSerif", java.awt.Font.PLAIN, 11) );
			g.drawString(gameStatus, 22, 584);

			if (mapView==1) {
				g.drawImage(game,24,32,139,39,   64,383,179,390,this);
			}
			else if (mapView==2) {
				g.drawImage(game,139,32,254,39,     64,390,179,397,this);
			}
			else if (mapView==3) {
				g.drawImage(game,254,32,369,39,     64,397,179,404,this);
			}
			else if (mapView==4) {
				g.drawImage(game,369,32,484,39,     64,404,179,411,this);
			}
			else if (mapView==5) {
				g.drawImage(game,484,32,599,39,     64,411,179,418,this);
			}
			else if (mapView==6) {
				g.drawImage(game,599,32,714,39,     64,418,179,425,this);
			}

			g2.setColor( Color.black );

			if ( gameState==0 ) {
				tl = new TextLayout( resb.getString("game.pleasewait") , font, frc);
				tl.draw( g2, (float) (656-tl.getBounds().getWidth()/2), (float)536 );
			}
			else if ( (gameState==1 || gameState==2 || gameState==3 || gameState==9 || gameState==6 ) && !(note.equals("")) ) {
				tl = new TextLayout( note , font, frc);
				tl.draw( g2, (float) (656-tl.getBounds().getWidth()/2), (float)536 );
			}



		}//public void paintComponent(Graphics g)

	}//class FlashPanel extends JPanel


	/**
	 * the game menu
	 * which you get when pressing the "Menu" button
	 */
	class GameMenuPanel extends JPanel
	{

		public GameMenuPanel()
		{

			setLayout(null);

			int w=100;

			savebutton = makeRiskButton(game.getSubimage(480, 373, w, 21), game.getSubimage(380, 373, w, 21), game.getSubimage(280, 373, w, 21), game.getSubimage(180, 373, w, 21), false );
			savebutton.setText(resb.getString("game.menu.save"));
			savebutton.setBounds(35, 50, w , 20 );
			savebutton.addActionListener( buttonActionListener );

			closebutton = makeRiskButton(game.getSubimage(480, 373, w, 21), game.getSubimage(380, 373, w, 21), game.getSubimage(280, 373, w, 21), game.getSubimage(180, 373, w, 21), true );

			closebutton.setBounds(35, 80, w , 20 );
			closebutton.addActionListener( buttonActionListener );





			AutoEndGo = new JCheckBox(resb.getString("game.menu.autoendgo"));
			AutoEndGo.setToolTipText( resb.getString("game.menu.autoendgo"));

			AutoEndGo.setMargin(new Insets(0,0,0,0));
			AutoEndGo.setBorderPainted(false);
			AutoEndGo.setFocusPainted(false);

			AutoEndGo.setBounds(35, 110, w , 20 );
			AutoEndGo.addActionListener( buttonActionListener );
			AutoEndGo.setBackground( Color.lightGray );

			AutoEndGo.setEnabled(false);





			AutoDefend = new JCheckBox(resb.getString("game.menu.autodefend"));
			AutoDefend.setToolTipText( resb.getString("game.menu.autodefend"));

			AutoDefend.setMargin(new Insets(0,0,0,0));
			AutoDefend.setBorderPainted(false);
			AutoDefend.setFocusPainted(false);

			AutoDefend.setBounds(35, 140, w , 20 );
			AutoDefend.addActionListener( buttonActionListener );
			AutoDefend.setBackground( Color.lightGray );

			AutoDefend.setEnabled(false);




			helpbutton = makeRiskButton(game.getSubimage(480, 373, w, 21), game.getSubimage(380, 373, w, 21), game.getSubimage(280, 373, w, 21), game.getSubimage(180, 373, w, 21), true );
			helpbutton.setText(resb.getString("game.menu.manual"));
			helpbutton.setBounds(35, 170, w , 20 );
			helpbutton.addActionListener( buttonActionListener );




			resumebutton = makeRiskButton(game.getSubimage(480, 373, w, 21), game.getSubimage(380, 373, w, 21), game.getSubimage(280, 373, w, 21), game.getSubimage(180, 373, w, 21), true );
			resumebutton.setText(resb.getString("game.menu.closemenu"));
			resumebutton.setBounds(35, 200, w , 20 );
			resumebutton.addActionListener( buttonActionListener );

			add(savebutton);
			add(AutoDefend);
			add(helpbutton);
			add(AutoEndGo);
			add(closebutton);
			add(resumebutton);

		}

		public void paintComponent(Graphics g) {

			Graphics2D g2 = (Graphics2D)g;

			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

			AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f);
			g2.setComposite(ac);

//					  destination		source
			g2.drawImage(game,0,0,170,250,     633,175,803,425,this); // top

			FontRenderContext frc = g2.getFontRenderContext();

			Font font = new java.awt.Font("Arial", java.awt.Font.BOLD, 24);
			g2.setColor( Color.black );
			TextLayout tl;

			tl = new TextLayout( resb.getString("game.menu.title") , font, frc);
			tl.draw( g2, (float) (85-tl.getBounds().getWidth()/2), (float)40 );

		}

	}




}

