/**
  *     Aplicación eFI 2.0.
  *  
  *     08.Abril.2008  (c) Terasoft Consultores.
  *     Autor: Cecilio Cano Calonge.
  *
 **/
var gridResultados;     //-- Grid de listado de resultados.

var texto;        

var familia ;        
var genero ;        
var provinciaSeleccionada ;        

var planta ;
var raiz ;
var cepa ;
var tallos_y_ramas ;
var espinas ;
var hojas ;
var flor ;
var inflorescencia ;
var receptaculo ;
var caliz ;
var corola ;
var gineceo ;
var androceo ;
var nectarios ;
var fruto ;
var semilla ;
var vernaculos ;
var habitat ;

var agruparCampos ;

var raizComparador; 

var proxyBusqueda; 
var readerBusqueda;
var storeBusqueda;

var treeComparator; 

var panelPestanias ;
var pestaniaResultadoBusqueda;
var pestaniaDicotomias;
var pestaniaComparador;

var fichasTaxones = new Array();
var contadorFichasTaxones = 0;


/**
 *  A really generic exception handler for to handle runtime/boundary 
 *  JSON-RPC exceptions.
 * 
 *  Return true if the exception was handled, and false if there was no 
 *  exception.
 *  @param p 
 *  @param o 
 *  @param e a possible exception.
 */
function excepcion(p,o,e){
    if (!e){
        return false;

    }else if( e.code == "591"  ){
        Ext.Msg.alert('Sesión caducada.', 'Demasiado tiempo sin utilizar la aplicación. Su sesión ha terminado. <br>' +
                      'Recargue la página para volver a utilizar la aplicación' );
    
    }else{
        Ext.Msg.alert('Error al conectar con el servidor',e.code + '<BR>' + e.msg);
    }
    return true;
}










