var gSeamapSummary = null;
var store_species;
var cm_species;
var gv_species;
var grid_species;
var store_dataset;
var cm_dataset;
var gv_dataset;
var grid_dataset;

window.onload = window_resize;
window.onresize = window_resize;

/* Species Grid */
store_species = new Ext.data.GroupingStore({
	groupField: "group_field",
	id: 'species_store',
	remoteGroup: true,
	remoteSort: true,
  
	proxy: new Ext.data.HttpProxy({
            url: g_ROOT_URL + '/functions/getSpecies',
            method: 'POST'
        }),
	baseParams: gQuery.query("facts"),
	
	listeners: {
		load: species_loaded
	},
	
	reader: new Ext.data.JsonReader({   
	    root: 'species_list',
	    totalProperty: 'num_species',
	    id: 'sp_tsn'},
	    [ 
	        {name: 'sp_tsn', type: 'int'},
	        {name: 'entity_name', type: 'string', mapping: 'scientific_name'},
	        {name: 'group_field', type: 'string', mapping: 'obis_taxa'},
	        {name: 'profile', type: 'string'},
	        {name: 'status', type: 'string'},
	        {name: 'datasets', type: 'string'},
	        {name: 'extent', type: 'string'},
	        {name: 'sp_rank', type: 'string'},
	        {name: 'notes', type: 'string'},
	        {name: 'records', type: 'int'},
	        {name: 'pic_credit', type: 'string'},
	        {name: 'common_name', type: 'string'},
	        {name: 'pic_url', type: 'string'}
	  	]),
  	
  sortInfo:{field: 'entity_name', direction: "ASC"}
});


cm_species = new Ext.grid.ColumnModel(
[{
	id: 'entity_name',
    header: 'Scientific name',
    readOnly: true,
    dataIndex: 'entity_name',
    width: 180,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		var species_url = '/species/tsn/' + record.data.sp_tsn;
   		var text = "<a href='" + species_url + "' title='Go to Species Profile Page' onmousedown='cancel_bubble(event);' onclick='cancel_bubble(event);'>" + value + "</a>";
    	return text;
    }
  },{
    header: 'Common name',
    readOnly: true,
    dataIndex: 'common_name',
    width: 180
  },{
    header: 'Status',
    readOnly: true,
    dataIndex: 'status',
    align: "center",
    tooltip: "Protected status under US Endangered Species Act",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	switch (value) {
    		case "T":
    			var text = "Threatened";
    			break;
	    	case "E":
    			var text = "Endangered";
    			break;
    		default:
    			var text = "";
    	}
    	return text;
    },
    width: 100
  },{
    header: '#obs. in area',
    id: 'obs_in_area',
    //readOnly: true,
    dataIndex: 'records',
    align: "right",
    tooltip: "#observations",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	var num_obs = store.reader.jsonData.num_obs;
   		var text = int_format(num_obs[record.data.sp_tsn]);
    	return text;
    },
    width: 120
  },{
    header: '#obs.',
    readOnly: true,
    dataIndex: 'records',
    align: "right",
    tooltip: "#observations",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = int_format(value);
    	return text;
    },
    width: 80
  },{
    header: '#datasets',
    readOnly: true,
    dataIndex: 'datasets',
    align: "right",
    tooltip: "#datasets",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = int_format(value);
    	return text;
    },
    width: 80
  },{
    header: 'Illustration',
    readOnly: true,
    dataIndex: 'pic_url',
    resizable: false,
    fixed: true,
    sortable: false,	
    menuDisabled: true,
    align: "center",
    tooltip: "Species illustration",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		if (record.data.pic_credit != "") {
			var title = "Courtesy: " + record.data.pic_credit;
		} else {
			var title = "";
		}
		if (value != "" && record.data.notes == "") {
			var text = "<img src='" + value + "/variant/thumbnail' width='105' title='" + title + "'>";
		} else {
			var text = "";
		}
    	return text;
    },
    width: 115
  },{
    header: 'SEAMAP Taxa',
    readOnly: true,
    dataIndex: 'group_field',
    width: 10,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	if (["marine mammals","seabirds", "sea turtles"].indexOf(value.toLowerCase()) != -1) {
    		var text = value.capitalize();
    	} else {
    		var text = "Others";
    	}
    	return text;
    },
	hidden: true
  }
]);
cm_species.defaultSortable= true;

