/* EXT JS Layout: referred to in page_layout_v2_2 */
var store;
var cm;
var cm_simple;
var grid;
var grid_simple;


var gSpecies = null;	// info from getSpecies (species_profiles table)
var gDatasets = null;
var gNumObs = [];		// Holding the species-specific number of observations per dataset (not the total #obs of the dataset)
//var gLegendLoaded = false;
var gLegendItems = null;
var gRelatedLayerStatus = true;

// Notes gMapserver, gActiveLayer, gLayerName are defined in dist_map_common.js


// Initialize EXT JS store, reader, ColumnModel
store = 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: data_loaded
	},
	reader: new Ext.data.JsonReader({   
    root: 'dataset_list',
    totalProperty: 'num_datasets',
    id: 'id'},
    [ 
        {name: 'entity_name', type: 'string', mapping: 'name_short'},
        {name: 'ds_type', type: 'string'},
        {name: 'id', type: 'int'},
        {name: 'platform', type: 'string'},
        {name: 'group_field', type: 'string', mapping: 'md_provider'},
        {name: 'table2', type: 'string'},
        {name: 'num_records', type: 'int'},
        {name: 'yr_begin', type: 'int'},
        {name: 'yr_end', type: 'int'},
        {name: 'sources', type: 'string'},
        {name: 'urlimg_s', type: 'string'},
        {name: 'auto', type: 'string'},
        {name: 'aves_count', type: 'int'},
        {name: 'mammalia_count', type: 'int'},
        {name: 'reptilia_count', type: 'int'},
        {name: 'data_extent', type: 'string'}
  	]),
  	
  sortInfo:{field: 'entity_name', direction: "ASC"}
});


cm = 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) {
   		var text = "<a href='/datasets/detail/" + record.data.id + "' title='Go to Dataset Page' onmousedown='cancel_bubble(event);' onclick='cancel_bubble(event);'>" + value + "</a>";
    	return text;
    }
  },{
    header: 'ID',
    readOnly: true,
    dataIndex: 'id',
    align: "right",
    width: 50
  },{
    header: 'Type',
    readOnly: true,
    dataIndex: 'ds_type',
    id: 'type',
    tooltip: "observations/tag/habitat/model",
    //tooltip: new Ext.ToolTip({target: 'x-grid3-td-type',  html: 'observations/tag/habitat/model'}),
    align: "center",
    width: 60
  },{
    header: 'Platform',
    readOnly: true,
    dataIndex: 'platform',
    tooltip: "boat/plane/tag/habitat",
    align: "center",
    width: 70
  },{
    header: 'Tracks',
    readOnly: true,
    dataIndex: 'table2',
    tooltip: "Survey effort/telemetry tracks",
    align: "center",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	if (value != "" && record.data.auto != "") {
    		var text = "Yes";
    	} else {
    		var text = "No";
    	}
    	return text;
    },
    width: 60
  },{
    header: 'Year',
    readOnly: true,
    dataIndex: 'yr_begin',
    tooltip: "Survey years",
    align: "center",
    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: 100
  },{
    header: '#obs.',
    readOnly: true,
    dataIndex: 'num_records',
    tooltip: "Number of observations (this species/all)",
    align: "right",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	var dataset = record.data.id;
    	var text = int_format(store.reader.jsonData.num_obs[dataset], false) + "/" + int_format(value, false);
    	return text;
    },
    width: 110
  },{
    header: '#animals.',
    readOnly: true,
    dataIndex: 'num_records',
    tooltip: "Number of animals",
    align: "right",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	var dataset = record.data.id;
    	var text = int_format(store.reader.jsonData.num_animals[dataset], false);
    	return text;
    },
    width: 110
  },{
    header: ' ',
    readOnly: true,
    dataIndex: 'data_extent',
    tooltip: "Click icon to zoom in",
    align: "center",
    sortable: false,
    menuDisabled: true,
    fixed: true,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	var text = "<img class='button' src='/seamap2/icons/icon_tool_fullextent.png' title='Zoom in to this dataset' onmousedown='cancel_bubble(event);' onclick='cancel_bubble(event); zoomToBOX3D(\"" + value + "\");'>";
    	return text;
    },
    width: 36
  },{
    header: 'Provider',
    readOnly: true,
    dataIndex: 'group_field',
    align: "right",
    width: 70,
     hidden: true
  }
]);
cm.defaultSortable= true;