Ext.onReady(function(){


    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    /**     Carga de los datos remotos desde la clase
     *      czy.flora.jabsorb.Formularios, registrada aquí
     *      como jsonrpc.datosForm, según se indica al inicio 
     *      de index.jsp
    */
    
    var jsonrpc = new JSONRpcClient("JSON-RPC");


    //--    Proxy para las familias.
    var proxyFamilias = new Ext.data.JsonRpcProxy( jsonrpc.datosForm.getTodasFamilias );
    proxyFamilias.on( "loadexception", function(p,o,e){ excepcion(p,o,e); });


    var familiaSeleccionada = "";


    //--    Proxy para géneros de la familia.
    var proxyGeneros = new Ext.data.JsonRpcProxy( function (cb, query) { 
        jsonrpc.datosForm.getGenerosDeLaFamilia (cb, query, familiaSeleccionada );
    });
    proxyGeneros.on( "loadexception", function(p,o,e){ excepcion(p,o,e); });


    //--    Proxy para las provincias.
    var proxyProvincias = new Ext.data.JsonRpcProxy( jsonrpc.datosForm.getProvincias );
    proxyProvincias.on( "loadexception", function(p,o,e){ excepcion(p,o,e); });



    
    
    //--    Store para todas las familias
    var storeTodasFamilias = new Ext.data.SimpleStore({
        fields : [ 'nombreFamilia' ], 
        proxy: proxyFamilias,
        reader: new Ext.data.JsonReader( 
                        { root: 'familias' }, 
                        [ {name: 'nombreFamilia'} ]
                )
    });



    //--    Store para los géneros
    var storeGeneros = new Ext.data.SimpleStore({
        fields : [ 'nombreGenero' ], 
        proxy: proxyGeneros,
        reader: new Ext.data.JsonReader( 
            { root: 'generos' }, 
            [ {name: 'nombreGenero'} ]
        )
    });


    //--    Store para las provincias
    var storeProvincias = new Ext.data.SimpleStore({
        fields : [ 'abrevProv', 'provincia' ], 
        proxy: proxyProvincias,
        reader: new Ext.data.JsonReader( 
            { root: 'provincias' }, 
            [ {name: 'abrevProv'}, {name: 'provincia'} ]
        )
    });












    /**
     *           VIEWPORT PRINCIPAL DE LA APLICACIÓN.
     *.................................................................. */
    new Ext.Viewport({
        
        layout:'border',

        items:[
            new Ext.BoxComponent({ // raw
                // ...........................................
                // 
                //             PANEL NORTE
                //............................................  
                region:'north',
                el: 'north',
                height:82
                        
            }),{
                // ...........................................
                // 
                //             PANEL OESTE
                //............................................  
                region:'west',
                id:'west-panel',
                title:determinacionEspecies_RTL,
                split:true,
                width: 350,
                minSize: 175,
                maxSize: 400,
                collapsible: true,
                margins:'0 0 0 5',
                layout:'accordion',
                layoutConfig:{ animate:true },
                items: [
                    // ............................................
                    // 
                    //      PANEL DE BÚSQUEDA
                    // ............................................  
                    new Ext.FormPanel({
                        id:'panelBusqueda',
                        labelWidth: 75, 
                        title: busqueda_RTL,
                        iconCls:'iconBusqueda',
                        bodyStyle:'padding:5px 5px 0',
                        width: 350,
                        defaultType: 'textfield',
                        items: [
                                
                            //
                            //      COMBO DE SELECCIÓN DE FAMILIA
                            // ............................................ 
                            new Ext.form.ComboBox({
                                fieldLabel: familia_RTL,
                                id: 'familia',
                                name: 'familia',
                                loadingText : cargandoFamilias_RTL + '...',
                                emptyText: '['+ restriccionFamilia_RTL + ']',
                                selectOnFocus:true,
                                store: storeTodasFamilias,
                                displayField: 'nombreFamilia',
                                minChars : 1,
                                triggerAction:'all',
                                      
                                listeners:{ 
                                    select:{ //-- Al seleccionar una familia.
                                        fn:function( comboFamilia ) {
                                            familiaSeleccionada = comboFamilia.getValue();

                                            var comboGenero = Ext.getCmp('genero');        
                                            comboGenero.reset();
                                            storeGeneros.reload();
                                        }
                                    }
                                }
                                        

                            }), new Ext.form.ComboBox({
                                //
                                //      COMBO DE SELECCIÓN DE GÉNERO
                                // ............................................  
                                fieldLabel: genero_RTL,
                                id: 'genero',
                                name: 'genero',
                                loadingText : cargandoGeneros_RTL + '...',
                                emptyText:'['+ restriccionGenero_RTL + ']',
                                selectOnFocus:true,
                                store: storeGeneros,
                                lazyInit:false,
                                displayField: 'nombreGenero',
                                minChars : 1,
                                triggerAction:'all'

                            }), new Ext.form.ComboBox({
                                //
                                //      COMBO DE SELECCIÓN DE PROVINCIA
                                // ............................................  
                                fieldLabel: provincia_RTL,
                                id: 'provincia',
                                name: 'provincia',
                                loadingText : cargandoProvincias_RTL + '...',
                                emptyText:'[' + restriccionProvincias_RTL + ']',
                                selectOnFocus:true,
                                store: storeProvincias,
                                triggerAction:'all',
                                minChars : 1,
                                displayField: 'provincia'
                                //-- No funciona correctamente. Explicado en el combo de "localización directa"
                                // valueField: 'abrevProv'
                            }),{     

                                xtype:'tabpanel',
                                plain:true,
                                id: "tabBusqueda",
                                activeTab: 0,
                                height:425,
                                defaults:{bodyStyle:'padding:10px'},
                                items:[{
                                    title:busquedaLibre_RTL,
                                    id: "textoLibre",
                                    layout:'form',
                                    defaultType: 'textfield',
                                    items: [{
                                        fieldLabel: textoBuscar_RTL,
                                        id: 'texto',
                                        name: 'texto',
                                        enableKeyEvents : true,
                                        
                                        listeners: {
                                            render: function( c ) {
                                                c.getEl().on( 'keyup', function(e) {
                                                     if( e.getKey() == 13 ){
                                                        realizaBusqueda() ;
                                                     }
                                                })
                                            }
                                        }
                                        
                                    }]
                                },{
                                    title:busquedaCampos_RTL,
                                    id: "porCampos",
                                    layout:'form',
                                    autoScroll : true,
                                    defaults: {width: 150},
                                    defaultType: 'textfield',
                                    items: [


                                        //
                                        //      CAMPOS PARA BUSQUEDA
                                        //......................................  
                                        {
                                            fieldLabel: agruparCampos_RTL,
                                            id: 'agruparCampos',
                                            name: 'agruparCampos',
                                            xtype: "checkbox",
                                            width: 15,

                                            listeners:{ 
                                                check : {
                                                    fn:function( checkbox, checked ) {
                                                        agrupaOdesagrupaCampos( checked ) ;
                                                    }                                                    
                                                } 
                                            }                                                    

                                        },{
                                            fieldLabel: planta_RTL,
                                            name: 'planta',
                                            id: 'planta',
                                            cls:'cabezaAgrupados',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }

                                        },{
                                            fieldLabel: raiz_RTL,
                                            name: 'raiz',
                                            id: 'raiz',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: cepa_RTL,
                                            name: 'cepa',
                                            id: 'cepa',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: tallosYramas_RTL,
                                            name: 'tallos_y_ramas',
                                            id: 'tallos_y_ramas',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: espinas_RTL,
                                            name: 'espinas',
                                            id: 'espinas',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: hojas_RTL ,
                                            name: 'hojas',
                                            id: 'hojas',
                                            cls:'cabezaAgrupados',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: flor_RTL,
                                            name: 'flor',
                                            id: 'flor',
                                            cls:'cabezaAgrupados',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: inflorescencia_RTL,
                                            name: 'inflorescencia',
                                            id: 'inflorescencia',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: receptaculo_RTL,
                                            name: 'receptaculo',
                                            id: 'receptaculo',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: caliz_RTL,
                                            name: 'caliz',
                                            id: 'caliz',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: corola_RTL ,
                                            name: 'corola',
                                            id: 'corola',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: gineceo_RTL,
                                            name: 'gineceo',
                                            id: 'gineceo',
                                            cls:'cabezaAgrupados',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: androceo_RTL,
                                            name: 'androceo',
                                            id: 'androceo',
                                            cls:'cabezaAgrupados',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: nectarios_RTL,
                                            name: 'nectarios',
                                            id: 'nectarios',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: fruto_RTL,
                                            name: 'fruto',
                                            id: 'fruto',
                                            cls:'cabezaAgrupados',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: semilla_RTL,
                                            name: 'semilla',
                                            id: 'semilla',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: vernaculos_RTL,
                                            name: 'vernaculos',
                                            id: 'vernaculos',
                                            cls:'cabezaAgrupados',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        },{
                                            fieldLabel: habitat_RTL,
                                            name: 'habitat',
                                            id: 'habitat',
                                            cls:'cabezaAgrupados',
                                            listeners: {
                                                render: function( c ) {
                                                    c.getEl().on( 'keyup', function(e) {
                                                        if( e.getKey() == 13 ){
                                                            realizaBusqueda() ;
                                                        }
                                                    })
                                                }
                                            }
                                        }
                                    ]
                                }]
                            }],
                        buttons: [{ 
                            text    : buscar_RTL, 
                            handler : function(){ realizaBusqueda() ; }
                        }],buttonAlign : 'right'
                        
                        
                     }),{
                         // ............................................
                         // 
                         //       PANEL DE CLAVES DICOTOMICAS
                         //............................................  
                         title:clavesDicotomicas_RTL,
                         border:false,
                         iconCls:'iconBusqueda',
                         bodyStyle:'padding:50px 25px 0',
                         listeners:{ 
                            expand:{ //-- Al seleccionar una familia.
                              fn:function( panel ) {
                                  cargaClaveDitocomica( null );
                              }
                            }
                         }

                         
                     },new Ext.FormPanel({
                         // ............................................
                         // 
                         //       PANEL DE ACCESO DIRECTO A ESPECIE
                         // ............................................  
                         labelWidth: 75, 
                         width: 350,
                         id:'LocalizacionDirecta',
                         title: ira_RTL,
                         iconCls:'iconBusqueda',
                         bodyStyle:'padding:50px 25px 0',
                         defaultType: 'textfield',
                         items: [

                            //
                            //      COMBO DE SELECCIÓN DE FAMILIA
                            // ............................................ 
                            new Ext.form.ComboBox({
                                fieldLabel: familia_RTL,
                                loadingText : cargandoFamilias_RTL + '...',
                                emptyText: '['+ restriccionFamilia_RTL + ']',
                                id: 'familiaDirecta',
                                name: 'familiaDirecta',
                                selectOnFocus:true,
                                store: storeTodasFamilias,
                                displayField: 'nombreFamilia',
                                triggerAction:'all',
                                minChars : 1,
                                minListWidth : 150,
                                listeners:{ 
                                    select:{ //-- Al seleccionar una familia.
                                        fn:function( comboFamilia ) {
                                            familiaSeleccionada = comboFamilia.getValue();

                                            var comboGenero = Ext.getCmp( 'generoDirecta' );        
                                            comboGenero.reset();
                                            storeGeneros.reload();
                                            
                                            //-- Realiza la búsqueda con la familia y provincia marcadas
                                            localizacionDirecta();
                                        }
                                    },
                                    change:{ //-- Al salir seleccionar una familia (por si no se selecciona ninguna)
                                        fn:function( comboFamilia ) {
                                            familiaSeleccionada = comboFamilia.getValue();

                                            var comboGenero = Ext.getCmp( 'generoDirecta' );        
                                            comboGenero.reset();
                                            storeGeneros.reload();
                                            
                                            //-- Realiza la búsqueda con la familia y provincia marcadas
                                            localizacionDirecta();
                                        }
                                    }
                                }

                            }), new Ext.form.ComboBox({
                                //
                                //      COMBO DE SELECCIÓN DE GÉNERO
                                // ............................................  
                                
                                fieldLabel: genero_RTL,
                                loadingText : cargandoGeneros_RTL + '...',
                                emptyText:'['+ restriccionGenero_RTL + ']',
                                id: 'generoDirecta',
                                name: 'generoDirecta',
                                selectOnFocus:true,
                                store: storeGeneros,
                                lazyInit:false,
                                displayField: 'nombreGenero',
                                triggerAction:'all',
                                minChars : 1,
                                minListWidth : 150,
                                
                                listeners:{ 
                                    select:{ //-- Al seleccionar un género.
                                        fn:function( comboGenero ) {
                                            //-- Realiza la búsqueda con la familia, género y provincia marcadas.
                                            localizacionDirecta();
                                        }
                                    },
                                    change:{ //-- Al salir de seleccionar un género (por si no se selecciona ninguno).
                                        fn:function( comboGenero ) {
                                            //-- Realiza la búsqueda con la familia, género y provincia marcadas.
                                            localizacionDirecta();
                                        }
                                    }

                                }
                                
                                

                            }), new Ext.form.ComboBox({
                                //
                                //      COMBO DE SELECCIÓN DE PROVINCIA
                                // ............................................  
                                fieldLabel: provincia_RTL,
                                loadingText : cargandoProvincias_RTL + '...',
                                emptyText:'[' + restriccionProvincias_RTL + ']',
                                id: 'provinciaDirecta',
                                name: 'provinciaDirecta',
                                selectOnFocus:true,
                                store: storeProvincias,
                                minChars : 1,
                                triggerAction:'all',
                                displayField: 'provincia',
                                //-- Si pongo esto, para que valor que se pase, sea el de la provinca abreviada
                                //-- no se limpia el valor cuando no hay ningún elemento seleccionado. ¿Bug ExtJS?
                                // valueField: 'abrevProv',
                                minListWidth : 150,
                                
                                listeners:{ 
                                    select:{ //-- Al Seleccionar una provincia
                                        fn:function( comboProvincia ) {
                                            //-- Realiza la búsqueda con la familia, género y provincia marcadas.
                                            localizacionDirecta();
                                        }
                                    },
                                    blur:{ //-- Al salir de seleccionar una provincia (por si no se selecciona ninguna)
                                        fn:function( comboProvincia ) {
                                            //-- Realiza la búsqueda con la familia, género y provincia marcadas.
                                            localizacionDirecta();
                                        }
                                    }

                                }
                                
                            })     
                         ] 
                     })
                ]
                        
            }, panelPestanias = new Ext.TabPanel({
                 //............................................
                 // 
                 //              PANEL CENTRAL
                 //............................................  
               	 region:'center',
                 deferredRender:false,
                 activeTab:0,
                 enableTabScroll:true,
                 defaults: {autoScroll:true},
                 layoutOnTabChange: true
                
            })
        ]
    });

    
    
    
    

    // =========================================================================
    //                         RESULTADOS DE LA BÚSQUEDA 
    // =========================================================================

    
    
    //
    //      Proxy para el grid de los resultados de la búsqueda (ESPECIES).
    //
    proxyBusqueda = 
        new Ext.data.JsonRpcProxy( 
            function (cb, query) { 
                jsonrpc.busqueda.getResultadoBusqueda(
                      cb, query, texto, familia, genero, provinciaSeleccionada, 
                      planta, raiz, cepa, tallos_y_ramas, espinas,
                      hojas, flor, inflorescencia, receptaculo, 
                      caliz, corola, gineceo, androceo, nectarios,
                      fruto, semilla, vernaculos, habitat, tipoBusqueda, 
                      agruparCampos );
            }
        );
          
    proxyBusqueda.on( "loadexception", function(p,o,e){ excepcion(p,o,e); });



    
    //
    //      Reader para los resultados de la búsqueda (Especies).
    //
    readerBusqueda = new Ext.data.JsonReader({
        root: 'registros',
        totalProperty: 'totalResultados',
        id: 'idfb'
    },[
         { name: "idfb",       mapping : "idfb" }, 
         { name: "nombre",     mapping : "nombre" }, 
         { name: "porcentaje", mapping : "porcentaje" }
    ]);




    //
    //      Store para los resultados de la búsqueda (Especies).
    //
    storeBusqueda = new Ext.data.Store({
        proxy: proxyBusqueda,
        reader: readerBusqueda,
        remoteSort: true 
    });


    
    //  ........................................................................
    //
    //         GRID DE RESULTADOS DE ESPECIES
    //  ........................................................................
    gridResultados = new Ext.grid.GridPanel({
 
        el:'resultadosEspecies',
        //--    define the colomns to show
        cm: new Ext.grid.ColumnModel([
            { id:'nombre', header:especie_RTL, width:250, sortable:false, dataIndex:'nombre' },
                     
            { id:'porcentaje',
              header: importancia_RTL,
              dataIndex: 'porcentaje',
              width:200,
              renderer: function( value, cell ){ 
                            return '<div style="border:solid 1px; border-color:blue; '+
                                        'background-color:green; width:'+ value*2 +
                                        'px; height:5px" title="'+ value +
                                        '% de importancia"></div><br>';
              }
           }
        ]),
                        
        //--    make the columns fit
        viewConfig: { forceFit:true },
 
        //--    Zebra stripes
        stripeRows:true,
        title:resultadoBusqueda_RTL,
        iconCls:'icon-grid',
        width:550,
        height:300,
        enableDrag: true,
        animate:true,
        autoExpandColumn: 'nombre',
        store: storeBusqueda, 

        bbar: new Ext.PagingToolbar({
                pageSize: 15,
                displayMsg: displayMsg_RTL,
                emptyMsg: emptyMsg_RTL,
                beforePageText: pagina_RTL,
                afterPageText: de_RTL + " {0}",
                store: storeBusqueda,
                displayInfo: true,
                items:[
                    '-', 
                    {
                      text: enviaComparador_RTL,
                      handler : function(){ seleccAlComparador() ; }
                    }
                ]
        })
    });

    gridResultados.setVisible( false ) ;
    gridResultados.render();
    gridResultados.getSelectionModel().selectFirstRow();


    //--    Listeners para la lista de resultados.
    gridResultados.addListener({
        'cellclick':{
                //--    Al pulsar un click, se expande el comparador de especies.
		fn: function( grid, rowIndex, columnIndex, event ){
                        treeComparator.expand();
		}
		,scope:this
	},
         
        'celldblclick':{
                //--    Al hacer un doble click, se abre la ficha de esta especie.
		fn: function( grid ){
                     
                     cargaFichaTaxon( grid.getSelectionModel().getSelected().id, 
                                 grid.getSelectionModel().getSelected().data.nombre ) ;
		}
		,scope:this
	}
    });


        
        
   /**
    *     Envía las filas seleccionadas al panel comparador de especies. 
    */
    function seleccAlComparador() {
        aniadeComparador( gridResultados.selModel.selections.items ) ;
    }//_________________________________________________________________________   
        
        
    
    
    
    /**
     *    Añade al panel comparador los registros recibidos como argumento.
     */
    function aniadeComparador( registros ) {
   
        var aniadidos = new Array();
        var contador = 0;

        //--    Primero, se miran si ya están añadidos, para no duplicarlos.
        for (var i=0; i<registros.length; i++) {
            var siEsta = false ;    

                for( var j=0; j<raizComparador.childNodes.length; j++){
                    if( raizComparador.childNodes[j].id == registros[i].data['idfb'] ){
                        siEsta = true ;
                        break;
                    }
                }        

             //--    Si no está ya añadido, se añade.
             if( siEsta == false ){

                if( (raizComparador.childNodes.length + contador) >= 15 ){
                      Ext.Msg.alert( demasiadasEspecies_RTL, noMasDeQuince_RTL );
                      break ;
                }   

                aniadidos[ contador++ ] = new Ext.tree.TreeNode({
                                                id: registros[i].data['idfb'],
                                                text: registros[i].data['nombre'],
                                                leaf: true,
                                                // cls: 'file',
                                                isTarget: true });
             }
        }

        //--    Ahora, se añaden todos en un lote.    
        if( aniadidos.length > 0 ){
            raizComparador.appendChild(aniadidos) ;
        }

    }//_________________________________________________________________________   
        
        
        
        
        
    //  ..........................................
    //
    //       PANEL DE COMPARACIÓN DE ESPECIES 
    //  ..........................................
    treeComparator = new Ext.tree.TreePanel({
        el:'panelComparador',
        autoScroll:true,       
        collapsible: true,
        animCollapse: true,
        frame: false,
        title: comparadorEspecies_RTL,
        enableDrop: true,
        animate:true,
        containerScroll: false,
        bbar: [
                { 
                    text    : quitarEspecies_RTL,
                    tooltip : quitarEspeciesTip_RTL ,
                    handler : function(){ quitaSeleccionadas() ; }
                },{ 
                    text    : comparar_RTL, 
                    tooltip : compararTip_RTL ,
                    handler : function(){ Comparar() ; }
                }
        ],

        dropConfig: {
            ddGroup: "GridDD",
            dropAllowed: true,
            
            //--    Para añadir las especies arrastradas al Tree del comparador.
            notifyDrop: function(source, e, data) {
                aniadeComparador( data.selections ) ;
                
                // These two lines should be called in onNodeOut but for some reason the
                // event is not being called.
                this.cancelExpand();                
                this.removeDropIndicators(this.lastOverNode);     
                return true;
            
            }, onNodeOver : function(n, dd, e, data){
                // slightly modified from TreeDropZone
                // this just highlights the node currently hovering over.
                // without regard to leaf or not.  See original TreeDropZone
                // version to change to leaf only.
                var pt = this.getDropPoint(e, n, dd);
                var node = n.node;

                // auto node expand check
                if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
                    this.queueExpand(node);
                }else if(pt != "append"){
                    this.cancelExpand();
                }

                // set the insert point style on the target node
                var returnCls = this.dropNotAllowed;
                if(this.isValidDropPoint(n, pt, dd, e, data)){
                   if(pt){
                       var el = n.ddel;
                       var cls;
                       returnCls = "x-tree-drop-ok-append";
                       cls = "x-tree-drag-append";
                       if(this.lastInsertClass != cls){
                           Ext.fly(el).replaceClass(this.lastInsertClass, cls);
                           this.lastInsertClass = cls;
                       }
                   }
               }
               return returnCls;
            } 
         }
    });
    
    // set the root node
    raizComparador = new Ext.tree.TreeNode({
        text: paqueteComparar_RTL,
        draggable:false,
        id:'comparator'
    });
    
       
    treeComparator.setRootNode( raizComparador );
    treeComparator.render();
    //--    Aparecerá plegado el cajetín.
    treeComparator.collapse(); 
    treeComparator.setVisible( false ) ;

        
    //--  Aparecerá desplegado el árbol dentro del cajetín.
    raizComparador.expand();

    //--  Se inician los campos de la búsqueda por campos, agrupados.
    Ext.getCmp( 'agruparCampos' ).setValue( true ) ;  //-- No, casca





}); //______________________________________________________________________________________________









