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

var gDataset = null;	// info from datasets
var gSpecies = null;	// species observed from species_itis
var gLegendItems = null;
var gRelatedLayerStatus = null;
var gChartType = 'obs';
var gSeriesMultiSelect = false;

// 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: 'species_store',
	remoteGroup: true,
	remoteSort: true,
  
	proxy: new Ext.data.HttpProxy({
            url: g_ROOT_URL + '/functions/getSpeciesList',
            method: 'POST',
			timeout: 180000            
        }),
	baseParams: {id: gQuery.dataset[0]},
	listeners: {
		load: data_loaded
	},
	reader: new Ext.data.JsonReader({   
	    root: '',
	    totalProperty: '',
	    id: 'sp_obs'}, // need to change it to sp_obs or something. Otherwise the same species with different sp_obs do not show up.
	    [ 
	        {name: 'entity_name', type: 'string', mapping: 'scientific_name'},
	        {name: 'sp_common', type: 'string'},
	        {name: 'display_name', type: 'string'},
	        {name: 'sp_tsn', type: 'int'},
	        {name: 'sp_class', type: 'string'},
	        {name: 'sp_family', type: 'string'},
	        {name: 'sp_genus', type: 'string'},
	        {name: 'group_field', type: 'int', mapping: 'class_order'},
	        {name: 'sp_rank', type: 'string'},
	        {name: 'sp_title', type: 'string'},
	        {name: 'record_count', type: 'int'},
	        {name: 'animal_count', type: 'int'},
	        //{name: 'class_order', type: 'string'},
	        {name: 'sp_obs', type: 'string'},
	        {name: 'data_extent', type: 'string'}
	  	]),
  	
  sortInfo:{field: 'entity_name', direction: "ASC"}
});


cm = new Ext.grid.ColumnModel(
[{
	id: 'entity_name',
    header: 'Species name',
    readOnly: true,
    dataIndex: 'entity_name',
    width: 200,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = "<a href='/species/tsn/" + record.data.sp_tsn + "' title='Go to Species Profile Page' onmousedown='cancel_bubble(event);' onclick='cancel_bubble(event);'>" + value + "</a>";
    	return text;
    }
  },{
    header: 'Common',
    readOnly: true,
    dataIndex: 'sp_common',
    //tooltip: "",
    width: 200,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	if (record.data.display_name != "") {
   			var text = record.data.display_name;
    	} else {
    		var text = value;
    	}
    	return text;
    }
  },{
    header: 'Rank',
    readOnly: true,
    dataIndex: 'sp_rank',
    tooltip: "Taxonomic rank",
    width: 100
  },{
    header: 'Family',
    readOnly: true,
    dataIndex: 'sp_family',
	hidden: true,
    tooltip: "Family the species belongs to",
    width: 70
  },{
    header: 'Genus',
    readOnly: true,
    dataIndex: 'sp_genus',
	hidden: true,
    tooltip: "Genus the species belongs to",
    width: 70
  },{
    header: 'Name recorded',
    readOnly: true,
    dataIndex: 'sp_obs',
    tooltip: "Data provider's species ID/name",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	if (record.data.sp_title != "") {
    		var text = record.data.sp_title;
    	} else {
    		var text = value;
    	}
    	return text;
    },
    width: 200
  },{
    header: 'ITIS#',
    readOnly: true,
    dataIndex: 'sp_tsn',
    align: "right",
    tooltip: "Taxonomic Serial Number by ITIS",
    width: 70
  },{
    header: '#obs.',
    readOnly: true,
    dataIndex: 'record_count',
    tooltip: "Number of observations",
    align: "right",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	var text = int_format(value, false);
    	return text;
    },
    width: 70
  },{
    header: "#animals",
    readOnly: true,
    dataIndex: 'animal_count',
    tooltip: "Number of animals",
    align: "right",
    //hidden: true,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	var text = int_format(value, false);
    	return text;
    },
    width: 80
  },{
    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: 'SEAMAP Taxa',
    readOnly: true,
    dataIndex: 'group_field',
    width: 10,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	var taxa_labels = ["Marine mammals","Seabirds", "Sea turtles", "Others"];
    	var text = taxa_labels[value - 1];
    	return text;
    },
	hidden: true
  }
]);
cm.defaultSortable= true;

cm_simple = new Ext.grid.ColumnModel(
[{
    header: 'Legend',
    readOnly: true,
    dataIndex: 'sp_tsn',
    width: 22,
    hidden: true,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	if (gLegendItems != null) {
    		var src = gLegendItems["legend_" + record.data.sp_tsn];
    	} else {
    		var src = "/seamap2/icons/blank.png";
    	}
   		var text = "<img src='" + src + "' id='legend_" + value + "'>";
    	return text;
    }
  },{
    header: 'Scientific name',
    readOnly: true,
    dataIndex: 'entity_name',
    autoWidth: true,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	if (record.data.sp_title != "") {
    		var text = record.data.sp_title;
    	} else {
	    	if (record.data.sp_obs.toLowerCase() != record.data.sp_common.toLowerCase() && record.data.sp_obs.toLowerCase() != record.data.entity_name.toLowerCase()) {
	    		var text = record.data.sp_common + " (" + record.data.sp_obs + ")";
	    	} else {
	    		var text = record.data.sp_common;
	    	}
    	}
    	
   		var text = "<a title=\"" + text + "\">" + value + "</a>";
    	return text;
    }
  },{
    header: 'SEAMAP Taxa',
    readOnly: true,
    dataIndex: 'group_field',
    width: 10,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	var taxa_labels = ["Marine mammals","Seabirds", "Sea turtles", "Others"];
    	var text = taxa_labels[value - 1];
    	return text;
    },
    hidden: true
}]);

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

gv_simple = new Ext.grid.GroupingView({
	groupTextTpl: '{group}',
	forceFit: true
});

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