cm_simple = new Ext.grid.ColumnModel(
[{
    header: 'Legend',
    readOnly: true,
    dataIndex: 'id',
    width: 22,
    hidden: true,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	if (gLegendItems != null) {
    		var src = gLegendItems["legend_" + record.data.id];
    	} else {
    		var src = "/seamap2/icons/blank.png";
    	}
   		var text = "<img src='" + src + "' id='legend_" + value + "'>";
    	return text;
    }
  },{
    header: 'Dataset name',
    readOnly: true,
    dataIndex: 'entity_name',
    //width: 230,
    autoWidth: true,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = "<a title='" + record.data.group_field + "'>" + value + "</a>";
    	return text;
    }
  },{
    header: 'Provider',
    readOnly: true,
    dataIndex: 'group_field',
    align: "right",
    width: 70,
    hidden: true
}]);


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

gv_simple = new Ext.grid.GridView({forceFit: true});

function data_loaded(theStore, records, options) {
	theStore.remoteSort = false;
	theStore.remoteGroup = false;
	
	$('summary_ds').update(theStore.data.length);
	$('summary_obs').update(int_format(theStore.reader.jsonData.num_obs['total'], false));
	reset_species_count();
	
	var year_min = 30000;
	var year_max = 0;
	
	for (var i = 0; i < records.length; i++) {
		var record = records[i];
		year_min = Math.min(year_min, parseInt(record.data.yr_begin));
		year_max = Math.max(year_max, parseInt(record.data.yr_end));
	}
	
	if (year_min == year_max) {
		var years = year_min;
	} else {
		var years = year_min + "-" + year_max;
	}
	$('summary_years').update(years);
}

/**** initialize page *****/
function init() {
	/***** 
		Notes: Loading Google Maps load() happens after get_dataset_info is finished (show_dataset_info).
	*****/
	gQuery.taxaColumn = "record_count";
	
	// Initialize Mapserver instance
	gMapserver = new Mapserver(gUrlPhp, "");

	// Register Navigation Tools.
	$$('img.NavTool').each(function (item) {NavigationTools.add(item);});
	
	// Get species basic information
	get_taxonomy(gQuery.sp_tsn[0]);
	//get_dataset_list(gTsn);
	
	new Draggable('div_chart',{zindex: 10, constraint:'horizontal',  starteffect:null, endeffect:null});
	new Draggable('scale_bar',{zindex: 101, constraint:'vertical',  starteffect:null, endeffect:null, onEnd: temporal_scale_dragged});
	
	document.forms['frm_options'].env_options[0].checked = true;
	$$('img.button').each(function (item) {
		item.observe('mouseover', function (event) {
			if (!$(item).hasClassName('button_selected')) {
				item.src = item.src.replace('.png', '_hover.png');
			}
		});
		item.observe('mouseout', function (event) {
			if (!$(item).hasClassName('button_selected')) {
				item.src = item.src.replace('_hover.png', '.png');
			}
		});});
	$$('img.tab_button').each(function (item) {
		item.observe('click', function (event) {
			button_onoff(item, 'img.tab_button');
		});
	});

	
	if ($("tab_multimedia") && !Ext.isIE) {
		// Somehow, coorilis flash plugin fails to load in IE when the enclosing DIV
		// has display:none at the time of page loading.
		// So, hide it here for Firefox. Do not hide for IE until the problem is fixed.
		$("tab_multimedia").hide();
	}
	
	// initialize_mapfile is called in show_species_info
	// get_taxonomy -> show_taxonomy -> get_species_info -> show_species_info
	// initialize_mapfile -> mapfile_initialized -> load -> map_loaded (if defined)
}


function get_species_info(sp_tsn) {
	// aves_count,mammalia_count,reptilia_count are added by defualt. no need to include in columns below.
	var parameters = $H({sp_tsn: sp_tsn, start_at: 0, num_species:1, profile:1}).toQueryString();
	var url = gPlone + "getSpecies?" + parameters;
	new Ajax.Request(url,
		{
			method: 'GET',
			onSuccess: show_species_info
		});
}