/*  .........................................................
 *      CARGA EL ARBOL DE DICOTOMÍAS DE TREEBOLIC 
 *  .........................................................
 */
function cargaClaveDitocomica( idfb ){

    if( pestaniaDicotomias == null ) {
        pestaniaDicotomias = new Ext.Panel( {
            // contentEl:'resultadoBusqueda',
            id: "pestaniaDicotomia",
            title: arbolDicotomias_RTL,
            closable:true,
            autoScroll:true,
            listeners:{ 
                beforedestroy:{ 
                    fn:function( estePanel ) {
                        pestaniaDicotomias = null;
                    }
                }
            }
        });
        
        panelPestanias.add( pestaniaDicotomias );
        panelPestanias.doLayout();
    }

    pestaniaDicotomias.load(
          { url:"ClavesDicotomicas.jsp", 
            params: { 
                ID: idfb
            },
            scripts:true,
            loadingText : cargandoClavesDicotomicas_RTL
          });

    panelPestanias.activate( pestaniaDicotomias );

}//_____________________________________________________________________________








/*  .........................................................
 *      ELIMINA LAS ESPECIES SELECCIONADAS DEL COMPARADOR 
 *  .........................................................
 */
function quitaSeleccionadas(){
    
    for( var i=0; i<raizComparador.childNodes.length; i++){
        if( raizComparador.item(i).isSelected() ){
            raizComparador.item(i).remove() ;
        }
    }
}//_____________________________________________________________________________





