var grid; 
var advSearch;

var rtglobal; 

var AdvSearch = function(){
    
    var roiLink, instLink, dateLink, otherLink;
    var ds, dataURL, ds2; 
    
    return {
        init : function(){
            
            // search and map 
            roiLink = Ext.get('infoROI');
            instLink = Ext.get('infoINST');
            //dateLink = Ext.get('infoDATE');
            otherLink = Ext.get('infoOTHER');
            
            this.createAdvSearchDialog();
            this.loadROITypeList();
            //this.setupROIMap(); 
            
            //this.testload();
            
            roiLink.on('click', function(e){
                e.stopEvent();
                tabs.activate('roi-tab');
                advSearch.show(roiLink);
            });
            
            instLink.on('click', function(e){
                e.stopEvent();
                tabs.activate('inst-tab');
                advSearch.show(instLink);
            });
            /*
            dateLink.on('click', function(e){
                e.stopEvent();
                tabs.activate('date-tab');
                advSearch.show(dateLink);
            });
            */            
            otherLink.on('click', function(e){
                e.stopEvent();
                tabs.activate('other-tab');
                advSearch.show(otherLink);
            });
            
        },
        
        createAdvSearchDialog : function() {
            if (!advSearch) {
                advSearch = new Ext.BasicDialog("advsearch-dlg", {
                    autoTabs:true,
                    modal:true,
                    width:600,
                    height: 500,
                    shadow: true,
                    minWidth: 600,
                    minHeight: 500            
                }); 
                advSearch.addKeyListener(27, advSearch.hide, advSearch);
                advSearch.addButton('Accept', advSearch.hide, advSearch);
                
                tabs = advSearch.getTabs();
                tabs.activate(0); 
            }
        }, 
        
        setupROIMap : function() {
            /*
            roimap = new OpenLayers.Map( 'roitype-map' );
             
            var roimaxbounds = new OpenLayers.Bounds(112, -44, -9, 154); 
            var burl = "http://localhost:90/cgi-bin/mswms.exe?"; 
            //var burl = "http://203.202.1.211/biomaps.asp?"; 
             
            var roibase = new OpenLayers.Layer.WMS( "Australia", 
            burl, {layers: 'Australia'} );
             
            var roilayer = new OpenLayers.Layer.Vector( "roilayer" );
             
            roimap.addLayers([roibase, roilayer]);
             
            var roioptions = {drawFeature: myDrawFeature};
            var roicontrol = new OpenLayers.Control.DrawFeature(roilayer, OpenLayers.Handler.Polygon, roioptions); 
             
            roimap.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
            roimap.addControl( new OpenLayers.Control.MousePosition() );
             */
            //console.log("calling roiMapInit");
            roiMapInit(); 
            
            //$('roitype-map').hide();
            //$('roitype-grid').hide();
        }, 
        
        loadROITypeList : function() {
            // simple array store
            var store = new Ext.data.SimpleStore({
                fields: ['abbr', 'roitype'],
                data : BioMaps.data.roiTypes 
            });
            var rtcombo = new Ext.form.ComboBox({
                store: store,
                displayField:'roitype',
                valueField:'abbr', 
                typeAhead: false,
                listAlign: 'l',  
                forceSelection:true, 
                triggerAction: 'all',
                mode: 'local',
                emptyText:'Whole of Australia',
                selectOnFocus:true
            });
            rtcombo.on('select', function() {
                var rtc = rtcombo.getValue(); 
                if (rtc == "") {
                    // do nothing as this would be all records
                    // hide the grid tho
                    //grid.visible = false; 
                    ds.removeAll(); 
                    $('roitype-map').hide();
                    $('roitype-grid').hide();
                    //advSearch.setContentSize(200,200); 
                    //advSearch.resizeTo(600,500); 
                } else if (rtc == "custom") {
                    // custom roi selected so display the map
                    ds.removeAll(); 
                    $('roitype-map').show();
                    $('roitype-grid').hide();
                    advSearch.setContentSize(530,500); 
                } else {
                    // load the selected json data
                    $('roitype-map').hide();
                    $('roitype-grid').show();
                    //advSearch.setContentSize(400,400); 
                    advSearch.resizeTo(600,500); 
                    dataURL = 'includes/' + rtc + 'data.json'; 
                    ds.proxy = new Ext.data.HttpProxy({
                        url: dataURL
                    });                                
                    ds.load(); 
                }
                document.getElementById('roiType').value=rtcombo.getValue(); 
            });
            rtcombo.applyTo('roiTypeDisplay');
            rtglobal = rtcombo; 
            
            // load data from server 
            var RecordDef = Ext.data.Record.create([
            {name: 'gid'},
            {name: 'fname'},
            {name: 'fdesc'}
            ]);
            var myReader = new Ext.data.JsonReader({
                root: 'roidata',
                totalProperty: 'totalCount',
                id: 'gid'
            }, RecordDef);
            
            // create the data store
            ds = new Ext.data.Store({
                proxy: new Ext.data.HttpProxy({url: 'includes/ibra61data.json'}),
                reader: myReader
            });
            
            var cm = new Ext.grid.ColumnModel([
            //{header: "<input type=checkbox>", width: 40, dataIndex: 'gid'},
            //{header: "", renderer: renderCheckBox }, 
            //{header: "Select", type: 'boolean', dataIndex: 'gid' }, 
            //{header: "Select", width: 50, renderer: render2 }, 
            {header: "Select", width: 50, renderer: renderCheckBox }, 
            {header: "Name", width: 150, dataIndex: 'fname'},
            {header: "Area", width: 150, dataIndex: 'fdesc'}
            ]);
            cm.defaultSortable = true;
            
            // create the grid
            grid = new Ext.grid.Grid('roitype-grid', {
                ds: ds,
                cm: cm,
                loadMask: true,
                width: 300,
                height: 300
            });
            //grid.on("rowclick", rowClick);
            grid.render();
            
            //ds.load(); 
            
            rtglobal.setValue('custom');
            rtglobal.fireEvent('select'); 
        } 
        
    };
}();
Ext.EventManager.onDocumentReady(AdvSearch.init, AdvSearch, true);