function show_species_info(oj) {
	var species_info = oj.responseText.evalJSON();
	var species = species_info.species_list[0];
	gSpecies = species;
	
	if (species.common_name != "") {
		var common_name = species.common_name;
	} else {
		var common_name = "";
	}
	
	if (species.synonyms != "") {
		$('synonyms').update(species.synonyms);
	}
	
	if (species.physical_id != "") {
		var physical_id = species.physical_id;
	} else {
		var physical_id = "";
	}
	
	switch (species.status) {
		case "E":
			var status = "Endangered";
			break;
		case "T":
			var status = "Threatened";
			break;
		default:
			var status = "-";
			break;
	}
	if (status != "-") {
		status = "<a href='http://www.fws.gov/endangered/' title='take you to USFWS site' target='external' style='color:#CFCFCF'><img src='" + gIconBase +  "us_fish_wildlife_logo_small.gif'> " + status + "</a>";
	}
	
	//$("obs_count").update(int_format(species.records, false));
	$('summary_tsn').update(species.sp_tsn);
	$('summary_status').update(status);
	//$('summary_obs').update(int_format(species.records, false));
	
	if (typeof(species.extent) != 'undefined' && species.extent != "") {
		var extent = species.extent.replace("BOX3D(", "");
		extent = extent.replace(")", "");
		extent = extent.split(",");
		var sw = extent[0].split(" ");
		var ne = extent[1].split(" ");
		$('summary_lat_min').update(parseFloat(sw[1]).toFixed(2));
		$('summary_lat_max').update(parseFloat(ne[1]).toFixed(2));
		$('summary_lon_min').update(parseFloat(sw[0]).toFixed(2));
		$('summary_lon_max').update(parseFloat(ne[0]).toFixed(2));
	}
	
	
	$('scientific_name').update(species.scientific_name);
	$('common_name').update(common_name);

	var profile_items = ['physical_id', 'physical_confusion', 'distribution', 'ecology_behavior', 'feeding_prey', 'threats_status', 'links', 'refs'];
	var item_labels = ['Physical Description / Field Identification', 'Can be Confused With', 'Distribution', 'Ecology and Behavior', 'Feeding and Prey', 'Threats and Status', 'Links', 'References'];	// Illustrations is removed
	var description = "";
	
	for (var i = 0; i < profile_items.length; i++) {
		var item = profile_items[i];
		if (species[item] != "") {
			description += "<h3>" + item_labels[i] + "</h3><div class='description'>" + species[item] + "</div>";
		} 
	}
	$('description').update(description);
	
	// Resize the provider logo.
	if (species.pic_url != "") {
		load_sized_image(species.pic_url, "species_pic", {width:260, height:250});
		load_sized_image(species.pic_url, "species_pic_small", {width:127, height:55});
		if (species.pic_credit != "") {
			$('species_pic').title = "Photo credit: " + species.pic_credit;
			$('species_pic_small').title = "Photo credit: " + species.pic_credit;
		}
	}

	// Initialize Google Maps here (Not called directly by window.onload)
	initialize_mapfile();
}

function get_taxonomy(sp_tsn) {
	var url = "/seamap2/main/seamap2.php?sp_tsn=" + sp_tsn;
	new Ajax.Request(url,
		{
			method: 'GET',
			onSuccess: show_taxonomy
		});
}

function show_taxonomy(oj) {
	var content = oj.responseText;
	$('taxonomy').update(content);
	
	get_species_info(gQuery.sp_tsn[0]);
}


function get_dataset_tooltip (aTag, dataid) {
	for (var i = 0; i < gDatasets.length; i++) {
		var dataset = gDatasets[i];
		var id = dataset.id;
		if (id == dataid) {
			var provider = dataset.md_provider;
			var name_short = dataset.name_short;
			aTag.title = name_short + ", " + provider;
			break;
		}
	}
}


function year_or_season_changed() {
	update_chart();
	time_range_changed();
}