/*  .......................................................................
 *      REALIZA LA COMPARACIÓN DE ESPECIES CARGADAS EN EL COMPARADOR 
 *  .......................................................................
 */
function Comparar(){
    
    var idElementosAcomparar = "";
    var nombresElementosAcomparar = "";

    if( raizComparador.childNodes.length < 2 ){
        Ext.Msg.alert( elementosInsuficientes_RTL, necesarioMasEspecies_RTL );
        return;
    }


    for( var i=0; i<raizComparador.childNodes.length; i++){
        idElementosAcomparar = idElementosAcomparar + "&" + raizComparador.item(i).id ;
        nombresElementosAcomparar = nombresElementosAcomparar + "&" + raizComparador.item(i).text ;
    }


    if( Ext.getCmp( 'pestaniaComparador' ) == null ) {
        pestaniaComparador = new Ext.Panel( {
            id: "pestaniaComparador",
            title: comparadorEspecies_RTL,
            closable:true,
            autoScroll:true
        });
        
        panelPestanias.add( pestaniaComparador );
        panelPestanias.doLayout();
    }

    var urlParaComparador = "cmpDicotTreebolic.jsp" ;
//    if( document.getElementById( "siNuevaDicotomia" ).checked ){
//        urlParaComparador = "cmpDicotTreebolic2.jsp" ;
//    }

    pestaniaComparador.load(
          { url: urlParaComparador,
            params: { 
                ELEMENTOS: idElementosAcomparar,
                NOMBRES: nombresElementosAcomparar
            },
            scripts:true,
            loadingText : cargandoComparador_RTL + '...'
          }
    );

    panelPestanias.activate( pestaniaComparador );

    
    
}//_____________________________________________________________________________