gv_species = new Ext.grid.GroupingView({
	groupTextTpl: '{group} ({[values.rs.length]})'
});


/* Dataset Grid */
store_dataset = new Ext.data.GroupingStore({
	groupField: "group_field",
	id: 'dataset_store',
	remoteGroup: true,
	remoteSort: true,
  
	proxy: new Ext.data.HttpProxy({
            url: g_ROOT_URL + '/functions/contributing_datasets',
            method: 'POST'
        }),
	baseParams: gQuery.query("facts"),
	
	listeners: {
		load: dataset_loaded
	},
	
	reader: new Ext.data.JsonReader({   
	    root: 'dataset_list',
	    totalProperty: 'num_datasets',
	    id: 'id'},
	    [ 
	        {name: 'id', type: 'string'},
	        {name: 'entity_name', type: 'string', mapping: 'name_short'},
	        {name: 'group_field', type: 'string', mapping: 'md_provider'},
	        {name: 'sources', type: 'string'},
	        {name: 'ds_type', type: 'string'},
	        {name: 'reptilia_count', type: 'int'},
	        {name: 'aves_count', type: 'int'},
	        {name: 'mammalia_count', type: 'int'},
	        {name: 'num_records', type: 'int'},
	        {name: 'yr_begin', type: 'int'},
	        {name: 'yr_end', type: 'int'},
	        {name: 'date_begin', type: 'string'},
	        {name: 'date_end', type: 'string'},
	        {name: 'platform', type: 'string'},
	        {name: 'longitude_max', type: 'float'},
	        {name: 'longitude_min', type: 'float'},
	        {name: 'latitude_max', type: 'float'},
	        {name: 'latitude_min', type: 'float'},
	        {name: 'urlimg_s', type: 'string'},
	        {name: 'table2', type: 'string'},
	        {name: 'relation', type: 'string'},
	        {name: 'auto', type: 'string'},
	        {name: 'added', type: 'string'},
	        {name: 'updated', type: 'string'}
	  	]),
  	
  sortInfo:{field: 'entity_name', direction: "ASC"}
});


