var border;
var gMultiSelect = false;


/***** EXT JS *****/
/* this custom RowSelectionModel allows multiple selection with single click.
Also clicking the selected row deselects it.
The default RowSelectionModel requires to do these with CTRL-Click
*/
Ext.ux.RowSelectionModelMSBSC = Ext.extend(Ext.grid.RowSelectionModel, {
	singleSelect: false,
	multiSelectWithClick: false,
	deselectWithClick: true,
	
	/* override selectRow */
    handleMouseDown : function(g, rowIndex, e){
        if(e.button !== 0 || this.isLocked()){
            return;
        };
        var view = this.grid.getView();
        if(e.shiftKey && !this.singleSelect && this.last !== false){
            var last = this.last;
            this.selectRange(last, rowIndex, e.ctrlKey);
            this.last = last; // reset the last
            view.focusRow(rowIndex);
        }else{
            var isSelected = this.isSelected(rowIndex);
            if((e.ctrlKey && isSelected) || (this.deselectWithClick && isSelected)){
                this.deselectRow(rowIndex);
            }else if(!isSelected || this.getCount() > 1){
                this.selectRow(rowIndex, e.ctrlKey || e.shiftKey || this.multiSelectWithClick);
                view.focusRow(rowIndex);
            }
        }
    }	 
});

Ext.ux.SliderTip = Ext.extend(Ext.Tip, {
    minWidth: 10,
    offsets : [0, -10],
    init : function(slider){
        slider.on('dragstart', this.onSlide, this);
        slider.on('drag', this.onSlide, this);
        slider.on('dragend', this.hide, this);
        slider.on('destroy', this.destroy, this);
    },

    onSlide : function(slider){
        this.show();
        this.body.update(this.getText(slider));
        this.doAutoWidth();
        this.el.alignTo(slider.thumb, 'b-t?', this.offsets);
    },

    getText : function(slider){		// Can be overridden
        return slider.getValue();
    }

});