var tipoBusqueda ;



/*  .........................................................
 *         EJECUTA LA BÚSQUEDA Y RECUPERA LOS RESULTADOS 
 *  ......................................................... */
function realizaBusqueda(){

    texto = Ext.getCmp( 'texto' ).getValue();        
    genero = Ext.getCmp( 'genero' ).getValue();        
    familia = Ext.getCmp( 'familia' ).getValue();        
    provinciaSeleccionada = Ext.getCmp( 'provincia' ).getValue();        

    planta = Ext.getCmp( 'planta' ).getValue();
    raiz = Ext.getCmp( 'raiz' ).getValue();
    cepa = Ext.getCmp( 'cepa' ).getValue();
    tallos_y_ramas = Ext.getCmp( 'tallos_y_ramas' ).getValue();
    espinas = Ext.getCmp( 'espinas' ).getValue();
    hojas = Ext.getCmp( 'hojas' ).getValue();
    flor = Ext.getCmp( 'flor' ).getValue();
    inflorescencia = Ext.getCmp( 'inflorescencia' ).getValue();
    receptaculo = Ext.getCmp( 'receptaculo' ).getValue();
    caliz = Ext.getCmp( 'caliz' ).getValue();
    corola = Ext.getCmp( 'corola' ).getValue();
    gineceo = Ext.getCmp( 'gineceo' ).getValue();
    androceo = Ext.getCmp( 'androceo' ).getValue();
    nectarios = Ext.getCmp( 'nectarios' ).getValue();
    fruto = Ext.getCmp( 'fruto' ).getValue();
    semilla = Ext.getCmp( 'semilla' ).getValue();
    vernaculos = Ext.getCmp( 'vernaculos' ).getValue();
    habitat = Ext.getCmp( 'habitat' ).getValue();

    tipoBusqueda = Ext.getCmp( 'tabBusqueda' ).getActiveTab().getId() ;
    // Opciones posibles:  "textoLibre", "porCampos",

    
    agruparCampos = Ext.getCmp( 'agruparCampos' ).getValue();
    


    if( tipoBusqueda == "textoLibre" ){
        if( texto.length < 3 ){
            Ext.Msg.alert( textoNoValido_RTL, alMenosTresLetras_RTL );
            return ;
        }
        
    }else{
                                                                                   
        if( ! agruparCampos ){
            if( raiz.length>0  && raiz.length < 3 ){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + raiz_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }else if( cepa.length>0  && cepa.length < 3 ){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + cepa_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }else if( tallos_y_ramas.length>0  && tallos_y_ramas.length < 3){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + tallosYramas_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }else if( espinas.length>0  && espinas.length < 3){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + espinas_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }else if( inflorescencia.length>0  && inflorescencia.length < 3 ){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + inflorescencia_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }else if( receptaculo.length>0  && receptaculo.length < 3 ){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + receptaculo_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }else if( caliz.length>0  && caliz.length < 3 ){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + caliz_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }else if( corola.length>0  && corola.length < 3 ){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + corola_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }else if( nectarios.length>0  && nectarios.length < 3 ){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + nectarios_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }else if( semilla.length>0  && semilla.length < 3){
                Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + semilla_RTL.toUpperCase(), alMenosTresLetras_RTL );
                return ;
            }            
            
            if(   planta.length==0          &&    raiz.length==0            &&    cepa.length==0         && 
                  tallos_y_ramas.length==0  &&    espinas.length==0         &&    hojas.length==0        && 
                  flor.length==0            &&    inflorescencia.length==0  &&    receptaculo.length==0  && 
                  caliz.length==0           &&    corola.length==0          &&    gineceo.length==0      && 
                  androceo.length==0        &&    nectarios.length==0       &&    fruto.length==0        &&  
                  semilla.length==0         &&    vernaculos.length==0      &&    habitat.length==0 ){
            
                  Ext.Msg.alert(  'Todos los campos están vacíos', 
                                  'Debe introducir algún texto en algún campo para poder buscarlo.' );
                  return ;
            }  

            
        }else{
            
            if(   planta.length==0       &&    hojas.length==0          &&     flor.length==0    &&    
                  gineceo.length==0      &&    androceo.length==0       &&     fruto.length==0        &&  
                  vernaculos.length==0   &&    habitat.length==0 ){
            
                  Ext.Msg.alert(  'Todos los campos vacíos', 
                                  'Debe introducir algún texto en algún campo para poder buscarlo.' );
                  return ;
            }
        }

                                                                                   
        if( planta.length>0  && planta.length<3 ){
            Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + planta_RTL.toUpperCase(), alMenosTresLetras_RTL );
            return ;
        }else if( hojas.length>0  && hojas.length < 3 ){
            Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + hojas_RTL.toUpperCase(), alMenosTresLetras_RTL );
            return ;
        }else if( flor.length>0  && flor.length < 3 ){
            Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + flor_RTL.toUpperCase(), alMenosTresLetras_RTL );
            return ;
        }else if( gineceo.length>0  && gineceo.length < 3 ){
            Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + gineceo_RTL.toUpperCase(), alMenosTresLetras_RTL );
            return ;
        }else if( androceo.length>0  && androceo.length < 3 ){
            Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + androceo_RTL.toUpperCase(), alMenosTresLetras_RTL );
            return ;
        }else if( fruto.length>0  && fruto.length < 3 ){
            Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + fruto_RTL.toUpperCase(), alMenosTresLetras_RTL );
            return ;
        }else if( vernaculos.length>0  && vernaculos.length < 3 ){
            Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + vernaculos_RTL.toUpperCase(), alMenosTresLetras_RTL );
            return ;
        }else if( habitat.length>0  && habitat.length < 3 ){
            Ext.Msg.alert( textoNoValido_RTL + " " + paraElCampo_RTL + " " + habitat_RTL.toUpperCase(), alMenosTresLetras_RTL );
            return ;
        }
    }



    if( pestaniaResultadoBusqueda == null ) {

        pestaniaResultadoBusqueda = new Ext.Panel( {
            contentEl:'resultadoBusqueda',
            title: resultadoBusqueda_RTL,
            closable:false,
            autoScroll:true
        });

        panelPestanias.add( pestaniaResultadoBusqueda );
        panelPestanias.doLayout();
    }
    
    panelPestanias.activate( pestaniaResultadoBusqueda );

    gridResultados.setVisible( true ) ;

    
    // storeBusqueda.reload();
    storeBusqueda.load( {params: {start: 0, limit: 15} } );
    
    //--    Expande el panel del comparador de especies.
    treeComparator.collapse(); 
    treeComparator.setVisible( true ) ;
    
}//_____________________________________________________________________________