cm_dataset = new Ext.grid.ColumnModel(
[{
	id: 'entity_name',
    header: 'Dataset name',
    readOnly: true,
    dataIndex: 'entity_name',
    width: 200,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		switch (record.data.id) {
			case 415:
				var dataset_url = "/widecast";
				break;
			default:
				var dataset_url = '/datasets/detail/' + record.data.id;
				break;
		}
   		var text = "<a href='" + dataset_url + "' title='Go to Dataset Page' onmousedown='cancel_bubble(event);' onclick='cancel_bubble(event);'>" + value + "</a>";
    	return text;
    }
  },{
    header: 'Map',
    readOnly: true,
    dataIndex: 'id',
    sortable: false,
    resizable: false,
    menuDisabled: true,
    fixed: true,
    align: 'center',
    //tooltip: "",
    width: 56,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = "<a><img src='/seamap2/images/datasets/dataset_" + value + "_s.png' title='Map this dataset with Advanced Onilne Mapper'></a>";
    	return text;
    }
  },{
    header: 'Platform',
    readOnly: true,
    dataIndex: 'platform',
    tooltip: "Platform",
    align: "center",
    width: 75
  },{
    header: 'Year',
    readOnly: true,
    dataIndex: 'yr_begin',
    align: "center",
    tooltip: "Range fo survey",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	if (value == record.data.yr_end) {
    		var text = value;
    	} else {
    		var text = value + "-"  + record.data.yr_end;
    	}
    	return text;
    },
    width: 95
  },{
    header: '<img src="/seamap2/icons/bird_w30.gif" height="21">',
    readOnly: true,
    dataIndex: 'aves_count',
    align: "right",
    tooltip: "#obs of Searbirds",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = int_format(value);
    	return text;
    },
    width: 75
  },{
    header: '<img src="/seamap2/icons/mammal_w30.gif" height="22">',
    readOnly: true,
    dataIndex: 'mammalia_count',
    align: "right",
    tooltip: "#obs of Marine mammals",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = int_format(value);
    	return text;
    },
    width: 70
  },{
    header: '<img src="/seamap2/icons/turtle_w30.gif" height="22">',
    readOnly: true,
    dataIndex: 'reptilia_count',
    align: "right",
    tooltip: "#obs of Sea turtles",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = int_format(value);
    	return text;
    },
    width: 70
  },{
    header: ' ',
    readOnly: true,
    dataIndex: 'sources',
    tooltip: "Data source/Customized interface",
    sortable: false,
    resizable: false,
    menuDisabled: true,
    fixed: true,    
    align: 'center',
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		switch (value) {
			case "Satellite Tracking and Analysis Tool":
				var text = "<img src='" + gIconBase + "stat_small.gif' title='Data fed from " + value + "' width=20>";
				break;
			case "WIDECAST":
			case "ESAS":
				var text = "<img src='" + gIconBase + "custom_app.png' title='Customized application available'>";
				break;
			default:
				var text = "";
		}
		return text;
    },
    width: 36
  },{
    header: 'SEAMAP Taxa',
    readOnly: true,
    dataIndex: 'group_field',
    width: 10,
	hidden: true
  }
]);
cm_dataset.defaultSortable= true;

gv_dataset = new Ext.grid.GroupingView({
	groupTextTpl: '{group} ({[values.rs.length]})'
});

Ext.onReady(function(){
    grid_species = 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_species",
        height:240,
        title:'Species',
        header: false,
        store: store_species,
        trackMouseOver:true,
        loadMask: true,
		autoHeight: false,
		cm: cm_species,
		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
		stateful: false,
		cls: "grid",
		ctCls: "grid",
	    view: gv_species
    });
    
    grid_dataset = 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_dataset",
        height:240,
        title:'Datasets',
        header: false,
        store: store_dataset,
        trackMouseOver:true,
        loadMask: true,
		autoHeight: false,
		cm: cm_dataset,
		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
		stateful: false,
		cls: "grid",
		ctCls: "grid",
	    view: gv_dataset
    });
    	
    var tabs_sp_ds = new Ext.TabPanel({
        renderTo: "tab_frame",
        id: "tabs_sp_ds",
        activeTab: 0,
        border: true,
        bodyBorder: true,
        width:800,
        height: 250,
        plain:true,
        tabPosition: "bottom",
        stateful: true,
        items: [grid_species, grid_dataset]
    });
    
    init();
    
    var tip_defaults = {
        title: ' ',
        width: 400,
        autoHide: true,
        closable: true,
        showDelay: 1300,
        hideDelay: 20000,
        dismissDelay: 20000,
        listeners: {
        	beforeshow: close_tooltip
        },
        bodyStyle: "color: #666666; text-align: left"    	
    };
    
    var create_map = $H(tip_defaults).merge({target: 'fp_create_map', id: "tooltip_create_map", contentEl: "div_tip_create_map"}).toObject();
    var contribute = $H(tip_defaults).merge({target: 'fp_contribute', id: "tooltip_contribute", contentEl: "div_tip_contribute"}).toObject();
    var by_species = $H(tip_defaults).merge({target: 'fp_by_species', id: "tooltip_by_species", contentEl: "div_tip_by_species"}).toObject();
    var by_location = $H(tip_defaults).merge({target: 'fp_by_location', id: "tooltip_by_location", contentEl: "div_tip_by_location"}).toObject();
    var by_dataset = $H(tip_defaults).merge({target: 'fp_by_dataset', id: "tooltip_by_dataset", contentEl: "div_tip_by_dataset"}).toObject();
    var species_search = $H(tip_defaults).merge({target: 'fp_species_search', id: "tooltip_species_search", contentEl: "div_tip_search_species"}).toObject();
    
    new Ext.ToolTip(create_map);
    new Ext.ToolTip(contribute);
    new Ext.ToolTip(by_species);
    new Ext.ToolTip(by_location);
    new Ext.ToolTip(by_dataset);
    new Ext.ToolTip(species_search);

   	grid_species.render();
   	grid_species.on("rowclick", select_species);

});