function roi_updated() {
	gQuery.clearTemporal();
	if (gQuery.spatial != "") {
		var loading = "<img src='" + gIconBase + "ajax_loader.gif'>";
		$('dataset_count').update(loading);
		$('obs_count').update(loading);
		var parameters = $H({columns: "id, name_short, md_provider, num_records"}).toQueryString();
		parameters += "&" + gQuery.toQueryString('facts');
		var url = gPlone + "contributing_datasets?" + parameters;
		new Ajax.Request(url,
			{
				method: 'GET',
				onSuccess: update_dataset_list
			});
	} else {
		reset_species_count();
	}
	
	// EXT JS Version
	var env_type = radio_value("frm_options", "env_options");
	var env_time_range = radio_value("frm_options", "env_time_range_options");
	var graph_panel = Ext.getCmp("graph_and_env_panel");
	if (!graph_panel.hidden || (env_type != 'N' && env_time_range == 'sync')) {
		// if env_type != "N", update_point_layer or update_dist_layers is called by update_chart -> show_chart
		// so that env layer is always sync'ed with time range.
		update_chart();
	} else {
		if (gActiveLayer == 'point') {
			update_point_layer(custom_query_updated);
		} else {
			update_dist_layers();
		}
	}
}


function update_dataset_list(oj) {	// EXT JS version
	var datasets_info = oj.responseText.evalJSON();	// Returns an dictionary {'num_obs': ..., 'datasets': [...]}
	var dataset_list = datasets_info.dataset_list;
	var num_obs = datasets_info.num_obs;
	var num_animals = datasets_info.num_animals;
	var obs_count = 0;
	var animal_count = 0;
	
	if (gQuery.spatial == "" && gQuery.temporal == "") {
		reset_species_count();
	} else {
		$('dataset_count').update(int_format(dataset_list.length, false));
		if (grid.rendered) {
			var selModel1 = grid.selModel;
			selModel1.clearSelections();
		}
		var selModel2 = grid_simple.selModel;
		selModel2.clearSelections();
		
		for (var i = 0; i < dataset_list.length; i++) {
			var dataset = dataset_list[i];
			var id = dataset.id;
			obs_count += num_obs[id];
			animal_count += num_animals[id];
			if (grid.rendered) {
				var index_to_select = grid.store.indexOfId(id.toString());
				selModel1.selectRow(index_to_select, true);
			}
			var index_to_select = grid_simple.store.indexOfId(id.toString());
			selModel2.selectRow(index_to_select, true);
		}
		$('obs_count').update(int_format(obs_count, false));
		$('animal_count').update(int_format(animal_count, false));
	}
	
	// Get cursor back to 'default'. Here is the only place to get it work.
	map_cursor("default"); 
}


function reset_species_count() {		// EXT JS version
	if (gQuery.dataset.length == 0 && gQuery.datasets == "") {
		var dataset_count = store.data.length;
		var animal_count = store.reader.jsonData.num_animals['total'];
		var obs_count = store.reader.jsonData.num_obs['total'];	
		grid.selModel.clearSelections();
		grid_simple.selModel.clearSelections();
	} else {
		if (gQuery.dataset.length > 0) {
			var dataset_ids = gQuery.dataset;
			var dataset_count = gQuery.dataset.length;
		} else {
			var dataset_ids = gQuery.datasets.toString().split(",");
			var dataset_count = dataset_ids.length;
		}
	    var obs_count = dataset_ids.inject(0, function(acc, n) {
				return acc + store.reader.jsonData.num_obs[n];
	    	});
	    var animal_count = dataset_ids.inject(0, function(acc, n) {
				return acc + store.reader.jsonData.num_animals[n];
	    	});
		
	}
	$("obs_count").update(int_format(obs_count, false));
	$("animal_count").update(int_format(animal_count, false));
	$("dataset_count").update(dataset_count);
}

function count_type_changed(count_type) {
	gQuery.count_type = count_type;
	if (gActiveLayer == "dist") {
		update_dist_layers();	
	}
	
	// If the chart panel is open, update chart.
	var env_type = radio_value("frm_options", "env_options");
	var env_time_range = radio_value("frm_options", "env_time_range_options");
	var graph_panel = Ext.getCmp("graph_and_env_panel");
	if (!graph_panel.hidden || (env_type != 'N' && env_time_range == 'sync')) {
		update_chart();
	}
	
	// Update legend label in the graph panel.
	var labels = {"record": "#observations", "animal": "#animals"};
	$("legend_count_type").update(labels[count_type]);
}

