var map;
var species_record_def;

var gIconBase = "/seamap2/icons/";
var gPlone = "/swot/";
var gUrlMapserver = g_ROOT_URL + "/cgi-bin/mapserv";
var FEEDBACK = "/seamap2/swot/feedback.php";
var gMapProcessUrl = g_ROOT_URL + "/seamap2/swot/swot.php";
var gMapPath = "/var/www/seamap2/map/swot.map";
var myTileOverlay;
var gSeamapLayerOpacity = 1.0;


var species_info = [
	[1, "species_loggerhead.png", "Caretta caretta", 173830, "Loggerhead", "CC_Distribution"],
	[2, "species_green.png", "Chelonia mydas", 173833, "Green", "CM_Distribution"],
	[3, "species_leatherback.png", "Dermochelys coriacea", 173843, "Leatherback", "DC_Distribution"],
	[4, "species_hawksbill.png", "Eretmochelys imbricata", 173836, "Hawksbill", "EI_Distribution"],
	[5, "species_kemp.png", "Lepidochelys kempii", 551770, "Kemp's ridley", "LK_Distribution"],
	[6, "species_olive.png", "Lepidochelys olivacea", 173840, "Olive ridley", "LO_Distribution"],
	[7, "species_flatback.png", "Natator depressus", 551902, "Flatback", "ND_Distribution"]
];
var species_info_extra = [8, "species_multi.png", "Multiple species", 0, "Multiple species", ""];
/*
var dist_layer_info = [
	[1, "#FF0000", "Caretta caretta", 173830, "CC_Distribution"],
	[2, "#00FF00", "Chelonia mydas", 173833, "CM_Distribution"],
	[3, "#0000FF", "Dermochelys coriacea", 173843, "DC_Distribution"],
	[4, "#FFFF00", "Eretmochelys imbricata", 173836, "EI_Distribution"],
	[5, "#00FFFF", "Lepidochelys kempii", 551770, "LK_Distribution"],
	[6, "#FF00FF", "Lepidochelys olivacea", 173840, "LO_Distribution"],
	[7, "#FFFFFF", "Natator depressus", 551902, "ND_Distribution"]
];
*/

var win_feedback;

gQuery = {
	nesting_layer: "swot_nesting",
	size_classes: ["%s > 0 and %s <= 25", "%s > 25 and %s <= 100", "%s > 100 and %s <= 500", "%s > 500 and %s <= 1000", "%s >1000", "%s = -1"],	// -1 represents "unquantified"
	countries: [],
	sizes: [0, 1, 2, 3, 4, 5],
	tsns: [],		// list of TSNs
	where: [],	// WHERE clause set by the user (e.g. green in ('500-1000') and loggerhead in ('500-1000'))
	dist_layers: [],
	
	build: function() {
		gQuery.where = [];	// initialize
		
		var s = this.where_country();
		if (s != "") {
			this.where.push(s);
		}
		var classes = [];
		var count_type = radio_value("swot_criteria", "count_type");
		if (this.sizes.length < 6 && this.sizes.length > 0) {
			for (var i = 0; i < this.sizes.length; i++) {
				classes.push("(" + this.size_classes[this.sizes[i]].replace(/%s/g, count_type) + ")");
			}
			var size_criteria = classes.join(" or ");
			this.where.push("(" + size_criteria + ")");
		} else if (this.sizes.length == 0) {
			this.where.push("(%s < -1)".replace(/%s/g, count_type));
		}
		if (this.tsns.length > 0) {
			this.where.push("sptsn in (" + this.tsns.join(",") + ")");
		}
			
 		if (this.where.length > 0) {
			//this.where_str = escape(this.where.join(" and "));
			this.where_str = this.where.join(" and ");
		} else {
			this.where_str = "true";		// In zd_415.map, WHERE clause says "WHERE %where% and _geom is not null"
		}

		return this.where_str;
	},

	where_country: function() {
		if (this.countries.length != 0) {
			var countries = [];
			for (var i = 0; i < this.countries.length; i++) {
				countries.push(add_quote(this.countries[i]));
			}
			var where = "swot_sites.code in (" + countries.join(",") + ")";
		} else {
			var where = "";
		}
		return where;
	}
}

/* EXTJS version */
var store_countries = new Ext.data.GroupingStore({
	groupField: "region",
	remoteGroup: true,
	remoteSort: true,
	autoLoad: true,
	proxy: new Ext.data.HttpProxy({
            url: gPlone + "getCountries",
            method: 'POST',
			timeout: 180000            
        }),
	baseParams: {},
	reader: new Ext.data.JsonReader({   
	    root: '',
	    totalProperty: '',
	    id: 'code'},
	    [ 
	        {name: 'region', type: 'string'},
	        {name: 'name', type: 'string'},
	        {name: 'code', type: 'string'},
	        {name: 'zoom_level', type: 'int'},
	        {name: 'center_long', type: 'float'},
	        {name: 'center_lat', type: 'float'}
	  	]),
  	
	sortInfo:{field: 'name', direction: "ASC"},
    listeners: {
    	load: function(panel){Ext.getCmp("grid_countries").getView().collapseAllGroups();}
    }
});