/**** initialize page *****/
function init() {
	update_layout("map");
	update_layout("taxa");
	
	var url = gPlone + 'getSpecies';
	var parseFunc = parseSpecies;	// Defined in auto_suggest.js
	var aAutoSuggestSp = new AutoSuggest("species", "result_list", species_changed);
	aAutoSuggestSp.SearchOptions = {record_count:1};
	aAutoSuggestSp.setFilter(url, parseFunc);

	// Register Navigation Tools.
	$$('img.NavTool').each(function (item) {NavigationTools.add(item);});

	//
	$$('img.ImgButton').each(function (item) {
		item.observe('mouseover', function (event) {
			if (!$(item).hasClassName('selected')) {
				item.src = gIconBase + item.id + '_hover.png';
			}
		});
		item.observe('mouseout', function (event) {
			if (!$(item).hasClassName('selected')) {
				item.src = gIconBase + item.id + '.png';
			}
		});});

	// Get the observation/datasets counts
	get_seamap_summary();

	
	gMapserver = new Mapserver(gUrlPhp, "");
	initialize_mapfile();	
}

function choose_layer(zoom, update_legend) {
	var layer_name = "dist_";

	if (gQuery.sp_tsn.length != 0 || gQuery.sp_tsns.length != 0) {
		layer_name += "sp_";
	} else {
		layer_name += "taxa_";
	}
	if (zoom >= gZoom['001']) {
		var cellsize = "001";
	} else if (zoom >= gZoom['01']) {
		var cellsize = "01";
	} else {
		var cellsize = "1";
	}
	layer_name += cellsize + "deg";

	if (update_legend) {
		choose_legend(layer_name, cellsize);
	}
	return layer_name;
}


/***** Taxa select *****/
function taxa_select(button, taxa) {
    gQuery.taxaColumn = taxa;	// [all_taxa|aves|mammalia|reptilia]

    var layer_name = choose_layer(map.getZoom(), false);
    update_dist_layers();
	
	$$("img.taxa_button").each(function (item) {
		$(item).removeClassName('selected');
		$(item).src = gIconBase + $(item).id + '.png';
	});
	$(button).src = gIconBase + $(button).id + "_selected.png";
	$(button).addClassName('selected');
}

function update_layout (mode) {
	$('result_list').hide();
	switch (mode) {
		case "map":
			break;
		case "taxa":
			$$('.species_info').each(function (item) {$(item).hide()});
			$$('tr.taxa_info').each(function (item) {$(item).setStyle({display:gTableRow})});
			$$('td.taxa_info').each(function (item) {$(item).setStyle({display:gTableCell})});
			$("info_frame").hide();
			break;
		case "species":
			$$('.taxa_info').each(function (item) {$(item).hide()});
			$$('tr.species_info').each(function (item) {$(item).setStyle({display:gTableRow})});
			break;
	}
}