/**** initialize page *****/
function init() {
	// Dataset page shows Terms of Use on page load. When agreed, it's saved in a cookie (session level).
	var cp = new Ext.state.CookieProvider({
		path: "/",
		expires: null, // At the end of session
		domain: g_ROOT_URL.replace("http://", "")
	});
	Ext.state.Manager.setProvider(cp);
   	
	if (cp.get("__SEAMAP_agreed2terms", "") != "true") {
		show_terms_of_use();
	}
	
	/***** 
		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 dataset's basic information. Google Maps is loaded after get_dataset_info is finished. 
	get_dataset_info(gQuery.dataset[0]);
	
	// Get contact info
	get_dataset_contacts(gQuery.dataset[0]);

	// the species list may or may not be loaded for zd_427 with FF3 
	// when get_species_list is called in init(). So call it in show_dataset_info (after calling initialize_mapfile).
	//get_species_list(gDatasetID);
	
	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});
		
	$$('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');
		});
	});
}


function get_dataset_info(dataset_id) {
	// aves_count,mammalia_count,reptilia_count are added by defualt. no need to include in columns below.
	var parameters = "id=" + dataset_id;
	var url = gPlone + "getDatasetInfo?" + parameters;
	new Ajax.Request(url,
		{
			method: 'GET',
			onSuccess: show_dataset_info
		});
}

function show_dataset_info(oj) {
	var datasets = eval(oj.responseText);
	dataset = datasets[0];
	gDataset = dataset;
	
	if (dataset.provider_logo != "") {
		var provider_logo = "<img src='' id='provider_logo' border=0> ";
	} else {
		var provider_logo = "";
	}
	if (dataset.provider_url != "") {
		md_provider = "<a href='" + dataset.provider_url + "' target='provider'>" + provider_logo + dataset.md_provider + "</a>";
	} else {
		var md_provider = provider_logo + dataset.md_provider;
	}

	var show_effort_stat = false;
	if (dataset.table2 != "" && dataset.auto == 'TRUE') {
		var effort = "YES (ID: " + dataset.table2.replace("zd_", "") + ")";
		if (dataset.ds_type == 'ptobs') {
			$$('td.effort').each(function(item){$(item).style.display = gTableCell;});
			var show_effort_stat = true;
			var length_traveled = dataset.length_traveled;	// in km
			var effort_hours = dataset.effort_hours;			// in hour
		}
	} else {
		var effort = "N/A";
	}
	
	if (dataset.md_references != "") {
		var references = "<ul><li class='reference'>";
		references += dataset.md_references.replace(/\n/g, "<li class='reference'>");
		references += "</ul>";
	} else {
		var references = "N/A";
	}
	if (dataset.md_purpose != "") {
		var purpose = dataset.md_purpose;
	} else {
		var purpose = "N/A";
	}
	if (dataset.md_supplementalinfo != "") {
		var supplementalinfo = dataset.md_supplementalinfo;
	} else {
		var supplementalinfo = "N/A";
	}
	switch (dataset.ds_type) {
		case "ptobs":
			var line_title = "Effort";
			var data_type = "Animal sighting";
			break;
		case "pttag":
			var line_title = "Tracklines";
			$$('td.pttag').invoke("setStyle", {display: gTableCell});
			get_animals(dataset.id);
			var data_type = "Telemetry location";
			break;
		case "pthab":
			//var line_title = "Tracklines";
			$$('td.pthab').invoke("setStyle", {display: gTableCell});
			var data_type = "Habitat survey";
			grid.getColumnModel().setHidden(6, true);	// Hide zoom to extent column.
			break;
		case "ptacs":
			var line_title = "Effort";
			var data_type = "Acoustic";
			break;
		case "ptacs_calls":
			var line_title = "Effort";
			var data_type = "Acoustic Call";
			// change column header etc.
			var column_index = grid.getColumnModel().findColumnIndex('animal_count');
			grid.getColumnModel().setColumnHeader(column_index, '#calls');
			$("label_num_animals").update('#calls');
			break;
	}
			
	if (dataset.id == "427") {		// esas
		// ESAS should list all the platforms. For the time being, hand-write here.
		// Got the platforms from esas_base_type.
		var platform = "Ship<br/>Helicopter<br/>Aircraft<br/>Drilling rig<br/>Oil producing platform<br/>Gas producing platform<br/>Support vessel";
		
		if (gQuery.layer_type == 'esas') {
			var name_short = dataset.name_short + " (Logged in as ESAS Member)";
			gAgreedToTermsForDownload = true;	// defined in detail_common_v2_2; do not show Terms of Use popup for ESAS members.
		} else {
			var name_short = dataset.name_short + " (Log in to <a href='/login_form'>ESAS Data Providers Area</a>)";
		}
	} else {
		var platform = dataset.platform.capitalize();
		var name_short = dataset.name_short;
	}
	gYearStart = dataset.date_begin.substr(0, 4);
	var s = "<table cellpadding='3' class='summary_box'>";
	s += "<tr><td>SEAMAP ID</td><td>" + dataset.id + "</td></tr>";
	s += "<tr><td>Date, Begin</td><td nowrap>" + dataset.date_begin + "</td></tr>";
	s += "<tr><td>Date, End</td><td nowrap>" + dataset.date_end + "</td></tr>";
	s += "<tr><td>Latitude, Min</td><td>" + dataset.latitude_min + "</td></tr>";
	s += "<tr><td>Latitude, Max</td><td>" + dataset.latitude_max + "</td></tr>";
	s += "<tr nowrap><td>Longitude, Min</td><td>" + dataset.longitude_min + "</td></tr>";
	s += "<tr><td nowrap>Longitude, Max</td><td>" + dataset.longitude_max + "</td></tr>";
	s += "<tr><td>Platform</td><td nowrap>" + platform + "</td></tr>";
	s += "<tr><td>Data type</td><td nowrap>" + data_type + "</td></tr>";
	s += "<tr><td>" + line_title + "</td><td nowrap>" + effort + "</td></tr>";
	if (show_effort_stat) {
		s += "<tr><td>Traveled (km)</td><td nowrap>" + number_format(length_traveled, 2, ".", ",") + "</td></tr>";
		s += "<tr><td>Effort hours</td><td nowrap>" + number_format(effort_hours, 2, ".", ",") + "</td></tr>";
	}
	if (dataset.sources != "") {
		s += "<tr><td>Source</td><td>" + dataset.sources + "</td></tr>";
	}
	s += "<tr><td>Last updated</td><td>" + dataset.updated + "</td></tr>";
	s += "</table>";
	$('dataset_info').update(s);
	
	if (dataset.md_datacred != "") {
		var datacred = dataset.md_datacred;
	} else {
		var datacred = dataset.md_provider;
	}
	
	$('name_short').update(name_short);
	$('md_provider').update(md_provider);
	$('md_datacred').update(datacred);
	$('md_abstract').update(dataset.md_abstract);
	$('md_purpose').update(purpose);
	$('md_supplementalinfo').update(supplementalinfo);
	$('md_references').update(references);
	
	if (dataset.ds_type == "pthab") {
		$('num_colonies').update(int_format(dataset.num_records, false));
	} else {
		$('aves_count', 'mammalia_count', 'reptilia_count').each(function(item) {$(item).update(int_format(dataset[item.id], false))});
		$('grand_total').update(int_format(dataset.num_records, false));
	}
	
	// Resize the provider logo.
	load_sized_image(dataset.provider_logo, "provider_logo");

	// Initialize Google Maps here (Not called directly by window.onload)
	initialize_mapfile();
	
	// the species list may or may not be loaded for zd_427 with FF3 
	// when get_species_list is called in init(). So call it here instead.
	//get_species_list(gDatasetID);
}

function get_dataset_contacts(dataset_id) {
	// aves_count,mammalia_count,reptilia_count are added by defualt. no need to include in columns below.
	var parameters = "dataset_id=" + dataset_id;
	var url = gPlone + "getDatasetContacts?" + parameters;
	new Ajax.Request(url,
		{
			method: 'GET',
			onSuccess: show_dataset_contacts
		});
}

function show_dataset_contacts(oj) {
	var contacts = eval(oj.responseText);
	
	var s = "<table class='listing' style='margin-left:2em'>";
	s += "<thead><tr><th>Role</th><th>Name</th><th>Organization</th><th>&nbsp;</th></tr></thead>";
	s += "<tbody>";
	for (var i = 0; i < contacts.length; i++) {
		var contact = contacts[i];
		
		var roles = {"data-manager": "Primary contact", "data-entry": "Data entry", "secondary-contact": "Secondary contact"};
		var role = contact.role.toLowerCase();
		if (role in roles) {
			var role_label = roles[role];
		} else {
			var role_label = contact.role;
		}
		var name = [contact.firstname, contact.lastname].join(" ").strip();
		
		if (contact.email != "") {
			var email_link = "<a href='mailto:" + contact.email + "' title='bring up a new message with your default mail client'><img src='" + gIconBase + "icon_email.gif'></a>";
		} else {
			var email_link = "N/A";
		}
		
		if (contact.role.toLowerCase() == "data-manager") {
			name = "<a href='/providers/detail/" + contact.id + "' target='contact'>" + name + "</a>";
		}
		s += "<tr>";
		s += "<td>" + role_label + "</td>";
		s += "<td>" + name + "</td>";
		s += "<td>" + contact.org_name + "</td>";
		s += "<td align='center'>" + email_link + "</td>";
		s += "</tr>";
	}
	
	s += "</tbody></table>";
	
	$('md_contacts').update(s);
}


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

function roi_updated() {
	gQuery.clearTemporal();
	
	if (gQuery.spatial != "" || (gQuery.dataset[0] == 427 && gQuery.criteria != "")) {
		var loading = '<img src="' + gIconBase + 'ajax_loader.gif">';
		$('aves_count', 'mammalia_count', 'reptilia_count', 'grand_total').invoke('update', loading);
		update_obs_numbers();
	} else {
		reset_species_count();
	}
	
	if (gQuery.dataset[0] == 427 && $("tab_esas_trips") && $("tab_esas_trips").visible() && gEsasTrips.length == 0) {
		// do not reflesh provider/trip list when trips are chosen
		get_esas_trips(gEsasProvider, false);
	}

	// 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 (gDataset.ds_type != "pthab" && (!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') {
			if (gQuery.dataset[0] == 427 && gQuery.spatial == "" && gRelatedLayerStatus && gQuery.criteria == "") {
				alert("Due to the huge amount of data, tracks are only available when a region of interest or a trip is defined.\nThe tracks are turned off.");
				gMapserver.request("layer_onoff", function(){
						gRelatedLayerStatus = false;
						var lines_button = $('tracks');
						lines_button.removeClassName('button_selected');
						lines_button.src = gIconBase + lines_button.id + ".png";
					},
					{
						layer_name: gRelatedLayerName,
						status: "OFF"
					}, "", {asynchronous: false});
			}
			update_point_layer(custom_query_updated);
		} else {
			update_dist_layers();
		}
	}	
}


function update_species(oj) {
	var species_info = oj.responseText.evalJSON();
	var num_obs = species_info.num_obs;
	var num_animals = species_info.num_animals;
	var species_count = species_info.num_species;
	var species = species_info.species_list;
	var s = "";
	
	if (gQuery.spatial == "" && gQuery.temporal == "" && gQuery.series.length == 0 && gQuery.criteria == "") {
		reset_species_count();
	} else {
		var taxa_counts = {'marine mammals': 0, 'seabirds': 0, 'sea turtles': 0};
		
		if (grid.rendered) {
			var selModel1 = grid.selModel;
			selModel1.clearSelections();
		}
		var selModel2 = grid_simple.selModel;
		selModel2.clearSelections();
		
		if (gQuery.count_type == "record") {
			var counts = num_obs;
		} else {
			var counts = num_animals;
		}
		for (var i = 0; i < species.length; i++) {
			var the_species = species[i];
			var sp_tsn = the_species.sp_tsn;
			var taxa = the_species.obis_taxa;
			var count = counts[sp_tsn];
			taxa_counts[taxa] += count;
			//var index_to_select = grid.store.indexOfId(sp_tsn);	// the id is sp_obs.
			var index_to_select = grid.store.findBy(function(record, id) {return record.data.sp_tsn == sp_tsn});
			if (grid.rendered) {
				selModel1.selectRow(index_to_select, true);
			}
			//var index_to_select = grid_simple.store.indexOfId(sp_tsn);
			selModel2.selectRow(index_to_select, true);
		}
		
		$H({aves_count: "seabirds", mammalia_count: "marine mammals", reptilia_count: "sea turtles"}).each(function(pair){
			$(pair.key).update(int_format(taxa_counts[pair.value], false));
		});
		$('grand_total').update(int_format(counts['total'], false));
	}
		
	// Get cursor back to 'default'. Here is the only place to get it work.
	map_cursor("default"); 	
}

function reset_species_count() {
	var counts = {"aves_count": 0, "mammalia_count": 0, "reptilia_count": 0, "grand_total": 0};
	if (gQuery.sp_tsn.length == 0) {
		if (gQuery.count_type == "animal") {
			var suffix = "animal_count";
			counts["grand_total"] = gDataset.num_all_animals;
			counts["num_colonies"] = gDataset.num_all_animals;
		} else {
			var suffix = "count";
			counts["grand_total"] = gDataset.num_records;
			counts["num_colonies"] = gDataset.num_records;
		}
		["aves_", "mammalia_", "reptilia_"].each(function(item){
			counts[item + "count"] = gDataset[item + suffix];
		});
		grid.selModel.clearSelections();
		grid_simple.selModel.clearSelections();
	} else {
		var sp_tsns = gQuery.sp_tsn;
		for (i = 0; i < store.data.items.length; i++) {
			// For some datasets, there are multiple entries with the same sp_tsn, eapecially for higher taxon levels.
			// So don't break the loop.
			var species = store.data.items[i].data;
			// gQuery.sp_tsn can have multiple entries
			if (sp_tsns.indexOf(species.sp_tsn) >= 0) {
				counts[species.sp_class.toLowerCase() + "_count"] += species[gQuery.count_type + "_count"];
			}
		}
		counts["grand_total"] = counts["aves_count"] + counts["mammalia_count"] + counts["reptilia_count"];
	}	
	$H(counts).each(function(pair){
		$(pair.key).update(int_format(pair.value, false));
	});
}


function count_type_changed(count_type) {
	gQuery.count_type = count_type;
	if (gActiveLayer == "dist") {
		update_dist_layers();	
	}
	
	if (gQuery.spatial != "" || (gQuery.dataset[0] == 427 && gQuery.criteria != "")) {
		var loading = '<img src="' + gIconBase + 'ajax_loader.gif">';
		$('aves_count', 'mammalia_count', 'reptilia_count', 'grand_total').invoke('update', loading);
		update_obs_numbers();
	} else {
		reset_species_count();
	}

	// 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 (gDataset.ds_type != "pthab" && (!graph_panel.hidden || (env_type != 'N' && env_time_range == 'sync'))) {
		update_chart();
	}
	
	// Update legend label in the graph panel.
	var labels = {"record": "#observations", "animal": gDataset.ds_type == "ptacs_calls" ? "#calls": "#animals"};
	$("legend_count_type").update(labels[count_type]);
}

function map_loaded() {
	switch (gDataset.ds_type) {
		case "pthab":
			$$("tr.taxa_info").invoke("hide");
			$$("tr.pthab").invoke("setStyle", {display: gTableRow});
			$$('div.scalebar').invoke('hide');	
			$("range_select").hide();
			$('charts_div').update("");
			$$("div.chart_legend").invoke("hide");
			// run this before whole_extent so the dist layer is properly turned off.
			switch_layer("point");
			var url = BASE_URL + "seamap2/js/dataset_pthab_v2_2.js?v=0.29";
			load_javascript(url);
			break;
		case "model":
			gActiveLayer = "point";
			switch_layer("point");
			$("legend_points", "legend_cellsize").invoke("hide");
			$("img_legend").src = gIconBase + "legend_" + gDataset.id + ".png";
			break;
	}
	switch (gDataset.id) {
		case 427:
			// run this before whole_extent so the dist layer is properly turned off.
			var url = BASE_URL + "seamap2/js/dataset_zd_427_v2_2.js?v=7.31";
			load_javascript(url);
			break;
	}
	
	window_resize();
	whole_extent();
	store.load();
	grid.render();
	grid.on("rowclick", row_clicked);
}
  
function whole_extent() {
	zoomToSwNe(new GLatLng(gDataset.latitude_min, gDataset.longitude_min), new GLatLng(gDataset.latitude_max, gDataset.longitude_max), -1);
}

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

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

function update_chart() {
	if (gDataset.ds_type == "pthab") {	// Habitat type datasets do not show time series graph.
		//$$('div.scalebar').invoke('hide');	// Hide scalebar, slidebar in graph area.
		return true;
	}
	gQuery.clearTemporal();
	$('div_chart').style.left = 0 + "px";
	$('charts_div').update("<img src='" + gIconBase + "ajax_loader.gif' style='margin-left:250px; margin-top:25px'>");
	
	var oceano_type = radio_value("form_oceano", "y_axis");
	if (gDataset.ds_type == "ptacs" && gDataset.platform == "station") {
		if (oceano_type == "obs") {
			var legend_station = "block";
		} else {
			var legend_station = "none";
		}
		$$("td.legend_station").invoke("setStyle", {display: legend_station});
	}
	if (oceano_type != "obs" && gChartType != "effort") {
		get_oceano_chart(oceano_type, 0);
	} else {
		switch (gChartType) {
			case "obs":
				if (gQuery.series.length > 0) {
					var parameters = gQuery.toQueryString('chart_z_union');
					var mode = "series";
				} else {
					var parameters = gQuery.toQueryString('chart');
					var mode = "sp";
				}
				parameters += "&mode=" + mode;
				var url = gPlone + "dist_sp_chart_url?" + parameters;
				break;
			case "effort":
				var effort_ids = gDataset.table2.replace("zd_", "");
				var parameters = "effort_ids=" + effort_ids + "&" + gQuery.toQueryString('chart');
				var url = gPlone + "effort_chart_url?" + parameters;
				break;
		}
		
		if (gDataset.ds_type == "ptacs" && gDataset.platform == "station") {
			// Currently for Melissa's 533 dataset.
			var url = gPlone + "dist_station_chart_url?" + parameters;
			//gChartType = "effort";
			//$('range_select').hide();
		}
	
		//$('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);
	}
	
	if (gChartType == 'obs') {
		$('range_select').show();
	}
	build_range_select(chart_data_list[0]);
	
	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) {
	if (layer_type == "dist" && gDataset.ds_type == "pthab") {
		alert("Distribution map is not available for shore/habitat type dataset");
		return true;
	}
	
	if (gQuery.dataset[0] == 427) {	// ESAS
		if (layer_type == "point" && (gQuery.sp_tsn.length == 0 && gQuery.criteria == "")) {
			alert("Due to the huge amount of data, points layer is available for a specific species (select one).");
			return true;
		}
		if (layer_type == "dist") {
			if (gQuery.criteria != "" && gQuery.sp_tsn.length == 0) {
				grid.selModel.clearSelections();
				grid_simple.selModel.clearSelections();
				reset_species_count();
			} else {
				update_obs_numbers();
			}
			gQuery.criteria = "";
			gEsasTrips = [];
			$("td_img_legend").setStyle({display:gTableCell});
			if (Ext.getCmp("esas_trips_panel") != null) {
				Ext.getCmp("esas_trips_panel").selModel.clearSelections();
				Ext.getCmp("esas_trip_species_panel").selModel.clearSelections();
			}
		}
		if (gRelatedLayerStatus == null) {	// Set initial effort layer state.
			gRelatedLayerStatus = false;
		}
	}
	
	if (gRelatedLayerStatus == null) {
		gRelatedLayerStatus = true;		// Set initial effort layer state.
	}	
	
	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.dataset[0],
			point_layer_type: gQuery.layer_type,
			line_layer: gRelatedLayerName,
			publish: gQuery.publish,
			line_status: gRelatedLayerStatus
		}, "", {});
}

function layer_switched(oj, layer_type) {
	var class_name = "button_selected";
	var legend_points = $('legend_points');
	var legend_cellsize = $('legend_cellsize');
	gActiveLayer = layer_type;
	switch (layer_type) {
		case "point":
			var msg = oj.responseText.evalJSON();
			gLayerName = msg.layer_name;
			gRelatedLayerName = msg.related_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);
			if (gDataset.ds_type == "pttag") {
				//$$('tr.series_item').invoke("removeClassName", "selected");
				var grid = Ext.getCmp("series_grid");
				grid.selModel.clearSelections();
				gQuery.series = [];
				update_obs_numbers();
			}
			activate_layer(layer_type);
			break;
	}	
	$$('input.radio_display_count').each(function(item){item.disabled = layer_type == "point"});	
}

function update_point_layer(updated) {
	if (gLayerName == "") {
		var layer_name = gQuery.dataset[0];
	} else {
		var layer_name = gLayerName;
	}
	var where = gQuery.toQueryString('z_union');
	
	if (gDataset.table2 != "" && gDataset.auto == "TRUE") {
		if (gDataset.ds_type == 'pttag' && gQuery.sp_tsn.length != 0) {
			// gQuery.sp_tsn can have multiple TSNs
			var sp_tsns = gQuery.sp_tsn;
			
			var series_grid = Ext.getCmp("series_grid");
			var series_list = [];
			for (var i = 0; i < sp_tsns.length; i++) {
				var records = series_grid.store.query("sp_tsn", sp_tsns[i]);
				var series = records.items.collect(function(item){return "'" + item.id + "'"});
				series_list = series_list.concat(series);
			}
			
			if (where != "") {
				var delimiter = "&";
			} else {
				var delimiter = "";
			}
			where += delimiter + "series_effort=" + series_list.join(",");
		}
	} 
	
	var time_range = get_env_time_range();
	if (time_range.start == "" || time_range.temporal == "") {
		alert("Wrong time range. Environmental layer won't show up.");
	}
	
	gMapserver.request("custom_query", updated,
		{
			layer_name: layer_name,
			layer_type: gQuery.layer_type,
			effort_layer_name: gRelatedLayerName,
			effort_status: gRelatedLayerStatus,
			temporal_scale: time_range.temporal,
			date_start: time_range.start,
			publish: gQuery.publish,
			env_type: radio_value("frm_options", "env_options")
		}, where, {});
}

function activate_layer(layer_type) {
	var lines_button = $('tracks');
	var class_name = "button_selected";
	gActiveLayer = layer_type;
	switch (layer_type) {
		case "point":
			$("img_legend").hide();
			if (gDataset.ds_type == "pthab") {
				var onoff = off;				
			} else {
				var onoff = true;
				get_legend();
			}
			if (gRelatedLayerName != "") {
				if (gRelatedLayerStatus) {
					var icon_suffix = "_selected";
					lines_button.addClassName(class_name);
				} else {
					var icon_suffix = "";
					lines_button.removeClassName(class_name);
				}
			} else {
				var icon_suffix = "_disabled";
			}
			break;
		case "dist":
			var onoff = false;
			$("img_legend").show();
			
			var icon_suffix = "_disabled";
			lines_button.addClassName(class_name);
			break;
	}
	lines_button.src = gIconBase + lines_button.id + icon_suffix + ".png";
	
	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'>";
	$('aves_count', 'mammalia_count', 'reptilia_count', 'grand_total').invoke('update', loading);
	
	// Update species list
	if (gQuery.spatial != "" || gQuery.temporal != "" || gQuery.sp_tsn.length == 0 || gQuery.series.length == 0) {
		update_obs_numbers();
	} else {
		reset_species_count();
	}
	
	if (gActiveLayer == 'point') {
		update_point_layer(custom_query_updated);
	} else {
		update_dist_layers();
	}
}

function update_obs_numbers() {
	if (gQuery.series.length > 0) {
		var parameters = gQuery.toQueryString('z_union') + "&id=" + gQuery.dataset[0];
		var url = gPlone + "getSeriesSummary/";
	} else if (gQuery.dataset[0] == 427 && gQuery.criteria != "") {
		// When trips are selected
		parameters =gQuery.toQueryString('z_union');
		var url = gPlone + "getEsasSpecies/";
	} else {
		var parameters = $H({
			start_at: 0,
			order_by: 'obis_taxa, max(species_profiles.scientific_name)',
			species_only: false,
			num_species:-1
		});
		parameters = parameters.toQueryString() + "&" + gQuery.toQueryString('facts');
		var url = gPlone + "getSpecies/";
	}
	new Ajax.Request(url + "?" + parameters,
		{
			method: 'GET',
			onSuccess: update_species
		});	
}

function get_attributes(id) {
	var url = g_ROOT_URL + BASE_URL + "seamap2/main/seamap2.php?mode=attributes&id=" + id;
	new Ajax.Updater('attributes_content', url, {onComplete: window_resize});
}

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

function show_legend(oj) {
	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 lines_on_off() {
	var lines_button = $('tracks');
	if (gActiveLayer == 'dist') {
		alert("This function is available when the point observations are visible.");
	} else if (gRelatedLayerName == "") {
		alert("This dataset does not have track/effort data.");
	} else {
		if (gQuery.dataset[0] == 427 && gQuery.spatial == "" && !gRelatedLayerStatus && gQuery.criteria == "") {
			alert("Due to the huge amount of data, tracks are only available when a region of interest or a trip is defined.");
			return true;
		}
		if (gRelatedLayerStatus) {
			var on_off = "OFF";
			lines_button.removeClassName('button_selected');
			lines_button.src = gIconBase + lines_button.id + ".png";
		} else {
			var on_off = "ON";
			lines_button.addClassName('button_selected');
			lines_button.src = gIconBase + lines_button.id + "_selected.png";
		}
		gMapserver.request("layer_onoff", update_map,
			{
				layer_name: gRelatedLayerName,
				status: on_off
			}, "", {});
		gRelatedLayerStatus = !gRelatedLayerStatus;
	}
}

function switch_chart_type(chart_type) {
	// Initialize timeRange
	gQuery.clearTemporal();
	
	$$("img.chart_type_button").each(
		function(item){
			$(item).removeClassName('button_selected');
			$(item).src = gIconBase + $(item).id + ".png";
		});
	$("graph_" + chart_type).src = gIconBase + "graph_" + chart_type + "_selected.png";
	$("graph_" + chart_type).addClassName("button_selected");
	
	if (chart_type == 'obs') {
		$('range_select').show();
		$$('tr.chart_legend_effort').invoke("hide");
		$$('tr.chart_legend_obs').invoke("setStyle", {display: gTableRow});
	} else {
		$('range_select').hide();
		$$('tr.chart_legend_obs').invoke("hide");
		$$('tr.chart_legend_effort').invoke("setStyle", {display: gTableRow});
	}
	gChartType = chart_type;
	
	update_chart();
}

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');
		switch (gChartType) {
			case "effort":
				var effort_ids = gDataset.table2.replace("zd_", "");
				parameters += "&effort_ids=" + effort_ids;
				var url_core = "effort_chart_url";
				break;
			default:
				parameters += "&mode=sp";
				var url_core = "dist_sp_chart_url";
		}
		var url = gPlone + url_core + "?" + parameters + "&download=1";
	}
	window.open(url, "download");
}


/***** functions for pttag ds_type *****/
var gSeriesMarker = null;

function get_animals(id) {
	var series_store = new Ext.data.GroupingStore({
		groupField: "group_field",
		id: 'series_store',
	  
		proxy: new Ext.data.HttpProxy({
	            url: g_ROOT_URL + '/functions/getSeriesList',
	            method: 'POST',
	            timeout: 180000	            
	        }),
		baseParams: {id: id, table2: gDataset.table2},
		listeners: {
			load: series_loaded
		},
		reader: new Ext.data.JsonReader({   
		    root: '',
		    totalProperty: '',
		    id: 'series'},
		    [ 
		        {name: 'entity_name', type: 'string', mapping: 'series'},
		        {name: 'group_field', type: 'string', mapping: 'sp_scientific'},
		        {name: 'sp_tsn', type: 'int'},
		        {name: 'date_min', type: 'string'},
		        {name: 'date_max', type: 'string'},
		        {name: 'count', type: 'int'},
		        {name: 'lat_min', type: 'float'},
		        {name: 'lat_max', type: 'float'},
		        {name: 'lon_min', type: 'float'},
		        {name: 'lon_max', type: 'float'},
		        {name: 'length', type: 'float'}
		  	]),
	  	
	  sortInfo:{field: 'entity_name', direction: "ASC"}
	});
	
	
	var series_cm = new Ext.grid.ColumnModel(
	[{
	    header: ' ',
	    readOnly: true,
	    dataIndex: 'sp_tsn',		// arbitorary set so that this field does not become the default sort column.
	    width: 30,
	    align: 'left',
	    fixed: true,
	    menuDisabled: true, 
	    resizable: false,
	    sortable: false,
	    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    		var src = "/seamap2/icons/blank.png";
	   		var text = "<img src='" + src + "' id='legend_" + record.data.entity_name + "'>";
	    	return text;
	    }
	  },{
		id: 'entity_name',
	    header: 'Animal ID',
	    readOnly: true,
	    dataIndex: 'entity_name',
	    width: 100
	  },{
	    header: 'Scientific',
	    readOnly: true,
	    dataIndex: 'group_field',
	    width: 150,
	    hidden: true
	  },{
	    header: 'Count',
	    readOnly: true,
	    dataIndex: 'count',
	    align: "right",
	    tooltip: "Number of data points",
	    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
	   		var text = int_format(value, false);
	    	return text;
	    },
	    width: 80
	  },{
	    header: 'Dates',
	    readOnly: true,
	    dataIndex: 'date_min',
	    tooltip: "Date range",
	    align: 'center',
	    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
	    	if (value != record.data.date_max) {
	    		var text = value + " - " + record.data.date_max;
	    	} else {
	    		var text = value;
	    	}
	    	return text;
	    },
	    width: 210
	  },{
	    header: 'Longitude',
	    readOnly: true,
	    dataIndex: 'lon_min',
	    tooltip: "Longitude range",
	    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
	    	if (value != record.data.lon_max) {
	    		var text = value.toFixed(2) + " - " + record.data.lon_max.toFixed(2);
	    	} else {
	    		var text = value;
	    	}
	    	return text;
	    },
	    width: 150
	  },{
	    header: 'Latitude',
	    readOnly: true,
	    dataIndex: 'lat_min',
	    tooltip: "Latitude range",
	    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
	    	if (value != record.data.lat_max) {
	    		var text = value.toFixed(2) + " - " + record.data.lat_max.toFixed(2);
	    	} else {
	    		var text = value;
	    	}
	    	return text;
	    },
	    width: 130
	  },{
	    header: 'Traveled (km)',
	    readOnly: true,
	    dataIndex: 'length',
	    tooltip: "Length traveled in km",
	    align: "right",
	    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
	    	if (value < 0) {
	    		var text = "N/A";
	    	} else {
	    		var text = number_format((value / 1000), 2, ".", ",");
	    	}
	    	return text;
	    },
	    width: 110
	  }
	]);
	series_cm.defaultSortable= true;	
	
	var btn_sort = new Ext.Toolbar.Button({id: "btn_series_sort", text: "Sort by ID", handler: sort_by_tag_id, tooltip: "Sort by animal tag id",  tooltipType: "title"});
	var btn_collapse = new Ext.Toolbar.Button({text: "Collapse all", id: "btn_series_collapse", handler: collapse_all, tooltip: "Collapse species",  tooltipType: "title"});
	var btn_pause = new Ext.Toolbar.TextItem('<img class="button" src="/seamap2/icons/animation_pause.png" onclick="animation_pause();" ALT="Pause animation" TITLE="Pause animation. Click Start to resume." BORDER="0">');
	var btn_stop = new Ext.Toolbar.TextItem('<img class="button" src="/seamap2/icons/animation_stop.png" onclick="terminate_animation();" ALT="Stop animation" TITLE="Stop animation. Marker will disappear." BORDER="0">');
	var btn_start = new Ext.Toolbar.TextItem('<img class="button" src="/seamap2/icons/animation_run.png" onclick="animation_prepare();" ALT="Start animation" TITLE="Start animation for animal selected" BORDER="0">');
	var btn_animation_time = new Ext.Toolbar.TextItem('<span id="animation_time"></span>');
	var btn_fill = new Ext.Toolbar.Fill();
	var btn_multi_select = new Ext.Toolbar.Button({text: "Multi-select", id: "btn_series_multi_select", enableToggle: true, toggleHandler: multi_select, pressed: false, tooltip: "Press to select multiple animals",  tooltipType: "title"});
	var btn_show_all = new Ext.Toolbar.Button({text: "Clear selection", id: "btn_series_show_all", handler: show_all, tooltip: "Clear user-made selection and show all observations",  tooltipType: "title"});
	
	if (gDataset.id == 477) {
		var btn_filtered_out = new Ext.Toolbar.Button({text: "Show filtered-out points", id: "btn_filtered_out", disabled: true, enableToggle: true, toggleHandler: toggle_filtered_out, pressed: false, tooltip: "Press to show filtered-out points",  tooltipType: "title"});
		var tbar_buttons = [btn_sort, '-',btn_collapse, '-', btn_pause, btn_stop, btn_start, btn_animation_time, '-', btn_filtered_out, btn_fill, btn_multi_select, '-', btn_show_all];
	} else {
		var tbar_buttons = [btn_sort, '-',btn_collapse, '-', btn_pause, btn_stop, btn_start, btn_animation_time, btn_fill, btn_multi_select, '-', btn_show_all];
	}
    var series_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: "series_grid",
        el:'tab_animals',
        width: 900,		// Width is set to 'auto' in switch_tab in detail_common_v2_2.js
        height:400,
        title:'Series list',
        header: false,
        store: series_store,
        trackMouseOver:true,
        loadMask: true,
		autoHeight: false,
		cm: series_cm,
		sm: new Ext.ux.RowSelectionModelMSBSC(),
		stripeRows: true,
		tbar: tbar_buttons,
		autoExpandColumn: 'entity_name',	// performance check
		cls: "grid",
		ctCls: "grid",
		stateful: false,
	    view: new Ext.grid.GroupingView({
	        groupTextTpl: '{gvalue} ({[values.rs.length]})',
	        forceFit: true
	    }),
	    listeners: {
	    	rowclick: select_series
	    }
    });	
    
    series_store.load();
}