function map_loaded() {
	window_resize();
	whole_extent();
	store.load();
	grid.render();
	grid.on("rowclick", row_clicked);
}

function whole_extent() {
	var extent = gSpecies.extent;
	zoomToBOX3D(extent);
}

function load_sized_image(url, image_id, params) {
	var logo = new Image;
	logo.onload = function (evt) {
		if ((logo.width / params.width) > (logo.height / params.height)) {
			if (logo.width > params.width) {
				$(image_id).setStyle({"width":params.width + "px", "height": "auto"});
			}
		} else {
			if (logo.height > params.height) {
				$(image_id).setStyle({"width": "auto", "height":params.height + "px"});
			} 
		}
		$(image_id).src = url;
	}
	logo.src = url;
}

function expand_taxa(class_name) {
	$$('tr.' + class_name).invoke("toggleClassName", "hide");
}

function update_chart() {
	// Update chart
	gQuery.clearTemporal();
	$('div_chart').style.left = 0 + "px";
	$('charts_div').update("<img src='" + gIconBase + "ajax_loader.gif' style='margin-left:310px; margin-top:25px'>");
	
	var oceano_type = radio_value("form_oceano", "y_axis");
	if (oceano_type != "obs") {
		get_oceano_chart(oceano_type);
	} else {	
		var parameters = gQuery.toQueryString('chart') + "&mode=sp";
		var url = gPlone + "dist_sp_chart_url?" + parameters;
	
		$('range_select').hide();
		new Ajax.Request(url,
			{
				method: 'GET',
				onSuccess: show_chart
			});
	}
}

function show_chart(oj) {
	var chart_data_list = eval(oj.responseText);
	
	$('charts_div').update("");
	gNumCharts = chart_data_list.length;
	$('charts_div').style.width = (950 * gNumCharts) + "px";
	
	for (var i = 0; i < gNumCharts; i++) {
		var image = document.createElement("IMG");
		image.src = chart_data_list[i].url;
		image.id = "chart_" + i;
		
		if (i > 0) {
			image.style.marginLeft = "10px";
		}
		$('charts_div').insert(image);
	}
	
	$('range_select').show();
	build_range_select(chart_data_list[0]);

	//var env_type = radio_value("frm_options", "env_options");
	//var env_time_range = radio_value("frm_options", "env_time_range_options");
	
	if (gActiveLayer == "point") {
		update_point_layer(custom_query_updated);
	} else {
		update_dist_layers();
	}

	if (gNumCharts > 1) {
		$("chart_page_control").show();
	} else {
		$("chart_page_control").hide();
	}
}

function switch_layer(layer_type) {
	var dist_layer = choose_layer(map.getZoom(), false);
	gMapserver.request("switch_layer", layer_switched.bindAsEventListener(this, layer_type),
		{
			layer_type: layer_type,
			dist_layer: dist_layer,
			point_layer: gLayerName,
			point_layer_id: gQuery.sp_tsn[0],
			point_layer_type: "species",
			publish: gQuery.publish
		}, "", {});
}

function layer_switched(oj, layer_type) {
	var class_name = "button_selected";
	var legend_points = $('legend_points');
	var legend_cellsize = $('legend_cellsize');
	switch (layer_type) {
		case "point":
			var msg = oj.responseText.evalJSON();
			gLayerName = msg.layer_name;
			update_point_layer(layer_updated.bindAsEventListener(this, "point"));
			legend_points.src = gIconBase + $('legend_points').id + "_selected.png";
			legend_points.addClassName(class_name);
			legend_cellsize.src = $('legend_cellsize').src.replace("_selected", "");
			legend_cellsize.removeClassName(class_name);
			break;
		case "dist":
			update_dist_layers();
			legend_points.src = gIconBase + $('legend_points').id + ".png";
			legend_points.removeClassName(class_name);
			legend_cellsize.addClassName(class_name);
			activate_layer(layer_type);
			break;
	}
	$$('input.radio_display_count').each(function(item){item.disabled = layer_type == "point"});	
}