Ext.onReady(function(){
	init();		// Load google maps etc. This sets gQuery.sp_tsn which is needed for store.load()

	var btn_sort = new Ext.Toolbar.Button({id: "btn_sort", text: "Sort by name", handler: sort_by_name, tooltip: "Sort by dataset name",  tooltipType: "title"});
	var btn_collapse = new Ext.Toolbar.Button({text: "Collapse all", id: "btn_collapse", handler: collapse_all, tooltip: "Collapse providers",  tooltipType: "title"});
	var btn_fill = new Ext.Toolbar.Fill();
	if (store.id == "species_store") {
		var tip = "Press to select multiple species";		
	} else {
		var tip = "Press to select multiple datasets";
	}
	var btn_multi_select = new Ext.Toolbar.Button({text: "Multi-select", id: "btn_multi_select", enableToggle: true, toggleHandler: multi_select, pressed: false, tooltip: tip,  tooltipType: "title"});
	var btn_show_all = new Ext.Toolbar.Button({text: "Clear selection", id: "btn_show_all", handler: show_all, tooltip: "Clear user-made selection and show all observations",  tooltipType: "title"});
	
    grid = new Ext.grid.GridPanel({		// This grid is rendered (grid.render()) when species tab first shows up: switch_tab() in detail_common_v2_2.js.
    	id: "grid",
        el:'sp_ds_list',
        //width: 'auto',		// Width is set to 'auto' in switch_tab in detail_common_v2_2.js
        height:400,
        title:'Large list',
        header: false,
        store: store,
        trackMouseOver:true,
        loadMask: true,
		autoHeight: false,
		cm: cm,
		sm: new Ext.ux.RowSelectionModelMSBSC(),
		stripeRows: true,
		tbar: [btn_sort, '-',btn_collapse, btn_fill, btn_multi_select, '-', btn_show_all],
		autoExpandColumn: 'entity_name',	// performance check
		cls: "grid",
		ctCls: "grid",
		stateful: false,
	    view: gv
    });
    
    grid_simple = new Ext.grid.GridPanel({
        region: 'west',
    	id: "grid_simple",
        title:'&nbsp;<a id="link_sort" href="javascript:void(0)" onclick="sort_by_name()" title="Sort by name">Sort by name</a>',
        width:250,
        height:400,
        minHeight: 350,
        autoHeight: false,
		cmargins: '0 5 0 0',
        collapsible: true,
        split: true,
        hideHeaders: true,
        store: store,
        trackMouseOver:true,
        loadMask: true,
		autoHeight: false,
		cm: cm_simple,
		sm: new Ext.ux.RowSelectionModelMSBSC(),
		stripeRows: true,
		cls: "grid",
		ctCls: "grid",
		stateful: false,
		view: gv_simple
    });    

    grid_simple.on("rowclick", row_clicked);
   
    // trigger the data store load
    //store.load();		// store is loaded in map_loaded in species_profile_v2_2.js which makes you feel faster page loading.
    
    // main frame
	border = new Ext.Panel({
	    title: 'Main frame',
	    header: false,
	    layout:'border',
	    renderTo: "body_frame",
	    monitorResize: true,
        height: 800,
        //autoHeight: true,
		defaults: {
			//collapsible: true,
	        split: true,
			animFloat: false,
			autoHide: false,
			useSplitTips: true,
			stateful: false,
			monitorResize: true		// performance check
		},
		
	    items: [{
	        region: 'north',		// North frames Google Maps, left-hand side list, legend and graph.
	        title: 'Map, list, legend, graph',
	        id: 'map_list_legend_graph_panel',
	        layout: 'border',
	        header: false,
	        border: false,
	        height: 400,
	        minHeight: 350,
	        margins: '5 5 0 5',
	        items: [
	        	grid_simple,		// West region: Left-hand side list (species/dataset list) is defined above.
				{
			        title: 'Map, Legend, Graph',	// Center region: Nested border containing google maps, graph, legend
			        region:'center',
			        layout:'border',
			        header: false,
			        height: 400,
			        minHeight: 350,
			        autoHeight: false,
			        border: false,
					defaults: {
						//collapsible: true,
				        split: true,
						animFloat: false,
						autoHide: false,
						useSplitTips: true,
						monitorResize: false	// for performance. not yet verified, though.
					},
			        items: [{
			        	title: 'Google Maps and tools',
			        	id: 'map_panel',
			        	region:'center',
			        	contentEl: "center_pane",
		   		        header: false,
				        height: 400,
				        minHeight: 350,
				        autoHeight: false,
				        listeners: {
							resize: resize_map
				        }
			        	}, {
					        title: ' ',
					        region:'east',
					        id:'general_info_panel',
					        layout: 'card',
					        activeItem: 0,
							collapsible: true,
							cmargins: '0 0 0 5',
					        width: 170,
					        height: 400,
					        minHeight: 350,
					        autoHeight: false,
					        stateful: false,
					        bbar: [{
							    id: 'card-general',
							    text: '&laquo; General info.',
							    handler: switch_card.createDelegate(this, [0, "general_info_panel"]),
							    hidden: true
							},'->', {
							    id: 'card-legend',
							    text: 'Env. legend &raquo;',
							    handler: switch_card.createDelegate(this, [1, "general_info_panel"])
							}],
					        items: [
					        {
					        	id: 'general_info',
					        	contentEl: 'east_pane',
						        border: false
					        }, {
					        	id: 'env_legend_panel',
					        	html: "<div class='current_env_layer'></div><img class='env_legend' src='/seamap2/icons/blank.png'>",
						        border: false,
						        bodyStyle: 'padding:5px',
						        autoScroll: true
					        }
					        ]
				        }, {
					        title: 'Graph and Environment',
					        id: "graph_and_env_panel",
					        region:'south',
					        layout: 'border',
					        border: false,
							collapsible: false,
							hidden: true,
							header: false,
					        width: 150,
					        height: 200,
					        minHeight: 200,
					        autoHeight: false,
					        defaults: {
						        split: true,
								animFloat: false,
								autoHide: false,
								useSplitTips: true,
								monitorResize: true
					        },
					        items: [{
					        	title: 'Graph',
					        	region:'center',
					        	id: 'graph_panel',
					        	contentEl: "info_frame",
				   		        header: false,
						        height: 200,
						        minHeight: 200,
						        autoHeight: false
					        }, {
					        	title: 'Environmental Layer',
					        	region:'east',
					        	id: 'env_option_panel',
					        	contentEl: "option_form",
				   		        header: true,
				   		        collapsible: true,
								collapsed: true,
						        height: 200,
						        minHeight: 200,
						        width: 300,
						        cmargins: '0 0 0 5',
						        bodyStyle: 'padding: 5px',
						        autoHeight: false
					        }]		// End of Graph / Environment (south region)
				        }]			// End of Google Maps and tools (center region)
			    }]	// End of Map, list, legend, graph (No north region)
	        }, {
	        region: 'center',		// Infor tabs in center region
	        title: 'info tabs',
	        header: false,
	        contentEl: "tabs",	// load <div id="tabs"> into the center region.
	        border: true,
	        height: 400,
	        autoHeight: true,
	        minHeight: 300,
	        margins: '0 5 0 5',
	        bodyStyle: 'padding: 5px',
	        listeners: {
				resize: window_resize
	        }  
		}]
	});		// End of main frame (Ext.Panel)
	
	//grid.render();		// grid is rendered in map_loaded. It makes you feel faster page loading.
	//grid.on("rowclick", row_clicked);	
	
	toggle_east_toolbar(true);
	
	/***** Implement misc tools. *****/
	/* 1. Transparency slide bar */
	var transparency_tip = new Ext.ux.SliderTip({		// Defined above
	    getText: function(slider){
	        return String.format('{0}% transparent', slider.getValue());
	    }
	});
	
    new Ext.Slider({
        renderTo: 'transparency_bar',
        //width: 105,
        width: 80,
        minValue: 0,
        maxValue: 100,
        value: 60,
        plugins: transparency_tip,
        listeners: {
        	 //changecomplete: slider_changed
        	 change: polygon_transparency
        }
    });
    
    new Ext.ToolTip({
    	target: "transparency_bar",
    	html: "drag slider to change polygon transparency",
    	autoWidth: true,
    	autoHeight: true,
    	mouseOffset: [10,10]
    });	
    
	/* 2. Calendar tool for env layer "Specified below" option */
	/*
	new Ext.form.DateField({
		renderTo: "div_env_time_range",
		fieldLabel: "Specified below",
		name: "env_time_range",
		id: "env_time_range",
		//format: "Y-m-d",
		altFormats: "Y|Y-m|Y-m-d|Y/m/d|m/d/Y",
		value: "2000",
		validateOnBlur: false,
		validationEvent: false
	});
	*/
    
	//store.remoteGroup = false;
	//store.remoteSort = false;
});