cm_countries = new Ext.grid.ColumnModel(
[{
	id: 'region',
    readOnly: true,
    dataIndex: 'region',
    width: 10, hidden: true
  },{
	id: 'name',
    header: 'Name',
    readOnly: true,
    dataIndex: 'name',
    width: 200
  }
]);
cm_countries.defaultSortable= true;

gv_countries = new Ext.grid.GroupingView({
	groupTextTpl: '{group}'
});

grid_countries = 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_countries",
    title:'Large list',
    header: false,
    hideHeaders: true,
    ///height: 300,
	autoHeight: true,
    border: false,
    store: store_countries,
    trackMouseOver:true,
    loadMask: true,
	cm: cm_countries,
	sm: new Ext.ux.RowSelectionModelMSBSC(),
	stripeRows: true,
	autoExpandColumn: 'name',
	stateful: false,
	tbar: ["->", {text: "Multi-select", id: "btn_multi_select", enableToggle: true, toggleHandler: multi_select, pressed: false, tooltip: "Press to select multiple countries",  tooltipType: "title"}],
    view: gv_countries,
    listeners: {
    	rowclick: select_country
    }
});


Ext.onReady(function(){
	// Species Panel
	species_record_def = Ext.data.Record.create([
	    {name: 'id'},			// Added to sort entries properly
	    {name: 'icon_symbol'},			// file name of symbol image
	    {name: 'species'},			// species name
	    {name: 'tsn'},				// species TSN
	    {name: 'common_name'},				// species common name
	    {name: 'layer_name'}				// distribution shapefile name (in swot.map)
	]);
	
	var store_species = new Ext.data.Store({
		id: 'store_criteria',
		reader: new Ext.data.ArrayReader({
            idIndex: 0  // id for each record will be the first element
        }, species_record_def),
  		sortInfo:{field: 'id', direction: "ASC"}			
	});
	
	var cm_species = new Ext.grid.ColumnModel(
	[{
	    header: 'ID',
	    readOnly: true,
	    dataIndex: 'id',
	    hidden: true,
	    width: 10
	  },{
	    header: 'symbol',
	    id: "symbol",
	    readOnly: true,
	    dataIndex: 'icon_symbol',
	    width: 25,
	    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
	    	var text = '<img src="/seamap2/swot/images/' + value + '">';
	    	return text;
	    }
	  },{
	    header: 'Species',
	    id: "species",
	    readOnly: true,
	    dataIndex: 'species',
	    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
	    	var text = '<div title="' + record.data.common_name + '">' + value + '</div>';
	    	return text;
	    },
	    width: 100
	  },
	  {
	    header: 'tsn',
	    readOnly: true,
	    dataIndex: 'tsn',
	    hidden: true,
	    width: 10
	  }
	]);

	var grid_species = new Ext.grid.GridPanel({
		id: "grid_species",
        title:'Species',
        header: false,
        hideHeaders: true,
        border: false,
        store: store_species,
		cm: cm_species,
		sm: new Ext.ux.RowSelectionModelMSBSC({multiSelectWithClick: true}),
		autoExpandColumn: "species",
		stateful: false,
		listeners: {
			rowclick: select_species
		}
	});
	grid_species.store.loadData(species_info);		// species_info defined at the top.
	grid_species.store.loadData([species_info_extra], true);

	var search_option_panels = [{
	        title: 'Species',
	        //contentEl: "box_turtle",
	        autoHeight: !Ext.isIE,
	        height: 240,
	        layout: 'fit',
	        items: [grid_species],
	        tools: [{id: 'help', qtip: 'Select your turtles of interest', handler: show_help_tip.bind(this, "turtle")}]        
	    },{
	        title: 'Count type',
	        contentEl: "box_count_type",
	        autoHeight: true,
	        tools: [{id: 'help', qtip: 'Choose count type: females, crawls, clutches', handler: show_help_tip.bind(this, "count_type")}]        
	    },{
	        title: 'Country',
	        id: 'box_countries',
	        autoScroll: true,
	        items: [grid_countries],
	        tools: [{id: 'help', qtip: 'Choose countries', handler: show_help_tip.bind(this, "country")}]
	    },{
	        title: 'Colony size',
	        id: "panel_colony_size",
	        contentEl: "box_colony_size",
   	        collapsed: true,
	        tools: [{id: 'help', qtip: 'Turn on/off colony sizes', handler: show_help_tip.bind(this, "colony_size")}]        
	    }
	];
	
	/* Sites */
	var store = new Ext.data.GroupingStore({
		groupField: "group_field",
		id: 'store_sites',
		remoteGroup: true,
		remoteSort: true,
	  
		proxy: new Ext.data.HttpProxy({
	            url: g_ROOT_URL + '/swot/siteSummary',
	            method: 'POST'
	        }),
		baseParams: {},
		
		listeners: {
			load: data_loaded
		},
		
		reader: new Ext.data.JsonReader({   
		    root: '',
		    totalProperty: '',
		    id: 'row_id'},
		    [ 
		        {name: 'row_id', type: 'string'},
		        {name: 'code', type: 'string'},
		        {name: 'entity_name', type: 'string', mapping: 'name'},
		        {name: 'group_field', type: 'string', mapping: 'country'},
		        {name: 'year_collected', type: 'int'},
		        {name: 'species', type: 'string'},
		        {name: 'compiler', type: 'string'},
		        {name: 'binfem', type: 'string'},
		        {name: 'exactfem', type: 'int'},
		        {name: 'binnest', type: 'string'},
		        {name: 'exactnest', type: 'int'},
		        {name: 'bincrawl', type: 'string'},
		        {name: 'exactcrawl', type: 'int'},
		        {name: 'longitude', type: 'float'},
		        {name: 'latitude', type: 'float'}
		  	]),
	  	
	  sortInfo:{field: 'entity_name', direction: "ASC"}
	});
	
	
	var cm = new Ext.grid.ColumnModel({
		defaults: {readOnly: true},
		columns: [{
			id: 'entity_name',
		    header: 'Site name',
		    dataIndex: 'entity_name',
		    align: "left",
		    width: 200,
		    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		    	var lat = record.data.latitude;
		    	var lon = record.data.longitude;
		    	if (rowIndex > 0 && store.getAt(rowIndex - 1).data.entity_name == value) {
		    		var text = "";
		    	} else {
		   			var text = "<a href='javascript:void(0);' title='Get site info on the map' onmousedown='cancel_bubble(event);' onclick='cancel_bubble(event); get_site_info(" + lon + ", " + lat + ");'>" + value + "</a>";
		    	}
		    	return text;
		    }
		  },{
		    //header: 'Compiler',
		    header: 'Regional<br>organization',
		    dataIndex: 'compiler',
		    tooltip: "Site data collected by local data provider and collated by SWOT and/or another regional organization",
		    align: "center",
		    width: 100,
		    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		    	if (rowIndex > 0 && store.getAt(rowIndex - 1).data.entity_name == record.data.entity_name && store.getAt(rowIndex - 1).data.compiler == value) {
		    		var text = "";	
		    	} else {
			    	if (value != "WIDECAST") {
			   			var text = "SWOT";
			    	} else {
			    		var text = value;
			    	}
		    	}
		    	return text;
		    }
		  },{
		    header: 'Species',
		    dataIndex: 'species',
		    tooltip: "Sea turtle",
		    align: "center",
		    width: 200,
		    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		    	if (rowIndex > 0 && store.getAt(rowIndex - 1).data.entity_name == record.data.entity_name && store.getAt(rowIndex - 1).data.species == value) {
		    		var text = "";	
		    	} else {
		    		var text = value;
		    	}
		    	return text;
		    }
		  },{
		    header: 'Year',
		    dataIndex: 'year_collected',
		    tooltip: "Year data collected",
		    align: "center"
		  },{
		    header: '#females<br>binned',
		    dataIndex: 'binfem',
		    tooltip: "#females binned",
		    align: "right", width: 75
		  },{
		    header: '#females<br>exact',
		    dataIndex: 'exactfem',
		    tooltip: "#females exact", align: "right", width: 75
		  },{
		    header: '#clutches<br>binned',
		    dataIndex: 'binnest',
		    tooltip: "#clutches binned", align: "right", width: 75
		  },{
		    header: '#clutches<br>exact',
		    dataIndex: 'exactnest',
		    tooltip: "#clutches exact", align: "right", width: 75
		  },{
		    header: '#crawls<br>binned',
		    dataIndex: 'bincrawl',
		    tooltip: "#crawls binned", align: "right", width: 75
		  },{
		    header: '#crawls<br>exact',
		    dataIndex: 'exactcrawl',
		    tooltip: "#crawls exact", align: "right", width: 75
		  },{
		    header: 'Country',
		    dataIndex: 'group_field',
		    width: 10,
			hidden: true	
		  }]
	});
	cm.defaultSortable= true;	
	
	var gv = new Ext.grid.GroupingView({
		groupTextTpl: '{group} ({[values.rs.length]})'
	});	
	
	
    var grid = new Ext.grid.GridPanel({		// This grid is rendered (grid.render()) when species tab first shows up: switch_tab() in detail_common_v2_2.js.
    	id: "grid_sites",
        //el: 'list_frame',
        //width: 'auto',		// Width is set to 'auto' in switch_tab in detail_common_v2_2.js
        height:300,
        title:'Nesting data',
        header: false,
        store: store,
        trackMouseOver:true,
        loadMask: true,
		autoHeight: false,
		cm: cm,
		sm: new Ext.ux.RowSelectionModelMSBSC(),
		stripeRows: true,
		autoExpandColumn: 'entity_name',
		stateful: false,
	    view: gv
    });	
    
	var border = new Ext.Panel({
	    title: 'Main frame',
	    id: "main_frame",
	    header: false,
	    layout:'border',
	    renderTo: "body_frame",
	    monitorResize: true,
        height: 900,
		defaults: {
	        split: true,
			animFloat: false,
			autoHide: false,
			useSplitTips: true,
			monitorResize: true		// performance check
		},
	    items: [
	    	{
	    		region: 'west',
		        title: 'Search Options',
		        width: 235,
				collapsible: true,
		        margins: '5 0 5 5',
		        cmargins: '5 5 5 5',
				defaults: {
			        border: false,
					collapsible: true,
					titleCollapse: true,
					animFloat: false,
			        autoWidth: true,
					autoHide: false,
			        bodyStyle: 'padding:0px 0px 0px 0px; background-color: #084D90;',
					listeners: {
						expand: resize_west,
						collapse: resize_west
					}
				},
			    items: search_option_panels
	    	},{
		        region: 'center',		// Google Maps, legend and graph, large list
		        title: 'Map and summary',
		        layout:'border',
		        header: false,
		        border: false,
		        height: 900,
		        minHeight: 350,
		        margins: '5 5 0 0',
				defaults: {
			        split: true,
					animFloat: false,
					autoHide: false,
					useSplitTips: true,
					monitorResize: true
				},
		        items: [
					{
				        region: 'center',		// Google Maps, legend and graph, large list
				        title: 'Map',
				        contentEl: "center_pane",
				        header: false,
				        border: false,
				        height: 600,
				        minHeight: 350,
				        margins: '0 0 0 0',
						tbar: [
							{text: "<img src='/seamap2/swot/images/googleearth_mark_w20.gif'> View in Google Earth", handler: view_in_ge, tooltip: "View the nesting beaches with Google Earth", tooltipType: "title"},
							{text: "<img src='/seamap2/swot/images/icon_legend.png' height='15'> Show Distribution Maps", id: "btn_dist_layer", handler: open_dist_layer_window, tooltip: "Overlay species distribution maps",  tooltipType: "title"}
						],
				        listeners: {
							resize: resize_map
				        }
			        }, {
				        title: 'Summary',
				        region:'south',
				        id: 'panel_summary',
				        contentEl: "summary",
				        border: false,
						collapsible: false,
						//hidden: true,
						header: false,
				        //width: 150,
				        height: 300,
				        margins: '0 0 5 0',
				        //bodyStyle: 'background-color: #084D90;',
				        autoHeight: false,
				        //autoScroll: true,
				        items: [grid]
			        }	        
		        ]
	        }]	// End of items
	})	// End of border
	
	
	init();
	// To force the country grid resizes upon the page load, expand the colony size panel here.
	Ext.getCmp("panel_colony_size").expand();
});		// End of main frame (Ext.Panel)
	
	
function init() {
	show_swot_terms_of_use();	
	
	load();
	//load_countries();
	
	var grid = Ext.getCmp("grid_sites");
	if (grid) {
		grid.setWidth(Ext.getCmp("panel_summary").getSize().width);
		grid.syncSize();
		
	}	
}