function series_loaded(theStore, records, options) {
	var series_grid = Ext.getCmp("series_grid");
    series_grid.render();
}

function sort_by_tag_id(btn) {
	var series_grid = Ext.getCmp("series_grid");
	var theStore = series_grid.getStore();
	
	if (btn.text == "Sort by ID") {
		theStore.clearGrouping();
		theStore.sort("entity_name", "ASC");
		var title = "Group by species";
	} else {
		theStore.groupBy("group_field");
		var title = "Sort by ID";
	}
	btn.setText(title);
}


function select_series(theGrid, rowIndex, e) {
	terminate_animation();
	
	/*
	if (gActiveLayer != 'point') {
		alert("Please select point layer");
		theGrid.getSelectionModel().deselectRow(rowIndex);
		return true;
	}
	*/
	var row = theGrid.store.getAt(rowIndex);
	var series_id = row.id;	
	
	if (gQuery.series.indexOf(series_id) == -1) {
		// Newly selected.
		if (gSeriesMultiSelect) {
			gQuery.series.push(series_id);
		} else {
			gQuery.series = [series_id];
		}
	} else {
		gQuery.series = gQuery.series.without(series_id);
	}

	// Initialize timeRange
	gQuery.clearTemporal();

	// Update numbers (in right pane)
	update_obs_numbers();
	
	if (gActiveLayer == 'point') {
		update_point_layer(custom_query_updated);
	} else {
		// If the map shows the dist layer, first switch to the point layer.
		// switch_layer takes care of the rest (calling update_point_layer())
		var msg = "In order to display individual animal track(s), the map was switched to the point layer. <br>Click [degree] button to go back to the distribution map (the animal selected will be deselected).<br>This window closes in 10 seconds.";
		show_tooltip("td_points_dist_selector", msg, {dismissDelay: 10000, offsetX: -150, offsetY: 220});
		switch_layer("point");
	}

	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 (gDataset.ds_type != "pthab" && (!graph_panel.hidden || (env_type != 'N' && env_time_range == 'sync'))) {
		update_chart();
	}
	
	if (gDataset.id == 477) {	// TOPP Albatrosses. ARGOS filter features.
		if (gQuery.series.length != 0) {
			Ext.getCmp("btn_filtered_out").enable();
		}
	}
}