function species_changed() {
	gQuery.temporal = "";
	gQuery.sp_tsn = [];
	
	if ($('result_list').visible()) {
		$('result_list').hide();
	}

	if ($F('species') != "") {
		var mode = "species";
		var species = $F('species');
		// Need to find children species, if any.
		var sp_tsn = species_search(species);	// species_search accepts either name or TSN number

		if (sp_tsn == "") {
			alert("No species found");
			return true;
		}
	} else {
		var mode = "taxa";
		gQuery.sp_tsns = [];
	}

	if ($F('species') == "" && gROIs.length == 0) {
		update_summary();
	} else {
		get_species();
		get_contributing_datasets();
	}
	
	update_layout(mode);
	update_dist_layers();
}

function get_species() {
	var s = '<img src="' + gIconBase + 'ajax_loader.gif">';
	$('aves_count', 'mammalia_count', 'reptilia_count', 'grand_total', 'species_count', 'record_count').invoke("update", s);

	columns_onoff();
		
	store_species.baseParams = gQuery.query("facts");
    var params = store_species.baseParams;
    params["start_at"] = 0;
    params["num_species"] = -1;
    params["order_by"] = "obis_taxa, max(species_profiles.scientific_name)";
    params["species_only"] = true;
    
	store_species.load({params: params});
}

function columns_onoff() {
	if (gQuery.spatial == "") {
		// hide [#obs. in area]
		cm_species.setHidden(3, true);		
		cm_species.setHidden(4, false);		
		cm_species.setHidden(5, false);				
	} else {
		cm_species.setHidden(3, false);		
		cm_species.setHidden(4, true);		
		cm_species.setHidden(5, true);				
	}
	
}

function species_loaded(theStore, records, options) {
	if (!$("info_frame").visible()) {
		$("info_frame").show();
	}
	
	store_species.remoteGroup = false;
	store_species.remoteSort = false;
	$('species_count').update(theStore.reader.jsonData.num_species);

	var species = theStore.reader.jsonData.species_list;
	var num_obs = theStore.reader.jsonData.num_obs;
	var num_taxa = {'seabirds': 0, 'marine mammals': 0, 'sea turtles': 0, 'others': 0};
	for (var i = 0; i < species.length; i++) {
		var species_i = species[i];
		var taxa = species[i].obis_taxa;
		if (taxa == "") {
			taxa = "others";
		}		
		if (species_i.records != "") {
			if (num_obs != "undefined" && typeof(num_obs[species_i.sp_tsn]) != "undefined") {
				//records =  int_format(num_obs[species_i.sp_tsn]) + "/" + records;
				num_taxa[taxa] += num_obs[species_i.sp_tsn];
			}
		}
	}
	$('aves_count').update(int_format(num_taxa['seabirds']));
	$('mammalia_count').update(int_format(num_taxa['marine mammals']));
	$('reptilia_count').update(int_format(num_taxa['sea turtles']));
	$('grand_total').update(int_format(num_taxa['seabirds'] + num_taxa['marine mammals'] + num_taxa['sea turtles']));

	if (gROIs.length != 0) {
		grid_species.getView().refresh();
	}
	grid_species.syncSize();
}


function get_seamap_summary() {
	gQuery.sp_tsn = [];
	
	var url = gPlone + "getSeamapSummary";
	new Ajax.Request(url,
		{
			method: 'GET',
			onSuccess: show_seamap_summary
		});
}

function show_seamap_summary(oj) {
	gSeamapSummary = oj.responseText.evalJSON();	// data are returned formatted.
	update_summary();
}

function update_summary() {
	var keys = ['aves_count', 'mammalia_count', 'reptilia_count', 'grand_total', 'dataset_count'];
	keys.each(function(item) {$(item).update(gSeamapSummary[item]);});
	$('species_count').update(gSeamapSummary.num_species);	
}

function species_search_results(oj) {		// EXT JS version
	var species_info = oj.responseText.evalJSON();
	var species = species_info.species_list;
	gQuery.sp_tsns = [];
	for (var i=0; i < species.length; i++) {
		gQuery.sp_tsns.push(species[i]['sp_tsn']);
	}

	return gQuery.sp_tsns;
}