function load() {
	if (GBrowserIsCompatible()) {
		map = new GMap2($("map"), {draggableCursor:"default", backgroundColor: '#1D1C56'});
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());

		map.setCenter(new GLatLng(10, 0), 2, G_SATELLITE_MAP);

		var copyright = new GCopyright(1,
		   new GLatLngBounds(new GLatLng(23,122),new GLatLng(46,151)),
		    1, "OBIS-SEAMAP");

		var copyrightCollection = new GCopyrightCollection('SEAMAP Distribution');
		copyrightCollection.addCopyright(copyright);

		var myTileLayer = new GTileLayer(copyrightCollection, 1, 16);
		myTileLayer.getTileUrl = myGetTileUrl;
		myTileLayer.getOpacity = function() { return gSeamapLayerOpacity; }
		myTileLayer.isPng = function() { return false; }	// Somehow IE6 doesn't show overlays in PNG if there is a polygon.
		myTileOverlay = new GTileLayerOverlay(myTileLayer);
		map.addOverlay(myTileOverlay);
		
		GEvent.addListener(map, "click", on_click_identify);
		/*
		if ($('current_position')) {
			GEvent.addListener(map, 'mousemove', on_mousemove_coordinate);
		}
		*/
		if (typeof(map_loaded) == 'function') {
			map_loaded();
		}
	}
}

