var view; 
var dsSList; 
var tabc, slViewTab, slDownloadTab; 
var slurl = 'GetNames?'; 
var spResults; 

var spListLimit = 100; 
var converted; 

var SpeciesListing = {
    init : function() {
        
        
        // set up the button click on this page
        var goSpecieslist = Ext.get('goSpecieslist'); 
        goSpecieslist.on('click', this.getData, this); 
        
        // species list 
        roiLink2 = Ext.get('select-roi-btn'); 
        
        roiLink2.on('click', function(e){
            e.stopEvent();
            tabs.activate('roi-tab');
            advSearch.show(roiLink2);
        });
        
        converted = new Ext.form.ComboBox({
            id: 'cgroup', 
            typeAhead: true,
            triggerAction: 'all',
            transform:'cgroupsel',
            width:180,
            forceSelection:true
        });   
        converted.on('select', function() {
            document.getElementById('cgroup').value = converted.getValue(); 
        })
        
        // setup the download and cancel species list buttons
        var dlSpeciesList = Ext.get('dlSpeciesList'); 
        dlSpeciesList.on('click', this.downloadData, this); 
        
        var ndlSpeciesList = Ext.get('ndlSpeciesList'); 
        ndlSpeciesList.on('click', this.cancelDownload, this); 
        
        /*
        var ls = location.search; 
        if (ls.length > 1) {
            console.log("generating request"); 
            this.getData2(); 
            //var splist = Ext.get('splist'); 
            //var blah = slurl + location.search; 
            //splist.load(blah); 
         
        } else {
            console.log("not generating request"); 
        }
         */
    }, 
    
    dothis : function() {
        //console.log('loading complete'); 
    }, 
    
    downloadData : function() {
        //Ext.MessageBox.alert("BioMaps", "Downloading data..."); 
        location.href='GetNames?sa=d&' + Ext.Ajax.serializeForm("frmMapSpecies");
        slViewTab.close(); 
    }, 
    
    cancelDownload : function() {
        slViewTab.activate(); 
        Ext.MessageBox.alert("BioMaps", "Download cancelled..."); 
    }, 
    
    getData : function(config) {
        document.getElementById('st').value="sl";  
        
        if (!spResults) {
            spResults = new Ext.BasicDialog("splistresult-dlg", {
                autoTabs:true,
                modal:true,
                width:775,
                height: 600,
                shadow: true,
                minWidth: 700,
                minHeight: 600 
            }); 
            spResults.addKeyListener(27, spResults.hide, spResults);
            spResults.addButton('Close', spResults.hide, spResults);
            
            tabs = spResults.getTabs();
            
            slViewTab = tabs.getTab('splistresult-tab'); 
            
            slDownloadTab = tabs.getTab('splistdownload-tab'); 
            slDownloadTab.disable(); 
            
            
            this.setupGrid();
            
            tabs.activate('splistresult-tab');
        }
        
        var formObject = document.getElementById('frmMapSpecies'); 
        var qs = Ext.Ajax.serializeForm("frmMapSpecies");
        var dataURL = slurl + qs; //"&cgroup=" + $F('cgroup') + "&roiType=" + $F('roiType'); // + "&chkroi=" + $F('chkroi');
        dsSList.proxy = new Ext.data.HttpProxy({
            url: dataURL
        });
        
        spResults.show(); 
        // trigger the data store load
        dsSList.load({params:{start:0, limit:spListLimit}, callback: alldone}); //, st: "sl", cgroup: cg, sortby: sortby
        //console.log("dsslist.load complete"); 
    }, 
    
    setupGrid : function() {
        dsSList = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: slurl
            }),
            reader: new Ext.data.JsonReader({
                root: 'slresults',
                totalProperty: 'totalCount',
                id: 's'
            }, [
            {name: 'o'},
            {name: 'f'},
            {name: 'g'},
            {name: 's'},
            {name: 'cnt'}
            ])
            ,remoteSort: true 
        });
        
        
        // Setup columns
        // the column model has information about grid columns
        // dataIndex maps the column to the specific data field in
        // the data store
        var cm = new Ext.grid.ColumnModel([{
            header: "Order",
            dataIndex: 'o',
            width: 150,
            align: 'left'
            //renderer: renderTopic,
            //css: 'white-space:normal;'
        },{
            header: "Family",
            dataIndex: 'f',
            width: 150,
            align: 'left'
            //hidden: true
        },{
            header: "Scientific Name",
            dataIndex: 's',
            width: 250,
            align: 'left'
        },{
            header: "Record count",
            dataIndex: 'cnt',
            width: 70,
            align: 'left'
            //renderer: renderLast
        },{
            header: "Add to Map",
            width: 70,
            align: 'left', 
            renderer: renderAddToMap
        }]);
        cm.defaultSortable = false;
        // End columns setup
        
        // setup grid
        // create the editor grid
        var grid = new Ext.grid.Grid('slgrid', {
            ds: dsSList,
            cm: cm,
            height: 500, 
            width: 750,
            selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
            enableColLock:false,
            loadMask: true
        });
        // render it
        grid.render();
        
        var gridFoot = grid.getView().getFooterPanel(true);
        // add a paging toolbar to the grid's footer
        var paging = new Ext.PagingToolbar(gridFoot, dsSList, {
            pageSize: spListLimit,
            displayInfo: true,
            displayMsg: 'Displaying species list {0} - {1} of {2}',
            emptyMsg: "No species to display"
        });
        
        paging.add('-', 'Scientific name filter : '); // add a separator followed by a text string to label the filter input
        var filter = Ext.get(paging.addDom({ // add a DomHelper config to the toolbar and return a reference to it
            tag: 'input'
            , type: 'text'
            , size: '30'
            , value: ''
            , cls: ''
        }).el);
        
        
        filter.on('keypress', function(e) { // setup an onkeypress event handler
            if(e.getKey() == e.ENTER) // listen for the ENTER key
                dsSList.load({ // call the load() method of your datastore
                    params: {
                        start: 0 // reset the start to 0 since you want the filtered results to start from the first page
                        , limit: spListLimit
                    }
                });
        });
        
        
        filter.on('keyup', function(e) { // setup an onkeyup event handler
            if(e.getKey() == e.BACKSPACE && this.getValue().length == 0) // listen for the BACKSPACE key and the field being empty
                dsSList.load({ // call the load() method of your datastore
                    params: {
                        start: 0 // reset the start to 0 since you want unfiltered results to start from the first page
                        , limit: spListLimit
                    }
                });
        });
        
        
        filter.on('focus', function(){this.dom.select();}); // setup an onfocus event handler to cause the text in the field to be selected
        dsSList.on('beforeload', function() {
            dsSList.baseParams = { // modify the baseParams setting for this request
                filter: filter.getValue() // retrieve the value of the filter input and assign it to a property named filter (rename to suit your needs)
                
            };
        });        
        
        
        // end grid setup
        
    }
}
Ext.EventManager.onDocumentReady(SpeciesListing.init, SpeciesListing, true);

function renderAddToMap(value, p, record){
    return String.format('<a href="SpecimenSearch?cqn={0}&cql=SCI_NAME" class="addtomap" onclick="ShowMenu(event.clientX, event.clientY, this.href); event.returnValue=false; event.cancelBubble=true; return false;" onblur="HideMenu();">Add to map</a>', record.data['s']);
}

function alldone(r) {
    //console.log("all done: ");  //  r.totalCount
    slDownloadTab.enable(); 
}