var gSeries = [];
var gSeriesIndex = 0;
var gAnimationFunc = 0;
function animation_prepare() {
	//$("current_position").hide();
	//if (gSeriesSelected == "") {
	if (gQuery.series.length != 1) {
		alert("Please select an animal (series) in [Animals] tab.");
		return true;
	}
	if (gSeriesIndex == 0) {
		var parameters = $H({id: gQuery.dataset[0], series: gQuery.series[0], temporal: gQuery.temporalZ}).toQueryString();
		var url = gPlone + "getSeries?" + parameters;
		new Ajax.Request(url,
			{
				method: 'GET',
				onSuccess: animation_run
			});
	} else {
		animation_resume();
	}
}

function animation_run(oj) {
	gSeries = eval(oj.responseText);
	// Initialize the marker
	var series = gSeries[gSeriesIndex];
	$('animation_time').update(series.obs_date);
	var icon = new GIcon();
	icon.image = gIconBase + "marker_red.png";
	var icon_width = 16;
	var icon_height = 16;
	icon.iconSize = new GSize(icon_width, icon_height);
	icon.iconAnchor = new GPoint(icon_width / 2, icon_height / 2);
	icon.infoWindowAnchor = new GPoint(icon_width / 2, icon_height / 2);
	
	gSeriesMarker = new GMarker(new GLatLng(series.lat, series.lon), icon);
	map.addOverlay(gSeriesMarker);
	gSeriesIndex++;
	animation_resume();
}