function row_clicked(theGrid, rowIndex, e) {
	if (theGrid.id == "grid") {
		var selModel2 = grid_simple.selModel;
	} else {
		if (grid.rendered) {		// Grid in [Datasets/Species] tab may not be rendered yet.
			var selModel2 = grid.selModel;
		} else {
			var selModel2 = null;
		}
	}
	var row = theGrid.store.getAt(rowIndex);
	var id = parseInt(row.id);			
	if (store.id == "species_store") {
		var ids = gQuery.sp_tsn;	// Dataset Page
		var id = parseInt(row.data.sp_tsn);		// In Dataset Page, id is sp_obs (to show same sp_tsn with different sp_obs).
		gQuery.series = [];
	} else {
		var ids = gQuery.dataset;	// Species Profile Page
		var id = parseInt(row.id);			
	}
	
	//if (ids.indexOf(id) == -1) {
	if (theGrid.getSelectionModel().isSelected(rowIndex) || ids.length == 0) {
		// Newly selected.
		if (gMultiSelect) {
			ids.push(id);
		} else {
			ids = [id];			
		}
		if (selModel2 != null) {
			selModel2.selectRow(rowIndex, gMultiSelect);
		}
	} else {
		// Already selected. Deselect. gMultiSelect doesn't matter.
		ids = ids.without(id);
		if (selModel2 != null) {
			selModel2.deselectRow(rowIndex);
		}
	}
	
	if (store.id == "species_store") {
		gQuery.sp_tsn = ids;
		if (gDataset.ds_type == "pthab" && gQuery.spatial == "") {
			get_habitat_from_species();
		}			
	} else {
		gQuery.dataset = ids;
	}
	
	if (gQuery.dataset[0] == 427 && !gTripSpeciesClicked) {
		// When species is selected from the left-hand side panel,
		// always clear trip selection and species selection (euring) in trip.
		gEsasTrips = [];
		gEsasEurings = [];
	}
	
	roi_updated();		// Always clear time range.
	
}

function switch_card(id, panel_id) {
	var east = Ext.getCmp(panel_id);
	east.layout.setActiveItem(id);
	var bbar = east.getBottomToolbar();
	bbar.items.items[id * 2].hide();
	bbar.items.items[2 - id * 2].show();
}

