package tmaestroplayer;

import edutainmentclient.Main;
import java.awt.BorderLayout;

import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ContainerEvent;
import java.awt.event.InputMethodEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Stack;
import java.util.Vector;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.CannotRealizeException;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.StartEvent;
import javax.media.StopEvent;
import javax.media.Time;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.plaf.basic.BasicDesktopPaneUI;
import javax.swing.plaf.basic.BasicInternalFrameUI;

//import tm.applet.AppletTemplateComponentsXML.TimerListener;
import tmaestroplayer.template.TemplateComponentsJavaXML;

public class VentanaSeleccionUnidad extends JInternalFrame /*implements ControllerListener*/ {

    // Unidad del curso
    //SSS 26102009 debería estar publico
    public Unit unidadPrincipal;
    // Ruta del imsmanifest.xml y de los recursos asociados
    private String path;
    // Se india el Applet para la representaci�n del contenido 
    //SSS 26102009 aqui lo tengo publco
    //private CVApplet applet;
    //Ahora es una referencia a un JFrame
    public MainWindow frame;
    // idCliente necesario para la comunicaci�n con el servidor
    private String nameCliente = null;
    //nombre de la opcion a reproducir en los SCOs
    private String option;
    // Vector que contiene los elementos del estilo
    private Vector style = new Vector();
    // M�sica de fondo del men�
    public Player player; //era private
    // Variable que indica instante de reproducci�n
    public double timer = 0;//
    // Variables para la representaci�n de los componentes
    private URL dirURLup = null;
    private URL dirURLdown = null;
    String name = null, fontstyle = null, size = null, namef, fontstylef, sizef;
    private String r = null, g = null, b = null, rf = null, gf = null, bf = null;
    java.awt.Color colorn;
    java.awt.Color colorf;
    // Componentes graficos del menu de un curso
    private javax.swing.JLabel jLabel0;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabelBACK;
    private javax.swing.JLabel jLabelBACKGROUNDIMAGE;
    private javax.swing.JLabel jLabelDOWN;
    private javax.swing.JLabel jLabelEXIT;
    private javax.swing.JLabel jLabelINFO;
    private javax.swing.JLabel jLabelUP;
    // Indica cual es el primer elemento de la lista
    int offset = 8;
    // Indica cual es el elemento que tiene el focus
    public int focused = 0;
    public VentanaSeleccionUnidad vsupadre; //
    TemplateComponentsJavaXML atcjx;
    final private int LEFT = 0;
    final private int CENTER = 1;
    final private int RIGHT = 2;
    private int currentPosition = 1;

    //public VentanaSeleccionUnidad(Unit unidades[], String path, CVApplet applet, String optionName, Vector vstyle, double timePlayer, VentanaSeleccionUnidad vsupadre) {
    public VentanaSeleccionUnidad(Unit unidades[], String path, MainWindow frame, String optionName, Vector vstyle, double timePlayer, VentanaSeleccionUnidad vsupadre) {
        System.out.println("ventana selección unidad");
        this.vsupadre = vsupadre;
        unidadPrincipal = unidades[0];
        this.path = path;
        //this.applet = applet;
        this.frame = frame;
        //this.nameCliente = nameclnt;
        this.option = optionName;
        this.style = vstyle;
        this.timer = timePlayer;

        Unit[] subunidades = unidadPrincipal.getSubUnits();
        initComponents(subunidades.length);
    }

    /*******************************************************************************
     * Representa la imagen de fondo,la musica del men� y item focused de un curso *
     *******************************************************************************/
    //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
    private void myPersonalInitComponents(ImageIcon imagen) {
        //private void myPersonalInitComponents(ImageIcon imagen, Player player) {
        jLabelBACKGROUNDIMAGE.setIcon(imagen);
        //startPlayerUnidades(player, false);
        setFocused(0);
        setFocusable(true);
    }