function roi_updated() {
	gQuery.temporal = "";
	
	var mode = "species";
	if (gROIs.length == 0 && gQuery.sp_tsns.length == 0 && gQuery.sp_tsn.length == 0) {
		var mode = "taxa";	// Hide Grids
		update_summary();
	} else if (gQuery.sp_tsn.length != 0) {
		get_contributing_datasets();
	    var params = gQuery.query("facts");
	    params["start_at"] = 0;
	    params["num_species"] = -1;
	    params["order_by"] = "obis_taxa, max(species_profiles.scientific_name)";
	    params["species_only"] = true;
	    store_species.proxy.load(params, store_species.reader, function(records, args, status) {
	    	if (records.records.length > 0) {
	    		species_loaded(store_species, records, null);
	    	}
	    });		
	} else {
		get_contributing_datasets();
		get_species();
	}
	
	update_layout(mode);
	columns_onoff();
	update_dist_layers();
}

function get_contributing_datasets() {
	var s = '<img src="' + gIconBase + 'ajax_loader.gif">';
	$('dataset_count').update(s);
	store_dataset.baseParams = gQuery.query("facts");
    var params = store_dataset.baseParams;
    
	store_dataset.load({params: params});			
}

function dataset_loaded(theStore, records, options) {
	theStore.remoteGroup = false;
	theStore.remoteSort = false;

	if (options.params.provider_list == 1) {
		var store_provider = grid_provider.store;
		store_provider.removeAll();
		var providers = theStore.reader.jsonData.providers;
		var records = store_provider.reader.readRecords(providers);
		store_provider.add(records.records);
		
		// Update #datasets
		//update_num_datasets();
	}
		
	var datasets = theStore.reader.jsonData.dataset_list;
	var num_obs = theStore.reader.jsonData.num_obs;
	if (typeof(num_obs['total']) == "number") {		// for species
		$('record_count').update(int_format(num_obs['total']));
	} else {
		["aves", "mammalia", "reptilia"].each(function(item) {$(item + "_count").update(int_format(num_obs[item]));});
		$('grand_total').update(int_format(num_obs.grand_total));
	}
	$('dataset_count').update(int_format(datasets.length));
	
}


function select_species(theGrid, rowIndex, e) {
	var row = theGrid.store.getAt(rowIndex);
	if (theGrid.selModel.isSelected(rowIndex)) {
		var sp_tsn = row.data.sp_tsn;
		gQuery.sp_tsn = [sp_tsn];
	} else {
		gQuery.sp_tsn = [];
	}
	roi_updated();
	
}

function close_tooltip() {
	var tooltips = ["tooltip_create_map", "tooltip_contribute", "tooltip_by_species", "tooltip_by_location", "tooltip_by_dataset", "tooltip_species_search"];
	
	tooltips.each(function(item){
		var tooltip = Ext.getCmp(item);
		if (tooltip != null && tooltip.isVisible()) {
			tooltip.hide();
		}
	});
}

function window_resize() {
	var max_map_width = 1150;
	var window_width = GetWindowSize("width");
	if ($("visual-portal-wrapper")) {	// Plone 3 site
		if (window_width > max_map_width) {
			var wrapper_margin = (window_width - max_map_width) / 2;
		} else {
			var wrapper_margin = 0;
		}
		$("visual-portal-wrapper").setStyle({"marginRight": wrapper_margin + "px", "marginLeft": wrapper_margin + "px"}); // Fixed width, centered.
	}	
	
	var app_box_width = $("app_box").getWidth();
	var info_box_width = 175;
	var buffer = 8;
	$("td_map").setStyle({width: (app_box_width - info_box_width - buffer) + "px"});
	if (Ext.getCmp("tabs_sp_ds")) {
		Ext.getCmp("tabs_sp_ds").setWidth(app_box_width - 10);	
	}
}