function animation_resume() {
	if (gSeries.length > 100) {
		var interval = 300;
	} else {
		var interval = 500;
	}
	gAnimationFunc = setInterval('move_marker()', interval);
}

function move_marker() {
	if (gSeriesIndex < gSeries.length) {
		var series = gSeries[gSeriesIndex];
		var new_pos = new GLatLng(series.lat, series.lon);
		gSeriesMarker.setLatLng(new_pos);
		var bounds = map.getBounds();
		if (!bounds.containsLatLng(new_pos)) {	// If the marker is out of the view, move the map so the marker is located at the center.
			map.panTo(new_pos);
		}
		$('animation_time').update(series.obs_date);
		gSeriesIndex++;
	} else {
		terminate_animation();
	}
}

function terminate_animation() {
	gSeriesIndex = 0;
	clearInterval(gAnimationFunc);
	gAnimationFunc = 0;
	if (gSeriesMarker != null) {
		map.removeOverlay(gSeriesMarker);
		gSeriesMarker = null;
	}
	$('animation_time').update("");
}

function animation_pause() {
	if (gAnimationFunc == 0) {
		alert("Animation hasn't started.");
		return true;
	}
	clearInterval(gAnimationFunc);
	gAnimationFunc = 0;
}

function toggle_filtered_out(item, pressed) {
	if (pressed) {
		var status = "ON";
		//item.setText("Hide filtered_out points");
	} else {
		var status = "OFF";
		//item.setText("Show filtered_out points");
	}
	gMapserver.request("layer_onoff", update_map, {layer_name: "zd_" + gQuery.dataset[0] + "_filtered_out", status: status}, "", {});
}

function show_tooltip(target_id, message, options) {
    var tip_defaults = {
        title: ' ',
        width: 300,
        autoHide: true,
        autoDestroy: true,
        closable: true,
        //showDelay: 1000,
        hideDelay: 20000,
        dismissDelay: 5000,
        
        listeners: {
        	hide: function(){this.destroy()}
        },
        
        bodyStyle: "color: #666666; text-align: left"    	
    };
    
    if (options != null) {
    	options = $H(tip_defaults).merge(options).toObject();
    } else {
    	options = tip_defaults;
    }
    
    var pos = $(target_id).cumulativeOffset();
    options = $H(options).merge({target: target_id, html: message}).toObject();
	var tooltip = new Ext.ToolTip(options);	
	pos = [pos[0] + options.offsetX, pos[1] + options.offsetY];
	tooltip.targetXY = pos;		// a workaround for a problem that showAt expects an event by which it gets X, Y of the event.
	tooltip.showAt(pos);
}