/**
 *      Realiza las búsquedas de localización directa.
 */
function localizacionDirecta() {

    familia = Ext.getCmp( 'familiaDirecta' ).getValue();        
    genero = Ext.getCmp( 'generoDirecta' ).getValue();        

    provinciaSeleccionada = Ext.getCmp( 'provinciaDirecta' ).getValue();        

    
    texto = "",  
    planta = "",  
    raiz = "",  
    cepa = "",  
    tallos_y_ramas = "",  
    espinas = "",  
    hojas = "",  
    flor = "",  
    inflorescencia = "",  
    receptaculo = "",  
    caliz = "",  
    corola = "",  
    gineceo = "",  
    androceo = "",  
    nectarios = "",  
    fruto = "",  
    semilla = "",  
    vernaculos = "",  
    habitat = "",  
    tipoBusqueda = "",  
    agruparCampos = false ;
    

    if( pestaniaResultadoBusqueda == null ) {

        pestaniaResultadoBusqueda = new Ext.Panel( {
            contentEl:'resultadoBusqueda',
            title: resultadoBusqueda_RTL,
            closable:false,
            autoScroll:true
        });

        panelPestanias.add( pestaniaResultadoBusqueda );
        panelPestanias.doLayout();
    }
    
    panelPestanias.activate( pestaniaResultadoBusqueda );

    gridResultados.setVisible( true ) ;

    
    // storeBusqueda.reload();
    storeBusqueda.load( {params: {start: 0, limit: 15} } );
    
    //--    Expande el panel del comparador de especies.
    treeComparator.collapse(); 
    treeComparator.setVisible( true ) ;

} //________________________________________________________________________________________________