/*
checkBoxRowSelectionModel = function(config) {
    checkBoxRowSelectionModel.superclass.constructor.call(this, config);
}
Ext.extend(checkBoxRowSelectionModel , Ext.grid.RowSelectionModel, {
    initEvents : function(){
        var view = this.grid.view;
        view.on("refresh", this.onRefresh, this);
        view.on("rowupdated", this.onRowUpdated, this);
        view.on("rowremoved", this.onRemove, this);
    }	
}
);
 
function rowClick(grid, rowID, e) {
    var x = e.getTarget();
    if (x.name == "chkroi") {
        if (x.checked) {
            x.checked = true;
            grid.selModel.selectRow(rowID, true, false);
            return false;			
        }
        else {
            x.checked = false;
            grid.selModel.deselectRow(rowID, false, false);
        }
    } 
    return true;
}
 */

//create a template for a checkbox pass in the string 'checked' if its cheecked
var tplCB = new Ext.Template( '<input name="chkroi" type="checkbox" value="{value}" />'); //  checked="{checked}"
tplCB.compile();

function renderCheckBox(v, p, record) {
    var chk = '';
    if (grid.selModel.isIdSelected(v)) {
        chk = 'checked'; 
    }	
    return tplCB.applyTemplate({checked: chk, value: record.data.gid});
}

/*
var gv, gp, gr; 
function render2(v, p, record) {
    gv = v;
    gp = p;
    gr = record; 
    //v.getSelectionModel().selectRow(p); 
    return "<input type='checkbox' name='chkroi' value='" + record.data.gid + "' " + (v ? "checked='checked'" : "") + ">";
}
 */