/***** Mapserver layer definition *****/
// Return URL to get a tile image from Mapserver.
function myGetTileUrl(tile, zoom) {
    // max zoom plus 1
    var projection = new GMercatorProjection(18);

    // Four vertices location in pixcel in GPoint coordinates
    var p1 = new GPoint(tile.x*256,tile.y*256);
    var p2 = new GPoint(p1.x+256,p1.y+256);

    // latitude/longitude of four vertices location in decimal degree
    var latlng1 = projection.fromPixelToLatLng(p1,zoom);
    var latlng2 = projection.fromPixelToLatLng(p2,zoom);

    var lat1 = latlng1.lat();
    var lon1 = latlng1.lng();
    var lat2 = latlng2.lat();
    var lon2 = latlng2.lng();

    // binding box for mapserver
    var minlat = Math.min(lat1,lat2);
    var minlon = Math.min(lon1,lon2);
    var maxlat = Math.max(lat1,lat2);
    var maxlon = Math.max(lon1,lon2);

	var mapext = minlon + "+" + minlat + "+" + maxlon + "+" + maxlat;
	var where = gQuery.build();

	var layers = gQuery.dist_layers.clone();
	layers.push(gQuery.nesting_layer);
	var parameter = "map=" + gMapPath;
	parameter += "&size=256+256";
	parameter += "&mode=map";
	parameter += "&layers=" + layers.join("+");
	parameter += "&where=" + where;
	parameter += "&count_type=" + radio_value("swot_criteria", "count_type");
	parameter += "&mapext=" + mapext;
	
	// Add random parameter, so the image is not cached by browser
	var random_parm = (new Date()).format('mmddyyyyhhnnss');
	
	var url = gUrlMapserver + "?" + parameter + "&" + random_parm;

    return url;
}

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