var panelesPestaniasTaxones = new Array(); 
var contadorPestanias = 0;
var panelIzquierdo = new Array();
var panelDerecho = new Array();
var fichaSinonimos = new Array();
var fichaFloracion = new Array();
var fichaAltitud = new Array();
var fichaProvincias = new Array();



/* ...............................................................
 *          VISUALIZA UNA FICHA DE UN TAXON
 * ................................................................
*/

function cargaFichaTaxon( idfb, nombre ) {


   if( nombre.charAt(0)=='*' ){
      alert( 'La especie indicada, no se encuentra aún recopilada en la base de datos' );
      return;
   }


   //-- Si ya hay una pestaña con el taxón marcado, se activa y no se 
   //-- carga una nueva.
   if( panelPestanias.getItem( "pestania_" + idfb ) != null ){
        panelPestanias.setActiveTab( panelPestanias.getItem( "pestania_" + idfb ) );
        return ;
   }

    
   fichasTaxones[ contadorFichasTaxones ] = new Ext.Panel( {
            id:"pestania_" + idfb,
	    title: nombre, 
            iconCls: 'iconFicha',
	    closable: true,
            autoScroll:true
   });

    
   panelPestanias.add( fichasTaxones[ contadorFichasTaxones ] );
    
   //--    The Container will need to recalculate its View now that it has a new child Component
   panelPestanias.doLayout();
    
   //--    Make the newest tab visible
   panelPestanias.setActiveTab( panelPestanias.items.getCount() - 1);



   fichasTaxones[ contadorFichasTaxones ].load(
      { url:"FichaTaxon.jsp", 
        params: { 
            IDFB: idfb,
            TEXTO: texto, 
            PLANTA: planta, RAIZ:raiz, CEPA:cepa, TALLOS_Y_RAMAS: tallos_y_ramas, 
            ESPINAS: espinas, HOJAS: hojas, FLOR: flor, INFLORESCENCIA: inflorescencia, 
            RECEPTACULO: receptaculo, CALIZ: caliz, COROLA: corola, GINECEO: gineceo, 
            ANDROCEO: androceo, NECTARIOS: nectarios, FRUTO: fruto, SEMILLA: semilla, 
            VERNACULOS: vernaculos, HABITAT: habitat, 
            TIPOBUSQUEDA: tipoBusqueda, 
            AGRUPARCAMPOS: agruparCampos 
        },
        method: 'POST',        
        scripts:true,
        loadingText : cargando_RTL + ' ' + nombre + ' ...'
   });

   contadorFichasTaxones++ ;
}//_____________________________________________________________________________









