/*
 * Clase creada por Mart�n, modificada para su integraci�n con la herramienta.
 *
 *
 */
package com.uvigo.tMaestro.SCOCreator.tool.properties.cellEditors.contentEditors;

import com.uvigo.tMaestro.SCOCreator.tool.MainFrame;
import com.uvigo.tMaestro.SCOCreator.tool.MyFileFilter;
import com.uvigo.tMaestro.SCOCreator.tool.ProgressBar;
import com.uvigo.tMaestro.SCOCreator.tool.Code;
import com.uvigo.tMaestro.SCOCreator.tool.ImageView;
import com.uvigo.tMaestro.SCOCreator.tool.MyOptionPane;


import java.awt.*;
import java.beans.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.media.*;
import javax.xml.bind.*;
import com.uvigo.mhp.mediaPlayer.*;
import com.uvigo.mhp.xml.mediaPlayer.*;

public class MediaPlayerContentEditorPanel extends JPanel implements TableModelListener, ListSelectionListener, ContentEditorPanel {

    private DefaultListModel listModel;
    private DefaultListSelectionModel selectionModel;
    private DefaultTableModel tableModel;
    private boolean moving;
    private Player player;
    private java.util.List resourceList;
    private java.util.List currentTimestampList;
    private JAXBContext jc;
    private ObjectFactory objFactory;
    private MediaList ml;
    //Ruta hasta el directorio de la aplicaci�n
    private String sBase;
    //Ruta desde sBase hasta el directorio en donde est� el fichero xml
    private String sRuta;
    //Nombre del fichero .xml
    private String sFile;
    //Ruta al directorio del componente (dentro del directorio del proyecto). Desde /Projects
    private String sDir;
    //Listado de ficheros a�adidos desde este panel en alg�n momento.
    //Guarda tanto los actuales como los descartados
    private java.util.ArrayList<java.io.File> oAddedFiles = new java.util.ArrayList<java.io.File>();
    /**
     * Referencia al di�logo que va a contener este panel
     */
    private ContentEditorDialog oDialog;
    /**
     * Referencia al tipo de video que se debe agregar
     */
    private int oType;
    /**
     * Array que contiene los tipos de extensiones validos
     */
    private String[] extensiones = new String[5];
    /**
     * Array que contiene los tipos de extensiones validos
     */
    private JPanel panel;