    /*******************************************************************************
     *        Inicializa los componentes gr�ficos del men� del curso               *
     *******************************************************************************/
    private void initComponents(int numItems) {
        java.awt.GridBagConstraints gridBagConstraints;

        jLabel0 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabelINFO = new javax.swing.JLabel();
        jLabelEXIT = new javax.swing.JLabel();
        jLabelUP = new javax.swing.JLabel();
        jLabelDOWN = new javax.swing.JLabel();
        jLabelBACK = new javax.swing.JLabel();
        jLabelBACKGROUNDIMAGE = new javax.swing.JLabel();

        //-----------------------------------
        // Lectura de las variables de estilo: 
        String backgroundimage = null;
        String backgroundmusic = null;
        String exiticon = null;
        String gobackicon = null;
        String bulletpoints = null;
        String scrolluparrow = null;
        String scrolldownarrow = null;

        for (int i = 0; i < style.size(); i++) {
            HashMap map = (HashMap) style.get(i);
            backgroundimage = (String) map.get("backgroundimage");
            backgroundmusic = (String) map.get("backgroundmusic");
            exiticon = (String) map.get("exiticon");
            gobackicon = (String) map.get("gobackicon");
            bulletpoints = (String) map.get("bulletpoints");
            scrolluparrow = (String) map.get("scrolluparrow");
            scrolldownarrow = (String) map.get("scrolldownarrow");
            HashMap normalfont = (HashMap) map.get("normalfont");
            HashMap normalcolor = (HashMap) map.get("normalcolor");
            HashMap focusedfont = (HashMap) map.get("focusedfont");
            HashMap focusedcolor = (HashMap) map.get("focusedcolor");

            name = (String) normalfont.get("name");
            fontstyle = (String) normalfont.get("fontstyle");
            size = (String) normalfont.get("size");

            r = (String) normalcolor.get("r");
            g = (String) normalcolor.get("g");
            b = (String) normalcolor.get("b");

            namef = (String) focusedfont.get("name");
            fontstylef = (String) focusedfont.get("fontstyle");
            sizef = (String) focusedfont.get("size");

            rf = (String) focusedcolor.get("r");
            gf = (String) focusedcolor.get("g");
            bf = (String) focusedcolor.get("b");
        }

        colorn = new java.awt.Color(Integer.parseInt(r), Integer.parseInt(g), Integer.parseInt(b));
        colorf = new java.awt.Color(Integer.parseInt(rf), Integer.parseInt(gf), Integer.parseInt(bf));

        // Imagen de fondo del men�     
        URL dirURL = null;
        try {
            String nnn = path + backgroundimage;
            dirURL = new URL(nnn);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
        ImageIcon icono = new javax.swing.ImageIcon(dirURL);


        //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
        /*
        // M�sica de fondo del men�
        URL dirPlayer = null;
        try {
        dirPlayer = new URL(path + backgroundmusic);
        } catch (MalformedURLException e) {
        e.printStackTrace();
        }
        Player mediaPlayer = null;
        try {
        mediaPlayer = Manager.createRealizedPlayer(dirPlayer);
        } catch (NoPlayerException e) {
        System.err.println(e);
        } catch (CannotRealizeException e) {
        System.err.println(e);
        } catch (IOException e) {
        System.err.println(e);
        }
        this.player = mediaPlayer;
        this.player.addControllerListener(this);
         */

        // Iconos up&down
        try {
            dirURLup = new URL(path + scrolluparrow);
            dirURLdown = new URL(path + scrolldownarrow);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }

        // Iconos BulletPoints
        URL dirURLbulletpoints = null;
        try {
            dirURLbulletpoints = new URL(path + bulletpoints);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
        ImageIcon iconbulletpoints = new javax.swing.ImageIcon(dirURLbulletpoints);

        //-----------------------------------
        //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
        myPersonalInitComponents(icono);
        //myPersonalInitComponents(icono, mediaPlayer);

        getContentPane().setLayout(new java.awt.GridBagLayout());
        setBackground(new java.awt.Color(191, 191, 255));
        setBorder(null);
        setMaximumSize(new java.awt.Dimension(720, 576));
        setMinimumSize(new java.awt.Dimension(720, 576));
        setPreferredSize(new java.awt.Dimension(720, 576));

        /*addKeyListener(new java.awt.event.KeyAdapter() {

        public void keyPressed(java.awt.event.KeyEvent evt) {
        formKeyPressed(evt);
        }
        });*/

        final java.awt.Color colorNormal = colorn;
        final java.awt.Color colorFocused = colorf;

        if (numItems > 0) {
            if (focused != 0) {
                jLabel0.setFont(new java.awt.Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
            }
            jLabel0.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            jLabel0.setIcon(iconbulletpoints);
            jLabel0.setMaximumSize(new java.awt.Dimension(300, 50));
            jLabel0.setMinimumSize(new java.awt.Dimension(300, 50));
            jLabel0.setPreferredSize(new java.awt.Dimension(300, 50));
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = 2;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            getContentPane().add(jLabel0, gridBagConstraints);
            jLabel0.addMouseListener(new java.awt.event.MouseListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                }

                public void mouseEntered(MouseEvent arg0) {
                    setFocusedMouse(focused, 0);
                }

                public void mouseExited(MouseEvent arg0) {
                    jLabel0.setForeground(colorNormal);
                    jLabel0.setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
                }

                public void mousePressed(MouseEvent arg0) {
                    //focused = 0;
                    focused = 0 + offset;
                    goENTER();
                }

                public void mouseClicked(MouseEvent arg0) {
                }

                public void mouseReleased(MouseEvent arg0) {
                }
            });

        }
        if (numItems > 1) {
            if (focused != 1) {
                jLabel1.setFont(new java.awt.Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
            }
            jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            jLabel1.setIcon(iconbulletpoints);
            jLabel1.setMaximumSize(new java.awt.Dimension(300, 50));
            jLabel1.setMinimumSize(new java.awt.Dimension(300, 50));
            jLabel1.setPreferredSize(new java.awt.Dimension(300, 50));
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = 3;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            getContentPane().add(jLabel1, gridBagConstraints);
            jLabel1.addMouseListener(new java.awt.event.MouseListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                }

                public void mouseEntered(MouseEvent arg0) {
                    setFocusedMouse(focused, 1);
                }

                public void mouseExited(MouseEvent arg0) {
                    jLabel1.setForeground(colorNormal);
                    jLabel1.setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
                }

                public void mousePressed(MouseEvent arg0) {
                    //focused = 1;
                    focused = 1 + offset;
                    goENTER();
                }

                public void mouseClicked(MouseEvent arg0) {
                }

                public void mouseReleased(MouseEvent arg0) {
                }
            });
        }
        if (numItems > 2) {
            if (focused != 2) {
                jLabel2.setFont(new java.awt.Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
            }
            jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            jLabel2.setIcon(iconbulletpoints);
            jLabel2.setMaximumSize(new java.awt.Dimension(300, 50));
            jLabel2.setMinimumSize(new java.awt.Dimension(300, 50));
            jLabel2.setPreferredSize(new java.awt.Dimension(300, 50));
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = 4;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            getContentPane().add(jLabel2, gridBagConstraints);
            jLabel2.addMouseListener(new java.awt.event.MouseListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                }

                public void mouseEntered(MouseEvent arg0) {
                    setFocusedMouse(focused, 2);
                }

                public void mouseExited(MouseEvent arg0) {
                    jLabel2.setForeground(colorNormal);
                    jLabel2.setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
                }

                public void mousePressed(MouseEvent arg0) {
                    //focused = 2;
                    focused = 2 + offset;
                    goENTER();
                }

                public void mouseClicked(MouseEvent arg0) {
                }

                public void mouseReleased(MouseEvent arg0) {
                }
            });
        }
        if (numItems > 3) {
            if (focused != 3) {
                jLabel3.setFont(new java.awt.Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
            }
            jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            jLabel3.setIcon(iconbulletpoints);
            jLabel3.setMaximumSize(new java.awt.Dimension(300, 50));
            jLabel3.setMinimumSize(new java.awt.Dimension(300, 50));
            jLabel3.setPreferredSize(new java.awt.Dimension(300, 50));
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = 5;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            getContentPane().add(jLabel3, gridBagConstraints);
            jLabel3.addMouseListener(new java.awt.event.MouseListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                }

                public void mouseEntered(MouseEvent arg0) {
                    setFocusedMouse(focused, 3);
                }

                public void mouseExited(MouseEvent arg0) {
                    jLabel3.setForeground(colorNormal);
                    jLabel3.setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
                }

                public void mousePressed(MouseEvent arg0) {
                    //focused = 3;
                    focused = 3 + offset;
                    goENTER();
                }

                public void mouseClicked(MouseEvent arg0) {
                }

                public void mouseReleased(MouseEvent arg0) {
                }
            });
        }
        if (numItems > 4) {
            if (focused != 4) {
                jLabel4.setFont(new java.awt.Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
            }
            jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            jLabel4.setIcon(iconbulletpoints);
            jLabel4.setMaximumSize(new java.awt.Dimension(300, 50));
            jLabel4.setMinimumSize(new java.awt.Dimension(300, 50));
            jLabel4.setPreferredSize(new java.awt.Dimension(300, 50));
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = 6;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            getContentPane().add(jLabel4, gridBagConstraints);
            jLabel4.addMouseListener(new java.awt.event.MouseListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                }

                public void mouseEntered(MouseEvent arg0) {
                    setFocusedMouse(focused, 4);
                }

                public void mouseExited(MouseEvent arg0) {
                    jLabel4.setForeground(colorNormal);
                    jLabel4.setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
                }

                public void mousePressed(MouseEvent arg0) {
                    //focused = 4;
                    focused = 4 + offset;
                    goENTER();
                }

                public void mouseClicked(MouseEvent arg0) {
                }

                public void mouseReleased(MouseEvent arg0) {
                }
            });
        }
        if (numItems > 5) {
            if (focused != 5) {
                jLabel5.setFont(new java.awt.Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
            }
            jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            jLabel5.setIcon(iconbulletpoints);
            jLabel5.setMaximumSize(new java.awt.Dimension(300, 50));
            jLabel5.setMinimumSize(new java.awt.Dimension(300, 50));
            jLabel5.setPreferredSize(new java.awt.Dimension(300, 50));
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = 7;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            getContentPane().add(jLabel5, gridBagConstraints);
            jLabel5.addMouseListener(new java.awt.event.MouseListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                }

                public void mouseEntered(MouseEvent arg0) {
                    setFocusedMouse(focused, 5);
                }

                public void mouseExited(MouseEvent arg0) {
                    jLabel5.setForeground(colorNormal);
                    jLabel5.setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
                }

                public void mousePressed(MouseEvent arg0) {
                    //focused = 5;
                    focused = 5 + offset;
                    goENTER();
                }

                public void mouseClicked(MouseEvent arg0) {
                }

                public void mouseReleased(MouseEvent arg0) {
                }
            });
        }
        if (numItems > 6) {
            if (focused != 6) {
                jLabel6.setFont(new java.awt.Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
            }
            jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            jLabel6.setIcon(iconbulletpoints);
            jLabel6.setMaximumSize(new java.awt.Dimension(300, 50));
            jLabel6.setMinimumSize(new java.awt.Dimension(300, 50));
            jLabel6.setPreferredSize(new java.awt.Dimension(300, 50));
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = 8;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            getContentPane().add(jLabel6, gridBagConstraints);
            jLabel6.addMouseListener(new java.awt.event.MouseListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                }

                public void mouseEntered(MouseEvent arg0) {
                    setFocusedMouse(focused, 6);
                }

                public void mouseExited(MouseEvent arg0) {
                    jLabel6.setForeground(colorNormal);
                    jLabel6.setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
                }

                public void mousePressed(MouseEvent arg0) {
                    //focused = 6;
                    focused = 6 + offset;
                    goENTER();
                }

                public void mouseClicked(MouseEvent arg0) {
                }

                public void mouseReleased(MouseEvent arg0) {
                }
            });
        }
        if (numItems > 7) {
            if (focused != 7) {
                jLabel7.setFont(new java.awt.Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
            }
            jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            jLabel7.setIcon(iconbulletpoints);
            jLabel7.setMaximumSize(new java.awt.Dimension(300, 50));
            jLabel7.setMinimumSize(new java.awt.Dimension(300, 50));
            jLabel7.setPreferredSize(new java.awt.Dimension(300, 50));
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = 9;
            gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
            getContentPane().add(jLabel7, gridBagConstraints);
            jLabel7.addMouseListener(new java.awt.event.MouseListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {
                }

                public void mouseEntered(MouseEvent arg0) {
                    setFocusedMouse(focused, 7);
                }

                public void mouseExited(MouseEvent arg0) {
                    jLabel7.setForeground(colorNormal);
                    jLabel7.setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
                }

                public void mousePressed(MouseEvent arg0) {
                    //focused = 7;
                    focused = 7 + offset;
                    goENTER();
                }

                public void mouseClicked(MouseEvent arg0) {
                }

                public void mouseReleased(MouseEvent arg0) {
                }
            });
        }
        jLabelINFO.setBackground(new java.awt.Color(255, 255, 255));
        jLabelINFO.setBorder(javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, new java.awt.Color(0, 0, 0)));
        jLabelINFO.setMaximumSize(new java.awt.Dimension(500, 60));
        jLabelINFO.setMinimumSize(new java.awt.Dimension(500, 60));
        jLabelINFO.setOpaque(true);
        jLabelINFO.setPreferredSize(new java.awt.Dimension(500, 60));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(4, 40, 0, 40);
        getContentPane().add(jLabelINFO, gridBagConstraints);

        URL dirURLicon = null;
        try {
            dirURLicon = new URL(path + exiticon);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }

        jLabelEXIT.setIcon(new javax.swing.ImageIcon(dirURLicon));
        jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(255, 0, 0)));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 20);
        getContentPane().add(jLabelEXIT, gridBagConstraints);
        jLabelEXIT.addMouseListener(new java.awt.event.MouseListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
            }

            public void mouseEntered(MouseEvent arg0) {
                jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, java.awt.Color.YELLOW));
            }

            public void mouseExited(MouseEvent arg0) {
                jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(255, 0, 0)));
            }

            public void mousePressed(MouseEvent arg0) {
                System.out.println("Se pulsó exit en la vsu");
                Main.started = false;
                stopPlayerUnidades();
                String courseId = frame.getCourseLoader().getCourseId();


                VentanaSeleccionUnidad vsup;
                VentanaSeleccionUnidad vsuaux;
                vsup = vsupadre;
                while (vsup != null) {
                    vsuaux = vsup;
                    vsup = vsup.vsupadre;
                    //applet.atcjx.panel.remove(vsuaux);
                    //applet.oCL.panel.remove(vsuaux);
                    frame.oCL.panel.remove(vsuaux);
                }
                dispose();

                /*applet.remove(applet.oCL.panel);
                applet.oLF = new LoginFrame(applet);
                applet.panel = (JDesktopPane) applet.oLF.getVisual();
                applet.add(applet.panel);*/
                //Ahora al pulsar salir volvemos a la ventana de login
                //applet.jsi.invoke("history.back()");

                //Gonzalo 16122009: Ahora no eliminamos el panel sino que le añadimos la ventana de login
                //applet.panel.setVisible(false);
                frame.panel.setVisible(false);
                //if (applet.oLoginFrame == null) {
                /*if (frame.oGLF == null) {
                System.out.println("la login frame es null");
                } else {
                System.out.println("la login frame no es null");
                }*/
                //applet.panel.add(applet.oLoginFrame);
                //frame.panel.add(frame.oGLF);
                //applet.panel.setVisible(true);
                //frame.panel.setVisible(true);
                //frame.panel.requestFocusInWindow();
                //applet.panel.getDesktopManager().activateFrame(applet.oLoginFrame);
                //frame.panel.getDesktopManager().activateFrame(frame.oGLF);
                frame.dispose();

                Main.edutainmentStopEvent(courseId, null, null);
                Main.sendRulDelMessage();


            }

            public void mouseClicked(MouseEvent arg0) {
            }

            public void mouseReleased(MouseEvent arg0) {
            }
        });


        jLabelUP.setMaximumSize(new java.awt.Dimension(26, 26));
        jLabelUP.setMinimumSize(new java.awt.Dimension(26, 26));
        jLabelUP.setPreferredSize(new java.awt.Dimension(26, 26));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(20, 100, 0, 0);
        getContentPane().add(jLabelUP, gridBagConstraints);
        jLabelUP.addMouseListener(new java.awt.event.MouseListener() {

            public void mouseEntered(MouseEvent arg0) {
            }

            public void mouseExited(MouseEvent arg0) {
            }

            public void mousePressed(MouseEvent arg0) {
                goUP();
            }

            public void mouseClicked(MouseEvent arg0) {
            }

            public void mouseReleased(MouseEvent arg0) {
            }
        });

        jLabelDOWN.setMaximumSize(new java.awt.Dimension(26, 26));
        jLabelDOWN.setMinimumSize(new java.awt.Dimension(26, 26));
        jLabelDOWN.setPreferredSize(new java.awt.Dimension(26, 26));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 10;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 100, 0, 0);
        getContentPane().add(jLabelDOWN, gridBagConstraints);
        jLabelDOWN.addMouseListener(new java.awt.event.MouseListener() {

            public void mouseEntered(MouseEvent arg0) {
            }

            public void mouseExited(MouseEvent arg0) {
            }

            public void mousePressed(MouseEvent arg0) {
                goDOWN();
            }

            public void mouseClicked(MouseEvent arg0) {
            }

            public void mouseReleased(MouseEvent arg0) {
            }
        });

        try {
            dirURLicon = new URL(path + gobackicon);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
        jLabelBACK.setIcon(new javax.swing.ImageIcon(dirURLicon));
        jLabelBACK.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(0, 204, 0)));
        jLabelBACK.setMaximumSize(new java.awt.Dimension(45, 62));
        jLabelBACK.setMinimumSize(new java.awt.Dimension(45, 62));
        jLabelBACK.setPreferredSize(new java.awt.Dimension(45, 62));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(2, 20, 0, 0);
        getContentPane().add(jLabelBACK, gridBagConstraints);
        /*
        if (this.vsupadre == null) {
        jLabelBACK.setEnabled(false);
        } else {
         */

        jLabelBACK.addMouseListener(new java.awt.event.MouseListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
            }

            public void mouseEntered(MouseEvent arg0) {
                jLabelBACK.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, java.awt.Color.YELLOW));
            }

            public void mouseExited(MouseEvent arg0) {
                jLabelBACK.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(0, 204, 0)));
            }

            public void mousePressed(MouseEvent arg0) {
                if (vsupadre == null) {
                    System.out.println("aqui mostrar los cursos denuevo ");
                    stopPlayerUnidades();
                    VentanaSeleccionUnidad vsup;
                    VentanaSeleccionUnidad vsuaux;
                    vsup = vsupadre;
                    while (vsup != null) {
                        vsuaux = vsup;
                        vsup = vsup.vsupadre;
                        //applet.atcjx.panel.remove(vsuaux);
                        //applet.oCL.panel.remove(vsuaux);
                        frame.oCL.panel.remove(vsuaux);
                        vsuaux.dispose();
                    }
                    dispose();
                    System.out.println("El panel tiene " + frame.panel.getAllFrames().length + " frames");
                    frame.panel.setVisible(false);
                    frame.dispose();
                    frame.removeAll();
                    System.out.println(frame.getClass());
                    Window[] windows = Window.getWindows();
                    for (Window window : windows) {
                        System.out.println(window.getName() + ": " + window.getClass());
                        if (window.getClass() == frame.getClass()) {
                            System.out.println("es el tipo");
                            window.dispose();
                        }
                    }

                    System.gc();
                    System.out.println("aqui mostrar los cursos denuevo");
                    if (Main.mw_portada != null) {
                        Main.mw_portada.init();
                    } else {
                         Main.mw_portada = new MainWindow_portada(Main.userId, Main.listaCursos);
                            Main.mw_portada.init();
                            Main.started = true;
                    }
                } else {
                    goBACK();
                }

                /*vsupadre.setVisible(true);
                vsupadre.moveToFront();

                //Cambiado de orden para hacerlo justo antes de iniciar el otro reproductor
                vsupadre.timer = player.getMediaTime().getSeconds();
                stopPlayerUnidades();

                vsupadre.startPlayerUnidades(vsupadre.player, true);
                dispose();*/
            }

            public void mouseClicked(MouseEvent arg0) {
            }

            public void mouseReleased(MouseEvent arg0) {
            }
        });
        //  } //de el else

        jLabelBACKGROUNDIMAGE.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelBACKGROUNDIMAGE.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jLabelBACKGROUNDIMAGE.setMaximumSize(new java.awt.Dimension(720, 554));
        jLabelBACKGROUNDIMAGE.setMinimumSize(new java.awt.Dimension(720, 554));
        jLabelBACKGROUNDIMAGE.setPreferredSize(new java.awt.Dimension(720, 554));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.gridheight = 11;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
        getContentPane().add(jLabelBACKGROUNDIMAGE, gridBagConstraints);
        pack();
    }

    /*******************************************************************************
     *          Acciones relacionadas con los eventos del teclado                  *
     *******************************************************************************/
    private void formKeyPressed(java.awt.event.KeyEvent evt) {
        VentanaSeleccionUnidad vsuOrig = (VentanaSeleccionUnidad) evt.getSource();
        System.out.println("Se recibió una pulsación de tecla en al vsu: " + vsuOrig.unidadPrincipal.getName());
        switch (evt.getKeyCode()) {
            case KeyEvent.VK_UP:
                goUP();
                break;
            case KeyEvent.VK_DOWN:
                goDOWN();
                break;
            case KeyEvent.VK_LEFT:
                goLEFT();
                break;
            case KeyEvent.VK_RIGHT:
                goRIGHT();
                break;
            case KeyEvent.VK_ENTER:
                switch (currentPosition) {
                    case LEFT:
                        goBACK();
                        break;
                    case CENTER:
                        goENTER();
                        break;
                    case RIGHT:
                        goEXIT();
                        break;
                }
                break;
        }
    }

    public void upEvent() {
        goUP();
    }

    public void downEvent() {
        goDOWN();
    }

    public void leftEvent() {
        goLEFT();
    }

    public void rightEvent() {
        goRIGHT();
    }

    public void enterEvent() {
        System.out.println(currentPosition);
        switch (currentPosition) {
            case LEFT:
                System.out.println("goBack");
                goBACK();
                break;
            case CENTER:
                goENTER();
                break;
            case RIGHT:

                System.out.println("Se pulsó exit en la vsu");
                Main.started = false;
                stopPlayerUnidades();
                String courseId = frame.getCourseLoader().getCourseId();

                VentanaSeleccionUnidad vsup;
                VentanaSeleccionUnidad vsuaux;
                vsup = vsupadre;
                while (vsup != null) {
                    vsuaux = vsup;
                    vsup = vsup.vsupadre;

                    frame.oCL.panel.remove(vsuaux);
                }
                dispose();
                frame.panel.setVisible(false);
                frame.dispose();
                Main.edutainmentStopEvent(courseId, null, null);
                Main.sendRulDelMessage();
                //goEXIT();
                break;
        }
    }

    private void goUP() {
        if (currentPosition == CENTER) {
            setFocused(focused - 1);
        }
    }

    private void goDOWN() {
        if (currentPosition == CENTER) {
            setFocused(focused + 1);
        }
    }

    private void goLEFT() {
        System.out.println("goLeft " + currentPosition);
        switch (currentPosition) {
            case LEFT:

                break;
            case CENTER:
                // if (vsupadre != null) {
                jLabelBACK.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, java.awt.Color.YELLOW));
                currentPosition = LEFT;
                setUnfocused(focused);
                //  }

                break;
            case RIGHT:
                jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(255, 0, 0)));
                currentPosition = CENTER;
                setFocused(focused);
                break;
        }
    }

    private void goRIGHT() {
        switch (currentPosition) {
            case LEFT:
                jLabelBACK.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(0, 204, 0)));
                currentPosition = CENTER;
                setFocused(focused);
                break;
            case CENTER:
                jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, java.awt.Color.YELLOW));
                currentPosition = RIGHT;
                setUnfocused(focused);
                break;
            case RIGHT:
                break;
        }
    }

    private void goBACK() {
        if (vsupadre == null) {
            stopPlayerUnidades();
            VentanaSeleccionUnidad vsup;
            VentanaSeleccionUnidad vsuaux;
            vsup = vsupadre;
            while (vsup != null) {
                vsuaux = vsup;
                vsup = vsup.vsupadre;
                //applet.atcjx.panel.remove(vsuaux);
                //applet.oCL.panel.remove(vsuaux);
                frame.oCL.panel.remove(vsuaux);
                vsuaux.dispose();
            }
            dispose();
            System.out.println("El panel tiene " + frame.panel.getAllFrames().length + " frames");
            frame.panel.setVisible(false);
            frame.dispose();
            frame.removeAll();
            System.out.println(frame.getClass());
            Window[] windows = Window.getWindows();
            for (Window window : windows) {
                System.out.println(window.getName() + ": " + window.getClass());
                if (window.getClass() == frame.getClass()) {
                    System.out.println("es el tipo");
                    window.dispose();
                }
            }

            System.gc();
            System.out.println("aqui mostrar los cursos denuevo");
            Main.mw_portada.init();
        } else {
            vsupadre.setVisible(true);
            vsupadre.moveToFront();


            //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
            //Cambiado de orden para hacerlo justo antes de iniciar el otro reproductor
        /*vsupadre.timer = player.getMediaTime().getSeconds();
            stopPlayerUnidades();

            vsupadre.startPlayerUnidades(vsupadre.player, true);*/

            /* System.out.println("vsupadre, estado de selección: " + isSelected());
            try {
            vsupadre.setSelected(true);
            } catch (PropertyVetoException ex) {
            ex.printStackTrace();
            }

            System.out.println("Despues de solicitar selección, vsupadre, estado de selección: " + isSelected());
            System.out.println("vsupadre pidió focus: " + vsupadre.requestFocusInWindow());*/

            //applet.panel.setVisible(false);
            //applet.panel.setVisible(true);

            //System.out.println("JDesktop pane pidió el focus: "+applet.panel.requestFocusInWindow());
            //applet.panel.remove(this);
            frame.panel.remove(this);
            //applet.panel.getDesktopManager().activateframe(vsupadre);
            frame.panel.getDesktopManager().activateFrame(vsupadre);
            System.out.println("¿Le dieron el foco a vsupadre? " + vsupadre.requestFocusInWindow());
            //applet.panel.setSelectedFrame(vsupadre);


            //System.out.println("focusOwner:" +vsupadre.isFocusOwner());
            dispose();
        }
    }

    private void goEXIT() {
        stopPlayerUnidades();
        VentanaSeleccionUnidad vsup;
        VentanaSeleccionUnidad vsuaux;
        vsup = vsupadre;
        while (vsup != null) {
            vsuaux = vsup;
            vsup = vsup.vsupadre;
            //applet.atcjx.panel.remove(vsuaux);
            //applet.oCL.panel.remove(vsuaux);
            frame.oCL.panel.remove(vsuaux);
            vsuaux.dispose();
        }
        dispose();

        System.out.println("El panel tiene " + frame.panel.getAllFrames().length + " frames");
        /*applet.remove(applet.oCL.panel);
        applet.oLF = new LoginFrame(applet);
        applet.panel = (JDesktopPane) applet.oLF.getVisual();
        applet.add(applet.panel);*/


        //Gonzalo 16122009: Ahora no eliminamos el panel sino que le añadimos la ventana de login
        //applet.panel.setVisible(false);
        frame.panel.setVisible(false);
        //if (applet.oLoginFrame == null) {
        /*if (frame.oGLF == null) {
        System.out.println("la login frame es null");
        } else {
        System.out.println("la login frame no es null");
        }*/
        //applet.panel.add(applet.oLoginFrame);
        //frame.panel.add(frame.oGLF);
        //applet.panel.setVisible(true);
        //frame.panel.setVisible(true);
        //frame.panel.requestFocusInWindow();
        //this.applet.panel.getDesktopManager().activateFrame(applet.oLoginFrame);
        //this.frame.panel.getDesktopManager().activateFrame(frame.oGLF);
        frame.dispose();
        System.gc();

    }

    /**************************************************************************************
     * Envio al servidor TM el idSCO seleccionado y reproduce en pantalla la opci�n dada  *
     **************************************************************************************/
    //SSS 26102009 esta public
    private void goENTER() {
        Unit[] subunidades = unidadPrincipal.getSubUnits();
        if (subunidades[focused].getSubUnits() == null || subunidades[focused].getSubUnits().length == 0) {
            if (subunidades[focused].getResources() != null && subunidades[focused].getResources().length != 0) {
                pausePlayerUnidades();
                String[] sco = subunidades[focused].getResources();
                //try {
                //URL urlservlet = new URL(urlServlet);
                //URLConnection conservlet = urlservlet.openConnection();
                //conservlet.setDoInput(true);
                //conservlet.setDoOutput(true);
                //conservlet.setUseCaches(false);
                String nameSCO = sco[0];
                //String obj = "idSCO:" + sco[0] + " idCliente:" + nameCliente;
                //conservlet.setRequestProperty("Content-Type", "java-internal" + obj.getClass().getName());
                //Envio del idSCO seleccionado y del idCliente al servidor
                //ObjectOutputStream output = new ObjectOutputStream(conservlet.getOutputStream());
                //output.writeObject(obj);
                //output.flush();
                //output.close();
                // Respuesta servidor: conjunto pares {idCurso(nombre),imagenCurso(URL)}
                //ObjectInputStream input = new ObjectInputStream(conservlet.getInputStream());
                //Object response = input.readObject();
                //String option = (String) response;


                String optionF = this.frame.getOption(this.frame.rutaScorm + this.frame.nombreCurso + nameSCO, this.option);
                //String option = this.option;

                if (option.equals("0")) {
                } else {
                    // Mostramos el contenido del SCO


                    //Ahora creamos un objeto de la clase VentanaSCO que almacena la referencia al atcx
                    //final JInternalFrame jif = new JInternalFrame();



                    //TemplateComponentsJavaXML atcjx = new AppletTemplateComponentsXML(urlApplet, nameSCO, option);
                    //SSS 26102009 aqui paso un this para el next supongo
                    //y tengo el TemplateComponentsJavaXML global para poder usarlo
                    //atcjx = new AppletTemplateComponentsXML(this.applet.rutaScorm + this.applet.nombreCurso, nameSCO, option, this);
                    atcjx = new AppletTemplateComponentsXML(this.frame.rutaScorm + this.frame.nombreCurso, nameSCO, optionF, this);

                    //Creamos una VentanaSCO que almacena la referencia al atcjx para poder enviarle los eventos de teclado
                    final VentanaSCO jif = new VentanaSCO((AppletTemplateComponentsXML) atcjx);

                    JDesktopPane dp = new JDesktopPane();
                    dp.setOpaque(true);
                    dp.setBounds(0, 0, 720, 576);
                    dp.setVisible(true);
                    jif.setContentPane(dp);
                    final Component ccc = atcjx.getVisualTemplateComponent();
                    final VentanaSeleccionUnidad vsu = this;

                    //System.out.println("Memoria total: " + Runtime.getRuntime().totalMemory());
                    //System.out.println("Memoria libre: " + Runtime.getRuntime().freeMemory());

                    ccc.addComponentListener(new java.awt.event.ComponentListener() {

                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                        }

                        public void componentHidden(ComponentEvent arg0) {
                            //stopPlayerUnidades();
                            moveToFront();
                            setVisible(true);
                            //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
                            //startPlayerUnidades(player, true);
                            startPlayerUnidades();
                            //applet.oCL.panel.remove(jif);
                            frame.oCL.panel.remove(jif);

                            //applet.oCL.panel.getDesktopManager().activateFrame(vsu);
                            frame.oCL.panel.getDesktopManager().activateFrame(vsu);
                            vsu.requestFocusInWindow();

                            //SSS 26102009 aqui el control del next
                            if (atcjx.NEXT) {
                                setFocusedMouse(focused, atcjx.newfocused + offset);
                                atcjx = null;
                                jif.dispose();
                                //System.out.println("Memoria total: " + Runtime.getRuntime().totalMemory());
                                //System.out.println("Memoria libre: " + Runtime.getRuntime().freeMemory());
                                goENTER();
                            } else {
                                ((AppletTemplateComponentsXML) atcjx).p = null;
                                atcjx = null;
                                jif.dispose();
                                System.gc();
                                // System.out.println("Memoria total: " + Runtime.getRuntime().totalMemory());
                                // System.out.println("Memoria libre: " + Runtime.getRuntime().freeMemory());
                            }
                        }

                        public void componentMoved(ComponentEvent arg0) {
                        }

                        public void componentResized(ComponentEvent arg0) {
                        }

                        public void componentShown(ComponentEvent arg0) {
                        }
                    });
                    jif.add(ccc);
                    jif.setBorder(null);
                    jif.setMaximumSize(new java.awt.Dimension(720, 576));
                    jif.setMinimumSize(new java.awt.Dimension(720, 576));
                    jif.setPreferredSize(new java.awt.Dimension(720, 576));
                    BasicInternalFrameUI ui = (BasicInternalFrameUI) jif.getUI();
                    ui.setNorthPane(null);
                    /*try {
                    jif.setSelected(true);
                    } catch (PropertyVetoException e) {
                    e.printStackTrace();
                    }*/
                    jif.setVisible(true);

                    //jif.show();
                    jif.pack();
                    //applet.oCL.panel.add(jif);
                    frame.oCL.panel.add(jif);
                    jif.moveToFront();


                    jif.requestFocusInWindow();
                    //applet.oCL.panel.getDesktopManager().activateFrame(jif);
                    frame.oCL.panel.getDesktopManager().activateFrame(jif);

                    /*try {
                    jif.setSelected(true);
                    } catch (PropertyVetoException e) {
                    e.printStackTrace();
                    }*/
                    //SSS 26102009 para controlar todos los delayed
                    for (int i = 0; i < atcjx.HILOS.size(); i++) {

                        DelayedTime aux = (DelayedTime) atcjx.HILOS.get(i);
                        //if (TMAppletI.OUT) System.out.println("entro para "+aux.name);

                        if (aux != null) {
                            aux.start();
                        }
                    }

                }

                //} catch (MalformedURLException e) {
                //    e.printStackTrace();
                //} catch (IOException e) {
                //    e.printStackTrace();
                //} catch (ClassNotFoundException e) {
                //    e.printStackTrace();
                //}
            }
        } else {
            Unit[] nn = new Unit[]{subunidades[focused]};
            //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
            //double timePlayer = player.getMediaTime().getSeconds();
            //stopPlayerUnidades();
            hide();
            //openUnitSelectionWindow(new Unit[]{subunidades[focused]}, null, timePlayer);
            openUnitSelectionWindow(new Unit[]{subunidades[focused]}, null);
        }
    }

    /*******************************************************************************
     *                       Muestra los subItems de un Item                       *
     *******************************************************************************/
    public void openUnitSelectionWindow(Unit unidades[], File courseFile) {
        //public void openUnitSelectionWindow(Unit unidades[], File courseFile, final double timePlayer) {
        final Unit[] units = unidades;


        //System.out.println("numero de vsu's: " + applet.oCL.panel.getAllFrames().length);
        System.out.println("numero de vsu's: " + frame.oCL.panel.getAllFrames().length);
        //VentanaSeleccionUnidad vsu = new VentanaSeleccionUnidad(unidades, path, applet, nameCliente, style, timePlayer, this);

        //Paramos el reproductor justo antes de crear la vsu
        //Ahora no lo paramos, lo parará el método startPlayerUnidades() de la vsu hija
        //stopPlayerUnidades();

        //VentanaSeleccionUnidad vsu = new VentanaSeleccionUnidad(unidades, path, applet, this.option, style, timePlayer, this);
        //VentanaSeleccionUnidad vsu = new VentanaSeleccionUnidad(unidades, path, frame, this.option, style, timePlayer, this);
        System.out.println("llamo a ventana selección unidad1");
        VentanaSeleccionUnidad vsu = new VentanaSeleccionUnidad(unidades, path, frame, this.option, style, 0, this);
        BasicInternalFrameUI ui = (BasicInternalFrameUI) vsu.getUI();
        ui.setNorthPane(null);

        //applet.oCL.panel.add(vsu);
        frame.oCL.panel.add(vsu);
        vsu.moveToFront();
        vsu.setVisible(true);
        //SSS 26102009 yo tengo esto...pero no se para que es...
        //vsu.requestFocusInWindow();

    }

    /*******************************************************************************
     *                       Opciones de reproductor                               *
     *******************************************************************************/
    public void stopPlayerUnidades() {
        //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
        if (frame.bgMusicPlayer != null) {
            frame.bgMusicPlayer.removeControllerListener(frame);
            frame.bgMusicPlayer.stop();
            frame.bgMusicPlayer.setMediaTime(new Time(0));
            frame.bgMusicPlayer.close();
        }
        /*if (player != null) {
        player.stop();
        player.setMediaTime(new Time(0));
        }*/
    }

    public void startPlayerUnidades() {
        if (frame.bgMusicPlayer != null) {
            System.out.println("musicstart");
            frame.bgMusicPlayer.addControllerListener(frame);
            frame.bgMusicPlayer.start();
        }
    }

    public void startPlayerUnidades(Player p, boolean calledFromSon) {
        if (p != null) {
            //Si existe una ventana padre paramos su reproductor y copiamos el valor del tiempo de reproducción
            if (vsupadre != null && !calledFromSon) {
                this.timer = vsupadre.player.getMediaTime().getSeconds();
                vsupadre.stopPlayerUnidades();
            }
            p.setMediaTime(new Time(timer));
            System.out.println("Valor de this.timer: " + this.timer + "\nValor de p.getMediaTime: " + p.getMediaTime().getSeconds());
            p.start();
        }
    }

    private void pausePlayerUnidades() {
        //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
        if (frame.bgMusicPlayer != null) {
            frame.bgMusicPlayer.removeControllerListener(frame);
            frame.bgMusicPlayer.stop();
        }
        /*if (player != null) {
        player.stop();
        }*/
    }

    /*******************************************************************************
     *                 Establece los elementos visibles en pantalla                 *
     *******************************************************************************/
    private void setUnitsCells(int elemento) {

        if (elemento >= offset && elemento < offset + 8) {
            return;
        }

        Unit[] subunidades = unidadPrincipal.getSubUnits();
        if (elemento < offset) {
            offset = elemento;
        } else if (elemento >= offset + 8) {
            offset = elemento - 7;
        }

        int ini = offset;
        int finNOR = offset + 8;
        int finR = subunidades.length;
        int fin = Math.min(finR, finNOR);

        for (int i = ini; i < fin; i++) {
            getLabel(i).setText(subunidades[i].getName());
            getLabel(i).setForeground(colorn);
        }

        for (int i = finR; i < finNOR; i++) {
            getLabel(i).setText(null);
            getLabel(i).setIcon(null);
        }

        if (offset > 0) {
            jLabelUP.setIcon(new javax.swing.ImageIcon(dirURLup));
        } else {
            jLabelUP.setIcon(null);
        }

        if (offset + 7 < subunidades.length - 1) {
            jLabelDOWN.setIcon(new javax.swing.ImageIcon(dirURLdown));
        } else {
            jLabelDOWN.setIcon(null);
        }
    }

    /*******************************************************************************
     *            Establece el "foco" en un determinado objeto                     *
     *******************************************************************************/
    private void setFocused(int f) {

        Unit[] subunidades = unidadPrincipal.getSubUnits();
        if (f < 0 || f >= subunidades.length) {
            return;
        }

        setUnitsCells(f);
        getLabel(focused).setForeground(colorn);
        getLabel(focused).setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
        getLabel(f).setForeground(colorf);
        getLabel(f).setFont(new Font(namef, Integer.parseInt(fontstylef), Integer.parseInt(sizef)));

        jLabelINFO.setText("<html><center>&nbsp;&nbsp;&nbsp;" + unidadPrincipal.getName().toUpperCase() + " <font size=+2><b>\u2192</b></font> "
                + subunidades[f].getName().toUpperCase() + ":   "
                + subunidades[f].getDescription() + "</center></html>");

        focused = f;
        //System.out.println("setFocused: foco " + focused);
    }

    /*******************************************************************************
     *            Elimina el foco de una de las opciones, se utiliza               *
     *            nos desplazamos lateralmente con el mando o teclado              *
     * @param f                                                                    *
     *******************************************************************************/
    private void setUnfocused(int f) {
        getLabel(focused).setForeground(colorn);
        getLabel(focused).setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
        System.out.println("setUnfocused: foco quitado aa " + focused);
    }

    /*******************************************************************************
     *          Establece el "foco" en el objeto seleccionado con el rat�n         *
     *******************************************************************************/
    //SSS 26102009 yo lo tengo publico para el next
    private void setFocusedMouse(int fanterior, int factual) {
        //Al seleccionar una de las etiquetas con el ratón tenemos que comprobar
        //si nos habíamos movido a los botones de atrás o exit con el mando/teclado
        //de ser así, tenemos que desactivarles el estado de "focused"
        //si estamos en el botón BACK con el mando
        if (currentPosition == LEFT) {
            jLabelBACK.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(0, 204, 0)));
        } else if (currentPosition == RIGHT) {//Si estamos en el botón EXIT con el mando
            jLabelEXIT.setBorder(javax.swing.BorderFactory.createMatteBorder(4, 4, 4, 4, new java.awt.Color(255, 0, 0)));
        }//Si estabamos en las "etiquetas" no hacemos nada
        //En cualquier caso cambiamos la posición al "centro"
        currentPosition = CENTER;

        Unit[] subunidades = unidadPrincipal.getSubUnits();
        //SSS 26102009 yo esto no lo tengo, manejamos el offset distinto
        factual = factual + offset;
        if (factual < 0 || factual >= subunidades.length) {
            return;
        }

        setUnitsCells(factual);
        getLabel(fanterior).setForeground(colorn);
        getLabel(fanterior).setFont(new Font(name, Integer.parseInt(fontstyle), Integer.parseInt(size)));
        getLabel(factual).setForeground(colorf);
        getLabel(factual).setFont(new Font(namef, Integer.parseInt(fontstylef), Integer.parseInt(sizef)));

        jLabelINFO.setText("<html><center>&nbsp;&nbsp;&nbsp;" + unidadPrincipal.getName().toUpperCase() + " <font size=+2><b>\u2192</b></font> "
                + subunidades[factual].getName().toUpperCase() + ":   "
                + subunidades[factual].getDescription() + "</center></html>");

        focused = factual;
        //System.out.println("setFocusedMouse: foco " + focused);
    }

    /*******************************************************************************
     *         Obtiene la etiqueta correspondiente a un determinado indice         *
     *******************************************************************************/
    private JLabel getLabel(int i) {
        switch ((i - offset) % 8) { // i-offset debe ser SIEMPRE >= 0
            case 0:
                return jLabel0;
            case 1:
                return jLabel1;
            case 2:
                return jLabel2;
            case 3:
                return jLabel3;
            case 4:
                return jLabel4;
            case 5:
                return jLabel5;
            case 6:
                return jLabel6;
            case 7:
                return jLabel7;
            default:
                return null;
        }
    }

    public void controllerUpdate(ControllerEvent oCE) {
        if (oCE instanceof EndOfMediaEvent) {
            // System.out.println("reiniciando el reproductor de música de fondo");
            player.setMediaTime(new Time(0));
            player.start();
            /*JInternalFrame jif = applet.panel.getSelectedFrame();
            if (jif instanceof LoginFrame) {
            System.out.println("Está seleccionada la loginFrame");
            } else if (jif instanceof VentanaSeleccionUnidad) {
            String vsuName = ((VentanaSeleccionUnidad) jif).unidadPrincipal.getName();
            System.out.println("Está seleccionada la vsu: " + vsuName);
            } else {
            System.out.println("No se de que tipo es la JInternalFrame");
            }*/
        } else if (oCE instanceof StartEvent) {
            //System.out.println("**player started");
        } else if (oCE instanceof StopEvent) {
            System.out.println("**player stopped!!");
        }
    }

    public void restorePoint() {
        String nextItem;
        System.out.println("%%%%%%%SCOPATH: " + frame.oCL.scoPath);

        if (frame.oCL.scoPath != null) {
            if (!frame.oCL.scoPath.equals("")) {//Hay que abrir la siguiente vsu
                int indexEsp = frame.oCL.scoPath.indexOf(" ");
                if (indexEsp != -1) {
                    nextItem = frame.oCL.scoPath.substring(0, indexEsp);
                    System.out.println("################### " + nextItem);
                    frame.oCL.scoPath = frame.oCL.scoPath.substring(indexEsp + 1);
                } else {
                    nextItem = frame.oCL.scoPath;
                    frame.oCL.scoPath = "";
                }
                Unit[] subunidades = unidadPrincipal.getSubUnits();
                int index = 0;
                Unit unidadSeleccionada = null;
                for (Unit unidad : subunidades) {
                    System.out.println(unidad.getIdentifier());
                    if (unidad.getIdentifier().equals(nextItem)) {
                        System.out.println("la encuentro");
                        unidadSeleccionada = unidad;
                        break;
                    }
                    index++;
                }
                setFocused(index);
                System.out.println("llamo a ventana seleccion unidad2");
                Unit[] prueba = new Unit[]{unidadSeleccionada};
                if (prueba == null) {
                    System.out.println("es null");
                }
                VentanaSeleccionUnidad vsu = new VentanaSeleccionUnidad(new Unit[]{unidadSeleccionada}, path, frame, this.option, style, 0, this);
                BasicInternalFrameUI ui = (BasicInternalFrameUI) vsu.getUI();
                ui.setNorthPane(null);

                //applet.oCL.panel.add(vsu);
                frame.oCL.panel.add(vsu);

                vsu.restorePoint();

            } else {//En este caso hay que cargar el SCO
                System.out.println("entro en SCO "+frame.oCL.scoPath);
                Unit[] subunidades = unidadPrincipal.getSubUnits();
                int index = 0;
                Unit unidadSeleccionada = null;
                System.out.println("voy a comparar con " + frame.oCL.lastScoId);
                for (Unit unidad : subunidades) {
                    System.out.println(unidad.getIdentifier());
                    if (unidad.getIdentifier().equals(frame.oCL.lastScoId)) {
                        unidadSeleccionada = unidad;
                        System.out.println("encuentro el sco ");
                        break;
                    }
                    index++;
                }
               // System.out.println("unidad seleccionada " + unidadSeleccionada.getName());
                setFocused(index);
                String[] sco = unidadSeleccionada.getResources();

                String nameSCO = sco[0];
                String optionF = this.frame.getOption(this.frame.rutaScorm + this.frame.nombreCurso + nameSCO, this.option);
                //String option = this.option;
                if (option.equals("0")) {
                } else {
                    // Mostramos el contenido del SCO

                    //TemplateComponentsJavaXML atcjx = new AppletTemplateComponentsXML(urlApplet, nameSCO, option);
                    //SSS 26102009 aqui paso un this para el next supongo
                    //y tengo el TemplateComponentsJavaXML global para poder usarlo
                    //atcjx = new AppletTemplateComponentsXML(this.applet.rutaScorm + this.applet.nombreCurso, nameSCO, option, this);
                    atcjx = new AppletTemplateComponentsXML(this.frame.rutaScorm + this.frame.nombreCurso, nameSCO, optionF, this);

                    //Creamos una VentanaSCO que almacena la referencia al atcjx para poder enviarle los eventos de teclado
                    final VentanaSCO jif = new VentanaSCO((AppletTemplateComponentsXML) atcjx);

                    JDesktopPane dp = new JDesktopPane();
                    dp.setOpaque(true);
                    dp.setBounds(0, 0, 720, 576);
                    dp.setVisible(true);
                    jif.setContentPane(dp);
                    final Component ccc = atcjx.getVisualTemplateComponent();
                    final VentanaSeleccionUnidad vsu = this;

                    //System.out.println("Memoria total: " + Runtime.getRuntime().totalMemory());
                    //System.out.println("Memoria libre: " + Runtime.getRuntime().freeMemory());

                    ccc.addComponentListener(new java.awt.event.ComponentListener() {

                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                        }

                        public void componentHidden(ComponentEvent arg0) {
                            System.out.println("()()()()()()()()() Se ocultó el SCO");
                            //stopPlayerUnidades();
                            moveToFront();
                            setVisible(true);
                            //Gonzalo 14012010: Ahora el reproductor de la música de fondo lo gestiona la ventana principal
                            //startPlayerUnidades(player, true);
                            startPlayerUnidades();
                            //applet.oCL.panel.remove(jif);
                            frame.oCL.panel.remove(jif);

                            //applet.oCL.panel.getDesktopManager().activateFrame(vsu);
                            frame.oCL.panel.getDesktopManager().activateFrame(vsu);
                            vsu.requestFocusInWindow();

                            //SSS 26102009 aqui el control del next
                            if (atcjx.NEXT) {
                                setFocusedMouse(focused, atcjx.newfocused + offset);
                                atcjx = null;
                                jif.dispose();
                                // System.out.println("Memoria total: " + Runtime.getRuntime().totalMemory());
                                // System.out.println("Memoria libre: " + Runtime.getRuntime().freeMemory());
                                goENTER();
                            } else {
                                ((AppletTemplateComponentsXML) atcjx).p = null;
                                atcjx = null;
                                jif.dispose();
                                System.gc();
                                //System.out.println("Memoria total: " + Runtime.getRuntime().totalMemory());
                                // System.out.println("Memoria libre: " + Runtime.getRuntime().freeMemory());
                            }
                        }

                        public void componentMoved(ComponentEvent arg0) {
                        }

                        public void componentResized(ComponentEvent arg0) {
                        }

                        public void componentShown(ComponentEvent arg0) {
                        }
                    });
                    jif.add(ccc);
                    jif.setBorder(null);
                    jif.setMaximumSize(new java.awt.Dimension(720, 576));
                    jif.setMinimumSize(new java.awt.Dimension(720, 576));
                    jif.setPreferredSize(new java.awt.Dimension(720, 576));
                    BasicInternalFrameUI ui = (BasicInternalFrameUI) jif.getUI();
                    ui.setNorthPane(null);
                    /*try {
                    jif.setSelected(true);
                    } catch (PropertyVetoException e) {
                    e.printStackTrace();
                    }*/
                    jif.setVisible(true);

                    //jif.show();
                    jif.pack();
                    //applet.oCL.panel.add(jif);
                    frame.oCL.panel.add(jif);
                    jif.moveToFront();


                    jif.requestFocusInWindow();
                    //applet.oCL.panel.getDesktopManager().activateFrame(jif);
                    frame.oCL.panel.getDesktopManager().activateFrame(jif);

                    /*try {
                    jif.setSelected(true);
                    } catch (PropertyVetoException e) {
                    e.printStackTrace();
                    }*/
                    //SSS 26102009 para controlar todos los delayed
                    for (int i = 0; i < atcjx.HILOS.size(); i++) {

                        DelayedTime aux = (DelayedTime) atcjx.HILOS.get(i);
                        //if (TMAppletI.OUT) System.out.println("entro para "+aux.name);

                        if (aux != null) {
                            aux.start();
                        }
                    }

                }
            }
        }
    }
}