function toggle_east_toolbar(hidden) {
	var east = Ext.getCmp("general_info_panel");
	var height = east.getSize().height;
	var bbar = east.getBottomToolbar();
	if (hidden) {
		bbar.hide();
		if (Ext.isIE) {		// IE can't handle bbar's outer div height.
			$$("#general_info_panel div.x-panel-bbar")[0].setStyle({display: "none"});
		}
	} else {
		if (Ext.isIE) {		// IE can't handle bbar's outer div height.
			$$("#general_info_panel div.x-panel-bbar")[0].setStyle({display: "block"});
		}
		bbar.show();
	}
	east.syncSize();
	east.doLayout();
	east.setHeight(height);
}

function multi_select(item, pressed){
	if (item.id == "btn_series_multi_select") {
		gSeriesMultiSelect = pressed;
		Ext.getCmp("series_grid").getSelectionModel().multiSelectWithClick = pressed;
	} else {
		gMultiSelect = pressed;
		grid.getSelectionModel().multiSelectWithClick = pressed;
		grid_simple.getSelectionModel().multiSelectWithClick = pressed;
	}	
	if (!pressed) {
		// Clear selection. not used now.
	}
}


function window_resize (panel, adjWidth, adjHeight, rawWidth, rawHeight) {
	var prevWinW = gWinW;
	gWinW = GetWindowSize('width');
	if (typeof(border) != "undefined") {
		if (Ext.isIE6) {
			// IE6 can't adjust the width of main frame and needs help here.
			// Also resize event is not fired in IE6. So when resizing the window after the initial page load, this function is not called.
			var width = GetWindowSize('width') * 0.95;
			border.setWidth(width);
		}
		var layout = border.layout;
		var buffer1 = 12;		// margins etc. in the border layouts
		var buffer2 = 10;		// give arbitrary space below the info tab.
		border.setHeight(layout.north.getSize().height + layout.center.getSize().height + buffer1 + buffer2);
		
		if (grid.rendered && $("tab_sp_ds").visible() && prevWinW != gWinW) {
			if (!Ext.isIE6) {	// for IE6, the width is set in switch_tab in detail_common_v_2_2.js
				grid.setWidth('auto');
			}
			
			grid.syncSize();
		}
	}
}


function resize_map (panel, adjWidth, adjHeight) {
	var toolbar_height = 30;
	var dimension = {};
	if (typeof(adjWidth) != "undefined") {
		dimension['width'] = adjWidth + "px";
	}
	if (typeof(adjHeight) != "undefined") {
		dimension['height'] = (adjHeight - toolbar_height) + "px";
	}
	$("map").setStyle(dimension);
	if(typeof(map) != "undefined") {
		map.checkResize();
	}
}


function sort_by_name(btn) {
	// this function is used by both a button in grid toolbar and <a> link in grid_simple titlebar.
	// In titlebar, it's a link and btn is not passed.
	if (typeof(btn) == "undefined") {
		btn = Ext.getCmp("btn_sort");
	}
	if (btn.text == "Sort by name") {
		store.clearGrouping();
		store.sort("entity_name", "ASC");
		if (store.id == "species_store") {
			var title = "Group by taxa";
		} else {
			var title = "Group by provider";
		}
	} else {
		store.groupBy("group_field");
		var title = "Sort by name";
	}
	btn.setText(title);
	$("link_sort").update(title);
}

function collapse_all(btn) {
	if (btn.id == "btn_series_collapse") {
		var theGrid = Ext.getCmp("series_grid");
	} else {
		var theGrid = grid;
	}
	
	if (btn.text == "Collapse all") {
		theGrid.getView().collapseAllGroups();
		btn.setText("Expand all");
	} else {
		theGrid.getView().expandAllGroups();
		btn.setText("Collapse all");
	}
}

function show_all(btn) {
	gQuery.clearTemporal();
	
	if (btn.id == "btn_series_show_all") {
		gQuery.series = [];
		Ext.getCmp("series_grid").selModel.clearSelections();
	} else {
		if (store.id == "species_store") {
			gQuery.sp_tsn = [];
		} else {
			gQuery.dataset = [];
		}
		grid.selModel.clearSelections();
		grid_simple.selModel.clearSelections();
	}
	
	roi_updated();	
}