    /**
     * Constructor
     * @param sPathFile Ruta relativa al directorio de la aplicaci�n, del fichero .xml
     * @param oDialog Referencial aldi�logo contenedor de este panel.
     */
    public MediaPlayerContentEditorPanel(String sPathFile, ContentEditorDialog oDialog, int oType) {
        if ((sPathFile == null) || (sPathFile.isEmpty())) {
            sPathFile = "RESOURCES/MediaPlayerCE.xml";//M: inicializaci�n

        }
        this.oDialog = oDialog;
        this.oType = oType;
        this.panel = this;
        extensiones[0] = ".avi";
        extensiones[1] = ".wav";
        extensiones[2] = ".mpeg";
        extensiones[3] = ".mpg";
        extensiones[4] = ".mp2";
        initComponents();
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{},
                new String[]{
                    MainFrame.oMainFrame.getMessage("Title18"),
                    MainFrame.oMainFrame.getMessage("Title19"),
                    MainFrame.oMainFrame.getMessage("Title20")
                }) {

            Class[] types = new Class[]{
                java.lang.Double.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }
        });
        jPanel1.setBorder(new javax.swing.border.TitledBorder(MainFrame.oMainFrame.getMessage("Border4")));
        jButton10.setText(MainFrame.oMainFrame.getMessage("Button7"));
        jButton11.setText(MainFrame.oMainFrame.getMessage("Button6"));
        jButton4.setText(MainFrame.oMainFrame.getMessage("Button8"));
        try {
            jc = JAXBContext.newInstance("com.uvigo.mhp.xml.mediaPlayer");
            objFactory = new ObjectFactory();
            ml = objFactory.createMediaList();
            resourceList = ml.getResource();

            listModel = new DefaultListModel();
            jList1.setModel(listModel);
            tableModel = (DefaultTableModel) jTable1.getModel();
            selectionModel = (DefaultListSelectionModel) jTable1.getSelectionModel();
            TableColumn tc = jTable1.getColumn(MainFrame.oMainFrame.getMessage("Title18"));
            tc.setMaxWidth(100);
            tableModel.addTableModelListener(this);
            jList1.addListSelectionListener(this);
            moving = false;

            //M: ahora..
            sBase = new String(MainFrame.oMainFrame.sDir + "/");
            sDir = new String("TEMP/COMPONENTS/");
            if (sPathFile != null) {
                //Parte de sPathFile que corresponde a ruta (que no es fichero)
                String[] split = sPathFile.split("/");
                sRuta = new String();
                int z = 0;
                for (z = 0; z < split.length - 1; z++) {
                    sRuta = sRuta.concat(split[z] + "/");
                }

                //Parte de sPathFile que corresponde al fichero
                sFile = split[split.length - 1];

                load(new java.io.File(sBase + sPathFile));

            }
        } catch (JAXBException ex) {
            System.out.println(ex.getMessage());
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel13 = new javax.swing.JPanel();
        jButton10 = new javax.swing.JButton();
        jButton11 = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel5 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton13 = new javax.swing.JButton();
        jSplitPane2 = new javax.swing.JSplitPane();
        jPanel6 = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();
        jButton4 = new javax.swing.JButton();
        jPanel8 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();
        jPanel12 = new javax.swing.JPanel();
        jPanel10 = new javax.swing.JPanel();
        jPanel11 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

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

        jPanel13.setLayout(new java.awt.GridLayout(1, 0));

        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });
        jPanel13.add(jButton10);

        jButton11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton11ActionPerformed(evt);
            }
        });
        jPanel13.add(jButton11);

        add(jPanel13, java.awt.BorderLayout.SOUTH);

        jSplitPane1.setDividerLocation(150);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Locators"));
        jPanel1.setLayout(new java.awt.BorderLayout());

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

        jScrollPane1.setViewportView(jList1);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel5.setLayout(new java.awt.GridLayout(0, 1));

        jButton2.setText("<");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel5.add(jButton2);

        jButton3.setText(">");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel5.add(jButton3);

        jPanel2.add(jPanel5, java.awt.BorderLayout.WEST);

        jPanel1.add(jPanel2, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.GridLayout(1, 0));

        jButton1.setText("+");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton1);

        jButton13.setText("-");
        jButton13.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton13ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton13);

        jPanel1.add(jPanel3, java.awt.BorderLayout.SOUTH);

        jSplitPane1.setLeftComponent(jPanel1);

        jSplitPane2.setDividerLocation(250);

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

        jPanel7.setLayout(new java.awt.GridLayout(1, 0));

        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel7.add(jButton4);

        jPanel6.add(jPanel7, java.awt.BorderLayout.SOUTH);

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

        jPanel9.setBackground(new java.awt.Color(0, 0, 0));
        jPanel9.setLayout(new java.awt.GridLayout(0, 1));

        jButton7.setText("PLAY");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });
        jPanel9.add(jButton7);

        jButton8.setText("PAUSE");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });
        jPanel9.add(jButton8);

        jButton9.setText("STOP");
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });
        jPanel9.add(jButton9);

        jPanel8.add(jPanel9, java.awt.BorderLayout.WEST);

        jPanel12.setLayout(new java.awt.BorderLayout());
        jPanel8.add(jPanel12, java.awt.BorderLayout.CENTER);

        jPanel6.add(jPanel8, java.awt.BorderLayout.CENTER);

        jSplitPane2.setRightComponent(jPanel6);

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

        jPanel11.setLayout(new java.awt.GridLayout(1, 0));

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextField1FocusGained(evt);
            }
        });
        jPanel11.add(jTextField1);

        jButton5.setText("+");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel11.add(jButton5);

        jButton6.setText("-");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel11.add(jButton6);

        jPanel10.add(jPanel11, java.awt.BorderLayout.SOUTH);

        jScrollPane2.setAutoscrolls(true);

        jTable1.setCellSelectionEnabled(true);
        jTable1.setEditingColumn(1);
        jTable1.setEditingRow(1);
        jTable1.setOpaque(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable1);

        jPanel10.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jSplitPane2.setLeftComponent(jPanel10);

        jSplitPane1.setRightComponent(jSplitPane2);

        add(jSplitPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents
    private void jButton13ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton13ActionPerformed
    {//GEN-HEADEREND:event_jButton13ActionPerformed
        // hay que eliminar una entrada de la lista de localizadores
        int i = jList1.getSelectedIndex();
        if (i == -1) {
            return;
        }
        listModel.remove(i);
        resourceList.remove(i);

        if (listModel.size() == 0) {
            int j = tableModel.getRowCount();
            for (int k = 0; k < j; k++) {
                tableModel.removeRow(0);
            }
            jPanel12.removeAll();
            return;
        }

        if (i == listModel.size()) {
            jList1.setSelectedIndex(i - 1);
        } else {
            jList1.setSelectedIndex(i);
    }//GEN-LAST:event_jButton13ActionPerformed
    }

    /**
     * El usuario ha pulsado sobre cancelar
     */
    private void jButton11ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton11ActionPerformed
    {//GEN-HEADEREND:event_jButton11ActionPerformed
        oDialog.setAction(ContentEditorDialog.CANCEL, null);
        if (player != null) {
            player.close(); //

        }
        oDialog.dispose();
    }//GEN-LAST:event_jButton11ActionPerformed

    /**
     * Esta funci�n se utiliza para cargar un fichero .xml
     *
     */
    private void load(java.io.File oFile) {
        try {

            if (oFile == null) {
                return;
            }
            Unmarshaller u = jc.createUnmarshaller();
            u.setValidating(true);
            FileInputStream input = new FileInputStream(oFile);
            ml = (MediaList) u.unmarshal(input);
            input.close();
            resourceList = ml.getResource();

            for (int i = 0; i < resourceList.size(); i++) {
                ResourceType rt = (ResourceType) resourceList.get(i);
                listModel.addElement(rt.getLocator());
            }
            if (listModel.size() == 0) {
                return;
            }
            jList1.setSelectedIndex(0);
        } catch (Exception ex) {
            System.out.println(ex);

        }
    }

    /**
     * El usuario ha pulsado sobre OK
     */
    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton10ActionPerformed
    {//GEN-HEADEREND:event_jButton10ActionPerformed
        // Hay que grabar un fichero XML con el contenido creado, en el
        // directorio del proyecto (dentro del directorio de componente).
        // Adem�s hay que copiar los videos al mismo directorio
        final Code oCodigo = new Code() {

            public void run(ProgressBar oBar) {
                try {
                    java.io.File oDirComponent = new java.io.File(sBase + sDir);
                    oDirComponent.mkdir();
                    if (!sFile.contains("(")) {
                        sFile = new String("(" + MainFrame.oMainFrame.getPSheet().getSelectedOption() + ")" +
                                MainFrame.oMainFrame.oGetCapsulaActiva().oGetBean().getName() + ".xml");//M: le damos el nombre del componente

                    }
                    java.io.File oFile = new File(oDirComponent, sFile);
                    System.out.println("oFile: " + oFile);
                    java.util.ArrayList<java.io.File> oFiles = new java.util.ArrayList<java.io.File>();

                    Marshaller m = jc.createMarshaller();
                    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                    oFiles.add(oFile);
                    FileOutputStream output = new FileOutputStream(oFile);
                    m.marshal(ml, output);
                    output.close();

                    /**
                     * Para arreglar el tema de los acentos
                     */
                    /*
                    int auxi = sFile.lastIndexOf(".");
                    String aux = sFile.substring(0, auxi);
                    //File fichero2 = new File(oOptionsDir, sOptionName + "_aux.xml");
                    java.io.File fichero2 = new File(oDirComponent, aux + "_aux.xml");

                    
                    BufferedWriter outi = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fichero2), "UTF8"));
                    Reader ini = new BufferedReader(new InputStreamReader(new FileInputStream(oFile), "UTF8"));
                    int ch;
                    while ((ch = ini.read()) > -1) {
                        outi.write(transformaValor2((char) ch));
                    }
                    ini.close();
                    outi.close();
                       oFile.delete();
                    fichero2.renameTo(oFile);

                    */

                    /*
                     *
                    OutputStream out = new FileOutputStream(fichero2);
                    BufferedInputStream in = new BufferedInputStream(new FileInputStream(oFile));
                    byte[] buf = new byte[1024];

                    String thisLine;
                    int len;
                    int total = 0;

                    while ((len = in.read(buf)) != -1) {
                    // total = total + len;
                    thisLine = transformaValor(buf, len);
                    out.write(thisLine.getBytes(), 0, thisLine.length());//, 0, thisLine.getBytes().length);
                    //System.out.println(thisLine);
                    }
                     */
                    //in.close();
                    //out.close();

                  

                    //////////////////////////////////////////////////////

                    oBar.addValue();

                    //Vemos si los videos indicados ya han sido copiados al directorio del componente
                    //Si no es as� los copiamos
                    for (int i = 0; i < resourceList.size(); i++) {
                        ResourceType rt = (ResourceType) resourceList.get(i);
                        //Copiamos los videos
                        java.io.File oComponentFile = new java.io.File(oDirComponent, rt.getLocator());
                        oFiles.add(oComponentFile);
                        System.out.println("oComponentFile: " + oComponentFile);
                        if (!oComponentFile.exists()) {
                            MainFrame.copyFile(new java.io.File(sBase + sRuta + rt.getLocator()), oComponentFile);
                        }
                        //System.out.println("rt "+rt.getLocator());
                        oBar.addValue();
                    }
                    //  for(int i=0; i<oFiles.size(); i++) System.out.println(oFiles.get(i).getName());
                    MainFrame.oMainFrame.getEditionProperty().putOptionFiles(oFiles, MainFrame.oMainFrame.getPSheet().getSelectedOption());
                    oDialog.setAction(ContentEditorDialog.OK, sDir + sFile);

                } catch (Exception ex) {

                    ex.printStackTrace();
                    System.out.println(ex);
                    oDialog.setAction(ContentEditorDialog.CANCEL, null); // Si se produce alg�n error es como cancelar el proceso

                }
                oDialog.dispose();
                //oBar.dispose();
            }
        };
        if (player != null) {
            player.close();
        }
        new Thread(new Runnable() {

            public void run() {
                new ProgressBar(MainFrame.oMainFrame, 0, resourceList.size() + 1, MainFrame.oMainFrame.getMessage("Title30"), false, oCodigo, 700);
            }
        }).start();

    }//GEN-LAST:event_jButton10ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTable1MouseClicked
    {//GEN-HEADEREND:event_jTable1MouseClicked
        // Cuando se selecciona un sello temporal en la tabla se coloca en ese
        // punto la reproducci�n.
        Point p = new Point(evt.getX(), evt.getY());
        int col = jTable1.columnAtPoint(p);
        int fil = jTable1.rowAtPoint(p);
        if ((col == -1) || (fil == -1)) {
            return;
        }
        double d = ((Double) tableModel.getValueAt(fil, 0)).doubleValue();
        player.stop();
        player.setMediaTime(new Time(d));
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton4ActionPerformed
    {//GEN-HEADEREND:event_jButton4ActionPerformed
        // Hay que a�adir a la lista de sellos temporales uno para el instante actual
        // en la reproducci�n.
        if (player == null) {
            return;
        }
        try {
            Object temp[] = new Object[3];
            temp[0] = new Double(player.getMediaTime().getSeconds());
            temp[1] = new String("");
            temp[2] = new String("");
            newTimestamp(temp, false);
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton9ActionPerformed
    {//GEN-HEADEREND:event_jButton9ActionPerformed
        if (player == null) {
            return;
        }
        player.stop();
        player.setMediaTime(new Time(0));
    }//GEN-LAST:event_jButton9ActionPerformed

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton8ActionPerformed
    {//GEN-HEADEREND:event_jButton8ActionPerformed
        if (player == null) {
            return;
        }
        player.stop();
        player.setMediaTime(player.getMediaTime());
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton7ActionPerformed
    {//GEN-HEADEREND:event_jButton7ActionPerformed
        if (player == null) {
            return;
        }
        player.setMediaTime(player.getMediaTime());
        player.start();
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton5ActionPerformed
    {//GEN-HEADEREND:event_jButton5ActionPerformed
        // hay que a�adir un nuevo sello temporal con el valor indicado
        // en el campo de texto.
        if (player == null) {
            return;
        }
        try {
            Object temp[] = new Object[3];
            temp[0] = new Double(jTextField1.getText());
            temp[1] = new String("");
            temp[2] = new String("");
            newTimestamp(temp, false);
            jTextField1.setText("");
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton6ActionPerformed
    {//GEN-HEADEREND:event_jButton6ActionPerformed
        // hay que borrar el sello temporal seleccionado en la tabla
        int i[] = jTable1.getSelectedRows();
        if (i.length == 0) {
            return;
        }
        for (int j = 0; j < i.length; j++) {
            tableModel.removeRow(i[j] - j);
            currentTimestampList.remove(i[j] - j);
        }

        if (jTable1.getRowCount() == 0) {
            return;
        }
        if (i[0] == jTable1.getRowCount()) {
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(i[0] - 1, i[0] - 1);
        } else {
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(i[0], i[0]);
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jTextField1FocusGained(java.awt.event.FocusEvent evt)//GEN-FIRST:event_jTextField1FocusGained
    {//GEN-HEADEREND:event_jTextField1FocusGained
        jTextField1.setText(""); // para no seguir escribiendo a continuaci�n del
        // valor introducido anteriormente
    }//GEN-LAST:event_jTextField1FocusGained

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jTextField1ActionPerformed
    {//GEN-HEADEREND:event_jTextField1ActionPerformed
        // Cuando se pulsa ENTER en el campo de texto se hace lo mismo que
        // cuando se pulsa el bot�n a�adir
        jButton5ActionPerformed(null);
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // desplazar hacia abajo el localizador para que se reproduzca m�s
        // adelante en la secuencia
        int i = jList1.getSelectedIndex();
        if (i == -1) {
            return;
        }
        if (i == listModel.size() - 1) {
            return;
        }
        moving = true;
        Object aux = listModel.remove(i);
        Object aux2 = resourceList.remove(i);
        listModel.add(i + 1, aux);
        resourceList.add(i + 1, aux2);
        jList1.setSelectedIndex(i + 1);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // desplazar hacia arriba el localizador para que se reproduzca antes
        // en la secuencia
        int i = jList1.getSelectedIndex();
        if (i <= 0) {
            return;
        }
        moving = true;
        Object aux = listModel.remove(i);
        Object aux2 = resourceList.remove(i);
        listModel.add(i - 1, aux);
        resourceList.add(i - 1, aux2);
        jList1.setSelectedIndex(i - 1);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        //hay que a�adir un nuevo localizador a la lista
        javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
        if (oType == 1) {
            MyFileFilter oFilter = new MyFileFilter();
            oFilter = new MyFileFilter();
            oFilter.vAddExtension("m2v");
            oFilter.vSetDescripcion(".m2v");
            chooser.addChoosableFileFilter(oFilter);
            oFilter = new MyFileFilter();
            oFilter.vAddExtension("mp2");
            oFilter.vSetDescripcion(".mp2");
            chooser.addChoosableFileFilter(oFilter);
            oFilter = new MyFileFilter();
            oFilter.vAddExtension("mpg");
            oFilter.vSetDescripcion(".mpg");
            chooser.addChoosableFileFilter(oFilter);
            oFilter = new MyFileFilter();
            oFilter.vAddExtension("m2v");
            oFilter.vAddExtension("mpg");
            oFilter.vAddExtension("mp2");

            oFilter.vSetDescripcion(".m2v .mpg .mp2");
            chooser.addChoosableFileFilter(oFilter);
        } else {
            MyFileFilter oFilter = new MyFileFilter();
            oFilter.vAddExtension("mpeg");
            oFilter.vAddExtension("mpg");
            oFilter.vSetDescripcion(".mpeg");
            chooser.addChoosableFileFilter(oFilter);
            oFilter = new MyFileFilter();
            oFilter.vAddExtension("avi");
            oFilter.vSetDescripcion(".avi");
            chooser.addChoosableFileFilter(oFilter);
            oFilter = new MyFileFilter();
            oFilter.vAddExtension("wav");
            oFilter.vSetDescripcion(".wav");
            chooser.addChoosableFileFilter(oFilter);
            oFilter = new MyFileFilter();
            oFilter.vAddExtension("mp2");
            oFilter.vSetDescripcion(".mp2");
            chooser.addChoosableFileFilter(oFilter);
            oFilter = new MyFileFilter();
            oFilter.vAddExtension("avi");
            oFilter.vAddExtension("mpeg");
            oFilter.vAddExtension("mpg");
            oFilter.vAddExtension("wav");
            oFilter.vAddExtension("mp2");
            oFilter.vSetDescripcion(".mpeg .avi .wav .mp2");
            chooser.addChoosableFileFilter(oFilter);
        }
        chooser.setCurrentDirectory(MainFrame.oMainFrame.getLastDir());
        boolean bExit = false;
        while (!bExit) {
            int option = chooser.showOpenDialog(this);
            if (option == javax.swing.JFileChooser.APPROVE_OPTION) {
                final File file = chooser.getSelectedFile();
                //Comprobamos que no exista ningun fichero con el mismo nombre entre los componentes de la plantilla original
//                if (new java.io.File(MainFrame.oMainFrame.getToolDir(), "templates/" + MainFrame.oMainFrame.getTemplateName() + "/" + file.getName()).exists()) {
//                    MyOptionPane.showMessageDialog(MainFrame.oMainFrame, MainFrame.oMainFrame.getMessage("Error21"), "Error", javax.swing.JOptionPane.ERROR_MESSAGE);
//                    continue;
//                } //M- no hace falta: no habr� componentes en la plantilla
                //Si existe un fichero con el mismo nombre entre los elementos que el usuario ha configurado, lo avisamos
                if (new java.io.File(sBase + sDir, file.getName()).exists()) {
                    int iOption = MyOptionPane.showConfirmDialog(MainFrame.oMainFrame, MainFrame.oMainFrame.getMessage("Question4"), MainFrame.oMainFrame.getMessage("Title2"), javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE);
                    if (iOption == javax.swing.JOptionPane.NO_OPTION) {

                        continue;
                    }

                }
                bExit = true;
                final Code oCode = new Code() {

                    boolean encuentro = false;

                    public void run(ProgressBar oBar) {
                        try {

                            MainFrame.oMainFrame.setLastDir(file.getParentFile());
                            java.io.File oDirComponent = new java.io.File(sBase + sDir);
                            oDirComponent.mkdir();
                            File oVideo2 = null;
                            java.io.File oVideo = new java.io.File(oDirComponent, file.getName());
                            MainFrame.copyFile(file, oVideo);
                            String auxi = file.getAbsolutePath();
                            int indexi = auxi.lastIndexOf(".");
                            auxi = auxi.substring(0, indexi);

                            File filesound = new File(auxi + ".mp2");
                            if (filesound.exists()) {
                                java.io.File oSound = new java.io.File(oDirComponent, filesound.getName());

                                MainFrame.copyFile(filesound, oSound);
                            }
                            //SSSs
                            //System.out.println("la ruta "+file.getAbsolutePath()+" la otra "+oVideo.getAbsolutePath());
                            oAddedFiles.add(oVideo);
                            //SSSS

                            listModel.addElement(file.getName());

                            ResourceType rt = objFactory.createResourceType();
                            rt.setLocator(file.getName());
                            resourceList.add(rt);


                            if (oType == 1) {
                                // System.out.println("entro a copiar el otro");
                                String aux = file.getAbsolutePath();
                                int index = aux.lastIndexOf(".");
                                aux = aux.substring(0, index);
                                encuentro = false;
                                for (int i = 0; i < 4; i++) {
                                    File f = new File(aux + extensiones[i]);

                                    //System.out.println(f.getAbsolutePath());
                                    if (f.exists()) {
                                        encuentro = true;
                                        //System.out.println("lo encuentro "+oDirComponent +" "+f.getName());
                                        oVideo2 = new java.io.File(oDirComponent, f.getName());
                                        // System.out.println(oVideo.getAbsolutePath());
                                        MainFrame.copyFile(f, oVideo2);
                                        break;
                                        //oURL = new java.net.URL("file:/" + dir + File.separator + extension + extensiones[i]);
                                        //System.out.println(oURL.getPath());
                                    }
                                }
                                creaXML xml = new creaXML(oVideo.getAbsolutePath());


                                //aqui el main que genera el archivo
                                //en oVideo
                            }
                        } catch (Exception ex) {
                            System.out.println("aqyu?");
                            System.out.println(ex);
                        }
                        oBar.dispose();

                        if (oType == 1) {
                            if (!encuentro) {
                                // System.out.println("no encuentro");
                                String message = "Para poder previsualizar el video y añadir sellos temporales, el video se debe encontrar" +
                                        " \ntambién en uno de los siguientes formatos válidos:" +
                                        " \n                        .mpg .mpeg .avi";
                                MyOptionPane.showMessageDialog(panel, message, "Aviso", javax.swing.JOptionPane.WARNING_MESSAGE);//oIdioma.get("Question2"), oIdioma.get("Title2"), javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE);
                                //mensaje de advertencia

                            }
                        }
                    }
                };
                new Thread(new Runnable() {

                    public void run() {
                        new ProgressBar(MainFrame.oMainFrame, 0, 0, MainFrame.oMainFrame.getMessage("Title29"), true, oCode, 300);
                    }
                }).start();
            } else {
                bExit = true;
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    public void tableChanged(TableModelEvent e) {
        // hay que reordenar los sellos temporales en la tabla.
        if (e.getType() == TableModelEvent.UPDATE) {
            int j = e.getFirstRow();
            if (e.getColumn() == 0) {
                // si se ha modificado el valor del sello temporal, hay que
                // reordenar la tabla
                double d = ((Double) tableModel.getValueAt(j, 0)).doubleValue();
                String s1 = (String) tableModel.getValueAt(j, 1);
                String s2 = (String) tableModel.getValueAt(j, 2);
                if (jTable1.getRowCount() == 1) {
                    return;
                }
                Object temp[] = new Object[3];
                temp[0] = new Double(d);
                temp[1] = s1;
                temp[2] = s2;

                tableModel.removeRow(j);
                currentTimestampList.remove(j);
                for (int i = 0; i < jTable1.getRowCount(); i++) {
                    double d1 = ((Double) temp[0]).doubleValue();
                    double d2 = ((Double) tableModel.getValueAt(i, 0)).doubleValue();
                    if (d1 == d2) {
                        // Se impone una nueva cadena para un sello temporal ya existente
                        tableModel.setValueAt(s1, i, 1);
                        tableModel.setValueAt(s2, i, 2);
                        TimestampType ts = (TimestampType) currentTimestampList.get(i);
                        ts.setContextName(s1);
                        ts.setComment(s2);
                        return;
                    }
                    if (d1 < d2) {
                        tableModel.insertRow(i, temp);
                        try {
                            TimestampType ts = objFactory.createTimestampType();
                            ts.setContextName(s1);
                            ts.setTimestamp(d);
                            ts.setComment(s2);
                            currentTimestampList.add(i, ts);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                        jTable1.setColumnSelectionInterval(0, 0);
                        jTable1.setRowSelectionInterval(i, i);
                        return;
                    }
                }
                tableModel.addRow(temp);

                try {
                    TimestampType ts = objFactory.createTimestampType();
                    ts.setContextName(s1);
                    ts.setTimestamp(d);
                    ts.setComment(s2);
                    currentTimestampList.add(ts);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                jTable1.setColumnSelectionInterval(0, 0);
                jTable1.setRowSelectionInterval(jTable1.getRowCount() - 1, jTable1.getRowCount() - 1);
            } else {
                // si se ha modificado la cadena, hay que actualizarla en el
                // vector timestamps
                String s1 = (String) tableModel.getValueAt(j, 1);
                String s2 = (String) tableModel.getValueAt(j, 2);
                TimestampType ts = (TimestampType) currentTimestampList.get(j);
                ts.setContextName(s1);
                ts.setComment(s2);
            }
        }
    }

    public void valueChanged(ListSelectionEvent evt) {
        // al cambiar el localizador seleccionado, hay que cambiar el medio que
        // se reproduce y actualizar la tabla de sellos temporales.
        if (evt.getValueIsAdjusting()) {
            return;
        }
        if (jList1.getSelectedIndex() == -1) {
            return;
        }
        if (moving) {
            moving = false;
            return;
        }

        jPanel12.removeAll();
        ResourceType rt = (ResourceType) resourceList.get(jList1.getSelectedIndex());
        currentTimestampList = rt.getTimestamp();
        reloadTable();
        try {
            if (player != null) {
                player.close(); //Necesario cerrarlo por si el fichero que reproduce debe ser borrado!!
                //O el video se encuentra en el directorio del componente o se encuentra
                //en el mismo directorio que el fichero .xml

            }
            //SSSS
            java.net.URL oURL = null;
            String extension = "";
            extension = rt.getLocator();
            int index = extension.lastIndexOf(".");
            String nueva = extension.substring(index + 1, extension.length());

            if (nueva.compareTo("m2v") == 0) {
                String aux = extension.substring(0, index);

                //Buscar cual es la ruta origen
                for (int i = 0; i < 4; i++) {
                    File f = new File(sBase + sDir + aux + extensiones[i]);

                    if (f.exists()) {
                        //System.out.println("lo encuentro");
                        oURL = new java.net.URL("file:/" + sBase + sDir + aux + extensiones[i]);
                        //System.out.println(oURL.getPath());
                    }
                }
            } else {
                //System.out.println("entro por el else");

                oURL = new java.net.URL("file:/" + sBase + sDir + extension);
            }
            //java.net.URL oURL = new java.net.URL("file:/" + sBase + sDir + rt.getLocator());
            //Hacemos esto en lugar de verificar si el fichero existe (oFile.exists())
            //porque por alg�n motivo que desconozco la funci�n exists en algunas ocasiones
            //existiendo el fichero devuelve un false. As� nos curamos en salud.
            try {
                player = Manager.createRealizedPlayer(new MediaLocator(oURL));
            } //Ruta relativa
            catch (Exception oE) {
                player = Manager.createRealizedPlayer(new MediaLocator("file:/" + sBase + sRuta + rt.getLocator())); //Ruta relativa

            }
            jPanel12.add(player.getVisualComponent(), "Center");
            jPanel12.add(new MediaScrollBar(player), "South");
            jPanel12.validate();
            doLayout();
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return;
    }

    private void reloadTable() {
        // Al cambiar el medio, hay que actualizar la tabla de sellos temporales.
        int j = tableModel.getRowCount();
        for (int i = 0; i < j; i++) {
            tableModel.removeRow(0);
        }
        Object temp[] = new Object[3];
        for (int i = 0; i < currentTimestampList.size(); i++) {
            temp[0] = new Double(((TimestampType) currentTimestampList.get(i)).getTimestamp());
            temp[1] = ((TimestampType) currentTimestampList.get(i)).getContextName();
            temp[2] = ((TimestampType) currentTimestampList.get(i)).getComment();
            newTimestamp(temp, true);
        }

        selectionModel.clearSelection();
    }

    private void newTimestamp(Object temp[], boolean reloading) {
        // reloading es true cuando se est� recargando la tabla de sellos, y
        // false cuando se a�ade uno nuevo.

        try {
            if (jTable1.getRowCount() == 0) {
                tableModel.insertRow(0, temp);
                jTable1.setColumnSelectionInterval(0, 0);
                jTable1.setRowSelectionInterval(0, 0);

                if (!reloading) {
                    TimestampType ts = objFactory.createTimestampType();
                    ts.setTimestamp(((Double) temp[0]).doubleValue());
                    ts.setContextName((String) temp[1]);
                    ts.setComment((String) temp[2]);
                    currentTimestampList.add(ts);
                }
                return;
            }
            for (int i = 0; i < jTable1.getRowCount(); i++) {
                double d1 = ((Double) temp[0]).doubleValue();
                double d2 = ((Double) tableModel.getValueAt(i, 0)).doubleValue();
                if (d1 == d2) {
                    return;
                }
                if (d1 < d2) {
                    tableModel.insertRow(i, temp);
                    jTable1.setColumnSelectionInterval(0, 0);
                    jTable1.setRowSelectionInterval(i, i);

                    if (!reloading) {
                        TimestampType ts = objFactory.createTimestampType();
                        ts.setTimestamp(d1);
                        ts.setContextName((String) temp[1]);
                        ts.setComment((String) temp[2]);
                        currentTimestampList.add(i, ts);
                    }
                    return;
                }
            }
            tableModel.addRow(temp);
            jTable1.setColumnSelectionInterval(0, 0);
            jTable1.setRowSelectionInterval(jTable1.getRowCount() - 1, jTable1.getRowCount() - 1);

            if (!reloading) {
                TimestampType ts = objFactory.createTimestampType();
                ts.setTimestamp(((Double) temp[0]).doubleValue());
                ts.setContextName((String) temp[1]);
                ts.setComment((String) temp[2]);
                currentTimestampList.add(ts);
            }
        } catch (JAXBException ex) {
            ex.printStackTrace();
        }
    }

    public Dimension getPreferredSize() {
        return new Dimension(600, 400);
    }

    /**
     * Devuelve los ficheros a�adidos
     */
    public java.util.ArrayList<java.io.File> getFiles() {
        return oAddedFiles;
    }

    private String transformaValor(byte[] cadena, int longitud) {

        String sValue = new String(cadena, 0, longitud);

        String a[] = {"ñ", "á", "é", "í", "ó",
            "ú", "Ñ", "Á", "É", "Í", "Ó", "Ú", "¿", "¡"};
        //ñ=209
        String b[] = {"&#241;", "&#225;", "&#233;", "&#237;", "&#243;", "&#250;",
            "&#209;", "&#193;", "&#201;", "&#205;", "&#211;", "&#218;", "&#191;", "&#161;"};

        for (int i = 0; i < a.length; i++) {

            sValue = sValue.replaceAll((String) a[i], (String) b[i]);

        }
        System.out.println(sValue);
        return sValue;

    }

    private String transformaValor2(char cadena) {
        String svalue = String.valueOf(cadena);
        char a[] = {'ñ', 'á', 'é', 'í', 'ó', 'ú', 'Ñ', 'Á', 'É', 'Í', 'Ó', 'Ú', '¿', '¡'};
        //ñ=209
        String b[] = {"&#241;", "&#225;", "&#233;", "&#237;", "&#243;", "&#250;",
            "&#209;", "&#193;", "&#201;", "&#205;", "&#211;", "&#218;", "&#191;", "&#161;"};

        for (int i = 0; i < a.length; i++) {
            if (a[i] == cadena) {
                svalue = b[i];
            }
        }
//System.out.print(svalue);
        return svalue;

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton13;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