function update_point_layer(updated) {		// EXT JS version
	if (gLayerName == "") {
		var layer_name = gQuery.sp_tsn[0];
	} else {
		var layer_name = gLayerName;
	}
	var where = gQuery.query('z_union');
	var time_range = get_env_time_range();
	if (time_range.start == "" || time_range.temporal == "") {
		alert("Wrong time range. Environmental layer won't show up.");
	}

	where["date_start"] = time_range.start;
	where["temporal_scale"] = time_range.temporal;
	var where_str = $H(where).toQueryString();
	
	gMapserver.request("custom_query", updated,
		{
			layer_name: layer_name,
			layer_type: "species",
			env_type: radio_value("frm_options", "env_options")
		}, where_str, {});
}


function activate_layer(layer_type) {		// EXT JS version
	gActiveLayer = layer_type;
	switch (layer_type) {
		case "point":
			var onoff = true;
			$("img_legend").hide();
			get_legend();
			break;
		case "dist":
			var onoff = false;
			$("img_legend").show();
			break;
	}
	
	legend_column_onoff(onoff);
}

// Override the same function in dist_map_common.js, so it takes care of selected state and the points button
function choose_legend(layer_name, cellsize) {
	if (gActiveLayer == "dist") {
		var count_type = gQuery.count_type;
		var legend_name = gIconBase + "legend_" + layer_name + "_" + count_type + ".png";
		if (legend_name != $('img_legend').src) {
			$('img_legend').src = legend_name;
		}
	
		var legend_cellsize = gIconBase + "legend_cellsize_v2_" + cellsize + "_selected.png";
		if (legend_cellsize != $('legend_cellsize').src) {
			$('legend_cellsize').src = legend_cellsize;
		}
	}
}

function time_range_changed() {
	// Called from slider_dropped() in seamap2_common.js
	// Nothing to do if the map shows distribution. Map update is taken care of update_map.
	// For point observations, need to change DATA in mapfile here.
	var loading = "<img src='" + gIconBase +  "ajax_loader.gif'>";
	$('dataset_count', 'obs_count').invoke('update', loading);
	
	if (gQuery.spatial != "" || gQuery.temporal != "" || gQuery.dataset.length > 0) {
		var parameters = $H({columns: "id, name_short, md_provider, num_records"}).toQueryString();
		parameters += "&" + gQuery.toQueryString('facts');
		var url = gPlone + "contributing_datasets?" + parameters;
		new Ajax.Request(url,
			{
				method: 'GET',
				onSuccess: update_dataset_list
			});
	} else {
		reset_species_count();
	}

	if (gActiveLayer == 'point') {
		update_point_layer(custom_query_updated);
	} else {
		update_dist_layers();
	}
}


function get_legend() {		// EXT JS version
	if (gLegendItems == null) {
		gMapserver.request("get_legend_for_dataset_detail", show_legend,
			{
				layer_name: gLayerName
			}, "", {});
	}
}


function show_legend(oj) {		// EXT JS version
	var legend_text = oj.responseText;
	legend_text = legend_text.substr(legend_text, legend_text.length - 1);
	var legend_items = eval("[" + legend_text + "]");
	gLegendItems = {};
	
	for (var i = 0; i < legend_items.length; i++) {
		var legend_item = legend_items[i];
		if ($('legend_' + legend_item.class_name)) {
			// Legend may contain icons for unpublished datasets. Skip them as they are not listed.
			$('legend_' + legend_item.class_name).src = legend_item.icon;
			gLegendItems['legend_' + legend_item.class_name] = legend_item.icon;
		}
	}
}


function download_chart_data() {
	var oceano_type = radio_value("form_oceano", "y_axis");
	if (oceano_type != "obs") {
		var url = get_oceano_chart(oceano_type, 1);
	} else {			
		var parameters = gQuery.toQueryString('chart') + "&mode=sp";
		var url = gPlone + "dist_sp_chart_url?" + parameters + "&download=1";
	}
	window.open(url, "download");
}

function effort() {
	var effort_ids = "";
	var delimiter = "";
	for (var i = 0; i < gDatasets.length; i++) {	
		var dataset = gDatasets[i];
		if (dataset.table2 != "") {
			effort_ids += delimiter + dataset.table2.replace("zd_", "");
			delimiter = ",";
		}
	}
	return effort_ids;
}