function resize_west(panel) {
	var border = Ext.getCmp("main_frame");
	if (typeof(border) != "undefined") {
		var margin = 5;
		var buffer = 4;
		var layout = border.layout;
		
		/* Adjust left hand side grid (provider/taxon tree) */
		var header = layout.west.panel.getFrameHeight();
		var height = layout.west.panel.items.items.inject(0, function(acc, item){
			if (item.id == "box_countries") {
				return acc;
			} else if (item.rendered) {
				return acc + item.getSize().height
			} else {
				return acc;
			}
			});
		Ext.getCmp("box_countries").setHeight(layout.west.getSize().height - height - margin - header + buffer);
	}
}


function toggle_colony_size(element, class_index) {
	$(element).toggleClassName('selected');
	
	if ($(element).hasClassName("selected")) {
		$(element).src = gIconBase + "icon_ok.png";
		if (gQuery.sizes.indexOf(class_index) == -1) {
			gQuery.sizes.push(class_index);
		}
	} else {
		$(element).src = gIconBase + "icon_delete.png";
		gQuery.sizes = gQuery.sizes.without(class_index);
	}
	
	update_map();
}

function update_map() {
	myTileOverlay.refresh();
	update_summary();
}

/* EXT JS version */
function update_summary() {
	var where = gQuery.build();		// Returns query for zd_415 which is different from widecast_nesting.
	var store = Ext.getCmp("grid_sites").store;
	
	if (where == "true") {
		// If no criteria are set, do not load the grid data. Instead, clear it.
		store.removeAll();			
	} else {
		where = where.replace("swot_sites.code", "swot_nesting.code");
		store.load({params:{where: where}});
	}
}


function get_site_info(longitude, latitude) {
	var clicked = new GLatLng(latitude, longitude);
	on_click_identify(null, clicked);		
}

function multi_select(item, pressed) {
	Ext.getCmp("grid_countries").getSelectionModel().multiSelectWithClick = pressed;
}

function select_country(theGrid, rowIndex, e) {
	var sm = theGrid.getSelectionModel();
	var countries = sm.getSelections();
	gQuery.countries = countries.collect(function(item){return item.data.code});
	if (gQuery.countries.length == 1) { 
		var country = countries[0].data;
		map.setCenter(new GLatLng(country.center_lat, country.center_long), country.zoom_level);
		update_summary();
	} else {
		update_map();
	}	
	get_providers();
	get_citations();	
}