function agrupaOdesagrupaCampos( siAgrupar ) {
    visualizaCampo( !siAgrupar, Ext.getCmp( 'raiz' ) ) ;
    visualizaCampo( !siAgrupar, Ext.getCmp( 'cepa' ) ) ;
    visualizaCampo( !siAgrupar, Ext.getCmp( 'tallos_y_ramas' ) ) ;
    visualizaCampo( !siAgrupar, Ext.getCmp( 'espinas' ) ) ;
    visualizaCampo( !siAgrupar, Ext.getCmp( 'inflorescencia' ) ) ;
    visualizaCampo( !siAgrupar, Ext.getCmp( 'receptaculo' ) ) ;
    visualizaCampo( !siAgrupar, Ext.getCmp( 'caliz' ) ) ;
    visualizaCampo( !siAgrupar, Ext.getCmp( 'corola' ) ) ;
    visualizaCampo( !siAgrupar, Ext.getCmp( 'nectarios' ) ) ;
    visualizaCampo( !siAgrupar, Ext.getCmp( 'semilla' ) ) ;
}//_____________________________________________________________________________




function visualizaCampo( siVisualizar, campo ){
    if( siVisualizar ){
        campo.enable();
//        campo.show();
    }else{
        campo.disable();// for validation
//        campo.hide();
    }
    //campo.getEl().up('.x-form-item').setDisplayed( siVisualizar ); 
    
}//_____________________________________________________________________________






/* ...............................................................
 *          VISUALIZA UNA FICHA DE UN TAXON
 * ................................................................
*/
function cargaImagen( id, idfb, nombre ) {

   var pestaniaImagen = new Ext.Panel( {
            id:"imagen" + idfb,
	    title: nombre + " (Imagen)", 
            iconCls: 'iconFicha',
	    closable: true,
            autoScroll:true
   });

   panelPestanias.add( pestaniaImagen );
    
   //--    The Container will need to recalculate its View now that it has a new child Component
   panelPestanias.doLayout();
    
   //--    Make the newest tab visible
   panelPestanias.setActiveTab( panelPestanias.items.getCount() - 1);

/*

    <a href='lamina.jsp?id=<%= imagenesRutas[i] %>&idfb=<%= idfb %>' target='_blank' > 
*/

   pestaniaImagen.load(
      { url:"lamina.jsp", 
        params: { 
            id: id,
            idfb: idfb 
        },
        scripts:true,
        loadingText : 'Cargando ...'
   });

}//_____________________________________________________________________________