function select_species(theGrid, rowIndex, e) {
	var sm = theGrid.getSelectionModel();
	var species = sm.getSelections();
	gQuery.tsns = species.collect(function(item){return item.data.tsn});
	update_map();
}

/***** Identify feature *****/
function on_click_identify(overlay, point) {
	if (overlay && typeof(point) == 'undefined') {
		return false;
	}

	gClickedPoint = point;
	var lat = point.lat();
	var lon = point.lng();
	var parameters = {
		map: gMapPath,
		mode: "QUERY",
		lon: lon,
		lat: lat,
		layers: "swot_nesting"
	}
	var where = gQuery.build();

	var url = gMapProcessUrl + "?";
	url += $H(parameters).toQueryString();
	url += "&where=" + where + "&count_type=" + radio_value("swot_criteria", "count_type");

	new Ajax.Request(url,
		{
			method: 'GET',
			onSuccess: prepare_identify
		});
}

function prepare_identify(oj) {
	var site_info = oj.responseText.evalJSON();
	
	if (site_info["site_id"] != "") {
		var country_code = site_info["code"];
		var site_id = site_info["site_id"];
		var where = "swot_nesting.siteid='" + site_id + "'";
		var	count_type = radio_value("swot_criteria", "count_type");
		
		var url = gPlone + "siteSummary?code=" + country_code + "&where=" + where + "&include_country=1&count_type=" + count_type;
		new Ajax.Request(url,
			{
				method: 'GET',
				onSuccess: show_identify
			});
		
	} else {
		var msg = "No site found.";
		map.openInfoWindowHtml(gClickedPoint, msg, {maxHeight:300, maxWidth:500});
	}
}

function show_identify(oj) {
	var count_types = {mfem: "females", mnest: "clutches", mcrawl: "crawls"};
	var species_years = oj.responseText.evalJSON();
	
	var s = "<strong>" + species_years[0].name + "</strong>";
	s += "<table class='listing site_summary_popup'>";
	s += "<tr class='site_summary_popup popup_even'><th>Country</th><td style='border-top: 1px solid #8CACBB;'>" + species_years[0].country + "</td></tr>";
	s += "<tr class='site_summary_popup popup_even'><th>Location (long, lat)</th><td>" + number_format(species_years[0].longitude, 4, ".", ",") + ", " + number_format(species_years[0].latitude, 4, ".", ",") + "</td></tr></table>";

	/*
	s += "<table class='listing site_summary_popup'><thead><tr><th rowspan='2'>Year</th><th colspan='7'>Colony size measured by " + count_types[count_type] + "</th></tr>";
	s += "<tr><th>Green</th><th>Loggerhead</th><th>Hawksbill</th><th>Leatherback</th><th>Olive ridley</th><th>Kemp's ridley</th><th>Flatback</th></tr>";
	s += "</thead>";
	s += "<tbody>";
	*/
	
	s += "<div style='height:200px; overflow: auto'><table class='listing site_summary_popup'>";
	s += "<thead><tr><th>Species</th><th>Year</th><th>#females<br>binned</th><th>#females<br>exact</th><th>#clutches<br>binned</th><th>#clutches<br>exact</th><th>#crawls<br>binned</th><th>#crawls<br>exact</th></tr></thead>";
	s += "<tbody>";
	
	for (var i = 0; i < species_years.length; i++) {
		if (i % 2 == 0) {
			var even_odd = "popup_even";
		} else {
			var even_odd = "popup_odd";
		}
		var species_year = species_years[i];
		var siteid = species_year.siteid;
		s += "<tr class='site_summary_popup " + even_odd + "'>";
		s += "<td>" + species_year.species + "</td>";
		s += "<td class='td_count'>" + species_year.year_collected + "</td>";
		s += "<td class='td_count'>" + species_year.binfem + "</td><td class='td_count'>" + species_year.exactfem + "</td><td class='td_count'>" + species_year.binnest + "</td><td class='td_count'>" + species_year.exactnest + "</td><td class='td_count'>" + species_year.bincrawl + "</td><td class='td_count'>" + species_year.exactcrawl + "</td></tr>";
	}
		
	s += "</tbody></table></div>";
	map.openInfoWindowHtml(gClickedPoint, s, {maxHeight:300, maxWidth:500});
}

function get_providers() {
	var where = gQuery.where_country();
	
	if (where == "") {	// if no country selected, clear provider info and return immediately.
		$("provider_info").update("");
		return true;
	}
	
	where = where.replace("swot_sites", "swot_site_providers");
	var url = "providerInfo" + "?";
	url += "&where=" + where;

	new Ajax.Request(url,
		{
			method: 'GET',
			onSuccess: update_providers
		});
}

function update_providers(oj) {
	var providers = oj.responseText.evalJSON();

	var s = "<table class='listing'>";
	var prev_country = "";
	for (var i = 0; i < providers.length; i++) {
		if (i % 2 == 0) {
			var even_odd = "even";
		} else {
			var even_odd = "odd";
		}
		var provider = providers[i];
		var code = provider.code;
		if (prev_country != code) {
			s += "<tr class='" + even_odd + "' align='left'><th>";
			s += "<strong>" + provider.country + "</strong>";
			s += "</th></tr>"
		}
		
		if (provider.email != "") {
			var email = " (" + provider.email + ")";
		} else {
			var email = "";
		}
		
		if (provider.orgname != "") {
			var orgname = "<BR>" + provider.orgname;
		} else {
			var orgname = "";
		}
		
		s += "<tr class='" + even_odd + "'><td class='provider_name' nowrap>";
		s += provider.fullname + email;
		s += orgname;
		s += "</td></tr>";
		prev_country = code;
	}
	s += "</table>";
	
	$("provider_info").update(s);	
	
}

function get_citations() {
	var where = gQuery.where_country();
	
	if (where == "") {	// if no country selected, clear citation info and return immediately.
		$("citation_info").update("");
		return true;
	}
	
	where = where.replace("swot_sites", "swot_site_citations");
	var url = "citationInfo" + "?";
	url += "&where=" + where;

	new Ajax.Request(url,
		{
			method: 'GET',
			onSuccess: update_citations
		});
}

function update_citations(oj) {
	var citations = oj.responseText.evalJSON();

	var s = "<table class='listing'>";
	var prev_country = "";
	for (var i = 0; i < citations.length; i++) {
		if (i % 2 == 0) {
			var even_odd = "even";
		} else {
			var even_odd = "odd";
		}
		var citation = citations[i];
		var code = citation.code;
		if (prev_country != code) {
			s += "<tr class='" + even_odd + "' align='left'><th>";
			s += "<strong>" + citation.country + "</strong>";
			s += "</th></tr>"
		}
		
		s += "<tr class='" + even_odd + "'><td class='provider_name'>";
		s += citation.fullcite;
		s += "</td></tr>";
		prev_country = code;
	}
	s += "</table>";
	
	$("citation_info").update(s);	
	
}

function add_quote(text) {
	return "'" + text + "'";
}

function show_help_tip(tip_id) {
	var container = "div_help_tip";
	var help_path = "/help/swot/";
	url = help_path + "tip_" + tip_id + ".html" + "?" + get_random();
	new Ajax.Updater(container, url);
	
	var title = tip_id.replace(/_/g, " ").capitalize();
	
	if (!Ext.getCmp("help_tip_window")) {
		var win = new Ext.Window({
			id: "help_tip_window",
			title: title,
			contentEl: 'div_help_tip',
			autoScroll: true,
			autoShow: true,
			layout      : 'fit',
			width       : 800,
			height      : 400,
			closeAction :'hide',
			plain       : true,
			bodyStyle: 'text-align: left; background-color:#FFFFFF',
			bodyCfg: {
		        tag: 'center',
		        cls: 'help_tip'
		    }
		});
	} else {
		var win = Ext.getCmp("help_tip_window");
		win.setTitle(title);
	}
	
	win.show();	
}

function show_swot_terms_of_use() {
	win = new Ext.Window({
		title: 'SWOT Terms of Use',
		contentEl     : 'termsofuse_extjs',
		autoScroll: true,
		layout      : 'fit',
		width       : 640,
		height      : 400,
		closeAction :'hide',
		plain       : true,
		modal: true,
		bodyStyle: 'text-align: left',
		bodyCfg: {
	        tag: 'center',
	        cls: 'extjs_popup'
	    },

		buttons: [{
			text     : 'Agree',
			handler: function() {
				win.hide();
			}
		},{
			text     : 'Disagree',
			handler  : function(){
			    win.hide();
		}
		}]
	});
	
	win.show();
}

function data_loaded() {
	var store = Ext.getCmp("grid_sites").store;
	store.remoteSort = false;
	store.remoteGroup = false;	
}

function view_in_ge() {
	window.open("/cache/kml/swot_all.kmz");
}

/* Distribution layer window */
function open_dist_layer_window() {
	if (!Ext.getCmp("dist_layer_window")) {
		/*
		var layer_info_def = Ext.data.Record.create([
		    {name: 'id'},			// Added to sort entries properly
		    {name: 'symbol'},			// Layer color
		    {name: 'species'},				// species scientific
		    {name: 'tsn'},				// TSN
		    {name: 'layer_name'}				// layer name
		]);
		*/
		
		var store_dist_layers = new Ext.data.Store({
			id: 'store_dist_layers',
			reader: new Ext.data.ArrayReader({
	            idIndex: 0  // id for each record will be the first element
	        }, species_record_def),
	  		sortInfo:{field: 'id', direction: "ASC"}			
		});
		
		var cm_dist_layers = new Ext.grid.ColumnModel(
		[{
		    header: 'ID',
		    readOnly: true,
		    dataIndex: 'id',
		    hidden: true,
		    width: 10
		  },{
		    header: 'symbol',
		    id: "symbol",
		    readOnly: true,
		    dataIndex: 'layer_name',
		    width: 25,
		    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		    	var legend_url = gUrlMapserver + "?map=" + gMapPath + "&mode=legendicon&ICON=" + value;
		    	var text = '<img src="' + legend_url + '">';
		    	return text;
		    }
		  },{
		    header: 'Species',
		    id: "species",
		    readOnly: true,
		    dataIndex: 'species',
		    width: 100,
		    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		    	var text = '<div title="' + record.data.common_name + '">' + value + '</div>';
		    	return text;
		    }
		  },{
		    header: 'Metadata',
		    id: "metadata",
		    readOnly: true,
		    dataIndex: 'tsn',
		    width: 35,
		    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		    	var text = "<img class='button' src='/seamap2/swot/images/icon_info_with_box.png' onmousedown='cancel_bubble(event);' onclick='cancel_bubble(event); show_help_tip(\"dist_map_" + value + "\")'>";
		    	return text;
		    }
		  },{
		    header: 'Layer Name',
		    readOnly: true,
		    dataIndex: 'layer_name',
		    hidden: true,
		    width: 10
		  }
		]);
		
		var grid_layers = new Ext.grid.GridPanel({
	    	id: "grid_layers",
	        store: store_dist_layers,
	        //store: store_species,
	        trackMouseOver:true,
	        loadMask: true,
	        hideHeaders: true,
			autoHeight: false,
			cm: cm_dist_layers,
			sm: new Ext.ux.RowSelectionModelMSBSC({multiSelectWithClick: true}),
			stripeRows: true,
			autoExpandColumn: 'species',
	        width: 300,
	        height: 250,
		    listeners: {
		    	rowclick: select_dist_layer
		    }
	    });
		grid_layers.store.loadData(species_info);		// species_info defined at the top.
    
		var win = new Ext.Window({
			id: "dist_layer_window",
			title: "Turn on/off layers",
			layout      : 'fit',
			width       : 300,
			height      : 300,
			closeAction :'hide',
			plain       : true,
		    animateTarget: "btn_dist_layer",
	        tools: [{id: 'help', qtip: 'Turn on/off the distribution map of the turtles', handler: show_help_tip.bind(this, "distribution")}],
	        bbar: ["->", {text: "Feedback", id: "btn_feedback", handler: open_feedback_window, tooltip: "Click to submit feedback about the distribution map",  tooltipType: "text"}],
		    items: [grid_layers]
		});
	} else {
		var win = Ext.getCmp("dist_layer_window");
	}
	
	if (win.hidden || !win.rendered) {
		win.show();	
	} else {
		win.hide();
	}
}

function select_dist_layer(theGrid, rowIndex, e) {
	var sm = theGrid.getSelectionModel();
	var dist_layers = sm.getSelections();
	gQuery.dist_layers = dist_layers.collect(function(item){return item.data.layer_name});
	myTileOverlay.refresh(); // no need to refresh the site summary, which is called in update_map()
}

function open_feedback_window() {
	if (!win_feedback) {
		win_feedback = new Ext.Window({
			title: "Feedback",
	        layout:'fit',
	        maximized: false,
	        height: 400,
	        width: 800,
	        bodyStyle: "padding: 15px; background-color: #084D90",
		    closeAction:'hide',
		    plain: false,
	        contentEl: "div_feedback"
		});
	}
	win_feedback.show();
}

function submit_feedback() {
	var params = {};
	var boxes = ["full_name", "affiliation", "email", "feedback"];
	var empty_box = boxes.find(function(item){return $F(item) == ""});
	if (empty_box != null) {
		alert("Please fill " + empty_box + " box");
		return true;
	}
	boxes.each(function(item) {
		params[item] = $F(item);
	});
	params["v"] = get_random();	// To refresh
	Ext.Ajax.request({
	   url: FEEDBACK,
	   success: feedback_submitted,
	   failure: download_failed,
	   params: params
	});	
}

function feedback_submitted(response, opt) {
	var params = response.responseText.evalJSON();
	var text = "";
	$H(params).each(function(pair) {
		$("feedback_" + pair.key).update(pair.value);
	});
	$("feedback_input").hide();
	$("feedback_output").show();
}

function clear_feedback_form() {
	$("feedback_input").show();
	$("feedback_output").hide();	
}

function download_failed() {
	
}
