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

var gDatasetListStartAt = 0;
var gDontUpdateChart = false;

var gLockDetectScroll = false;
var gPageSize = 50;

var gSpeciesListStartAt = 0;
var gAutoSuggest;
var gSearchOptions = {};	//


// 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/getSpecies',
            method: 'POST'
        }),
	baseParams: gQuery.query("facts"),
	
	listeners: {
		load: data_loaded
	},
	
	reader: new Ext.data.JsonReader({   
	    root: 'species_list',
	    totalProperty: 'num_species',
	    id: 'sp_tsn'},
	    [ 
	        {name: 'sp_tsn', type: 'int'},
	        {name: 'entity_name', type: 'string', mapping: 'scientific_name'},
	        {name: 'group_field', type: 'string', mapping: 'obis_taxa'},
	        {name: 'profile', type: 'string'},
	        {name: 'status', type: 'string'},
	        {name: 'status_dsc', type: 'string'},
	        {name: 'datasets', type: 'string'},
	        {name: 'extent', type: 'string'},
	        {name: 'sp_rank', type: 'string'},
	        {name: 'notes', type: 'string'},
	        {name: 'records', type: 'int'},
	        {name: 'pic_credit', type: 'string'},
	        {name: 'common_name', type: 'string'},
	        {name: 'pic_url', type: 'string'}
	  	]),
  	
  sortInfo:{field: 'entity_name', direction: "ASC"}
});


cm = new Ext.grid.ColumnModel(
[{
	id: 'entity_name',
    header: 'Scientific name',
    readOnly: true,
    dataIndex: 'entity_name',
    width: 180,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		var species_url = '/species/tsn/' + record.data.sp_tsn;
   		var text = "<a href='" + species_url + "' title='Go to Species Profile Page' onmousedown='cancel_bubble(event);' onclick='cancel_bubble(event);'>" + value + "</a>";
    	return text;
    }
  },{
    header: 'Common name',
    readOnly: true,
    dataIndex: 'common_name',
    width: 180
  },{
    header: 'Profile',
    readOnly: true,
    dataIndex: 'sp_tsn',
    align: "center",
    resizable: false,
    //fixed: true,
    sortable: false,	
    menuDisabled: true,
    hidden: true,
    tooltip: "Edit species profile online (admin only)",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = "<a href='/species/edit/" + value + "' target='profile_editor'>Edit</a>";
    	return text;
    },
    width: 80
  },{
    header: 'Status',
    readOnly: true,
    dataIndex: 'status_dsc',
    align: "center",
    tooltip: "Protected status under US ESA and Red List",
    width: 140
  },{
    header: '#obs.',
    readOnly: true,
    dataIndex: 'records',
    align: "right",
    tooltip: "#observations",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = int_format(value);
    	return text;
    },
    width: 80
  },{
    header: '#datasets',
    readOnly: true,
    dataIndex: 'datasets',
    align: "right",
    tooltip: "#datasets",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
   		var text = int_format(value);
    	return text;
    },
    width: 80
  },{
    header: 'Illustration',
    readOnly: true,
    dataIndex: 'pic_url',
    resizable: false,
    fixed: true,
    sortable: false,	
    menuDisabled: true,
    align: "center",
    tooltip: "Species illustration",
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
		if (record.data.pic_credit != "") {
			var title = "Courtesy: " + record.data.pic_credit;
		} else {
			var title = "";
		}
		if (value != "" && record.data.notes == "") {
			var text = "<img src='" + value + "/variant/thumbnail' width='105' title='" + title + "'>";
		} else {
			var text = "";
		}
    	return text;
    },
    width: 115
  },{
    header: 'SEAMAP Taxa',
    readOnly: true,
    dataIndex: 'group_field',
    width: 10,
    renderer: function(value, metadata, record, rowIndex, colIndex, store) {
    	if (["marine mammals","seabirds", "sea turtles"].indexOf(value.toLowerCase()) != -1) {
    		var text = value.capitalize();
    	} else {
    		var text = "Others";
    	}
    	return text;
    },
	hidden: true
  }
]);
cm.defaultSortable= true;


gv = new Ext.grid.GroupingView({
	groupTextTpl: '{group} ({[values.rs.length]})',
	enableRowBody: true,
	getRowClass : function(record, rowIndex, rowParams, store){
        var text = "<p><table style='margin-left:2em; width: 300px;'><tr>";
        text += "<td class='ds_attr'>ITIS#</td><td class='ds_attr'>Profile</td><td class='ds_attr'>Map with</td>";
        text += "</tr>";
        text += "<tr>";
        text += "<td class='ds_attr'>" + record.data.sp_tsn + "</td>";
        text += "<td class='ds_attr''>" + record.data.profile + "</td>";
        
        text += "<td class='ds_attr'>";
        if (record.data.records > 0) {
        	text += "<img src='/seamap2/icons/icon_tool_ge.png' class='button' onmousedown='cancel_bubble(event);' onclick='cancel_bubble(event); open_google_earth(\"sp_tsn\", " + record.data.sp_tsn + ")' title='Map this species with Google Earth'>";
        } else {
        	text += "N/A";
        }
        text += "</td></tr></table></p>";
        rowParams.body = text;
        return 'x-grid3-row-collapsed';
    }
});

var grid_simple = new Ext.tree.TreePanel({
	id: "grid_simple",
	title: "Taxonomic tree",
    //autoHeight: true,
    height: 400,
    autoScroll: true,
    //useArrows: true,
    bodyStyle: 'padding:5px 0px 5px 5px;',
	loader: new Ext.tree.TreeLoader({
		dataUrl: "/functions/getTaxonTree2",
		baseParams: {rank: "class", sp_tsn: 179913}
	}),
	root: {
        text: 'All taxa',
        draggable:false,
        id:'all_taxa',
        scientific: 'All taxa',
        sp_rank: 'all',
        sp_tsn: 0,
        children: [
            {
	            nodeType: 'async',
	            leaf: false,
	            scientific: 'Aves',
	            text: 'Seabirds',
	            draggable:false,
	            id:'aves',
	            sp_rank: 'class',
	            sp_tsn: 174371
	        },{
	            nodeType: 'async',
	            leaf: false,
	            scientific: 'Mammalia',
	            text: 'Marine mammals',
	            draggable:false,
	            id:'mammalia',
	            sp_rank: 'class',
	            sp_tsn: 179913
	        }, {
	            nodeType: 'async',
	            leaf: false,
	            scientific: 'Reptilia',
	            text: 'Sea turtles',
	            draggable:false,
	            id:'reptilia',
	            sp_rank: 'class',
	            sp_tsn: 173747
	        }            
	        
        ]
    }
});

grid_simple.loader.on("beforeload", function(treeLoader, node) {
    treeLoader.baseParams.rank = node.attributes.sp_rank;
    treeLoader.baseParams.sp_tsn = node.attributes.sp_tsn;
});       

grid_simple.on("beforeappend", function(theTree, parent_node, this_node) {
	if (this_node.attributes.text == undefined || this_node.attributes.text == "") {
    	this_node.text = this_node.attributes.scientific;
	}
});
//grid_simple.on("click", taxa_tree_clicked);
grid_simple.getSelectionModel().on("selectionchange", taxa_tree_clicked);

var search_option_panels = [{
        title: 'Species',
        contentEl: "box_species",
        autoHeight: true,
        bodyStyle: 'padding:5px 0px 5px 0px'
    },{
        title: 'Protected status',
        collapsed: true,
        autoHeight: true,
        bodyStyle: 'padding:0px 0px 5px 0px',
        tools: [{id: 'help', qtip: 'Detailed description', handler: show_help_tip.bind(this, "protected_status")}],
        defaults: {
        	border: false
        },
        items: [{
   	        xtype: 'tabpanel',
   	        plain:true,
   	        activeTab: 0,
			items: [{
			        title: 'US ESA',
			        contentEl: "box_us_esa"
			    },{
			        title: 'IUCN Red List',
			        contentEl: 'box_iucn_redlist'
			    }
			]
        }]
        
    },{
        title: 'Only species with',
        contentEl: "box_only_species_with",
        collapsed: true,
        autoHeight: true,
        bodyStyle: 'padding:5px 0px 5px 0px'
    },
    grid_simple
];



/**** initialize page *****/
function init() {
	gQuery.taxaColumn = 'all_taxa';
	
	var url = gPlone + 'getSpecies';
	var parseFunc = parseSpecies;	// Defined in auto_suggest.js
	gAutoSuggest = new AutoSuggest("species", "result_list", species_changed);
	gAutoSuggest.setFilter(url, parseFunc);

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

	//
	$$('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');
			}
		});});

	new Draggable('div_chart',{zindex: 10, constraint:'horizontal',  starteffect:null, endeffect:null});
	
	// Update species list so it reflects the species chosen
	//gSpeciesListStartAt = 0;
	//get_species();
	
	gMapserver = new Mapserver(gUrlPhp, "");
	initialize_mapfile();
}

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

	var taxa_node = grid_simple.getSelectionModel().getSelectedNode();
	if (taxa_node == null || taxa_node.attributes.sp_rank == "all" || taxa_node.attributes.sp_rank == "class") {
		var dist_taxa = true;
	} else {
		var dist_taxa = false;
	}
	if (gQuery.sp_tsn.length > 0 || !dist_taxa || gQuery.temporal != "" || gQuery.datasets != "" || gQuery.dataset.length != 0 || gQuery.sp_tsns.length != 0) {
		layer_name += "sp_";
		gQuery.taxaColumn = "record_count";	// cheat
	} else {
		layer_name += "taxa_";
		set_taxa_column();
	}
	if (zoom >= gZoom['001']) {
		var cellsize = "001";
	} else if (zoom >= gZoom['01']) {
		var cellsize = "01";
	} else {
		var cellsize = "1";
	}
	layer_name += cellsize + "deg";

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


// set gQuery.sp_tsn (done in species_search) and update affected components (map, graph, species list)
/* old version
function species_changed() {
	if ($('result_list').visible()) {
		$('result_list').hide();
	}
	
	gQuery.clearTemporal();
	gQuery.sp_tsn = [];
	
	if ($F('species') != "") {
		// Species
		var species = $F('species');
		// Need to find children species, if any.
		var sp_tsn = species_search(species);	// species_search accepts either name or TSN number

		if (sp_tsn.length == 0) {
			alert("No species found");
		}
	} else {
		gQuery.sp_tsns = [];
	}

	// Update species list so it reflects the species chosen
	get_species(true);

	// Update chart
	var graph_panel = Ext.getCmp("graph_and_env_panel");
	if (!graph_panel.hidden) {
		update_chart();
	}
	
	update_dist_layers();
}
*/

/* streamlined version */
function species_changed() {
	if ($('result_list').visible()) {
		$('result_list').hide();
	}
	
	gQuery.clearTemporal();
	gQuery.sp_tsn = [];
	
	if ($F('species') != "") {
		// Species
		var species = $F('species');
		// Need to find children species, if any.
		var sp_tsn = species_search(species);	// species_search accepts either name or TSN number
	} else {
		gQuery.sp_tsns = [];
		get_species(true);
	
		// Update chart
		var graph_panel = Ext.getCmp("graph_and_env_panel");
		graph_panel.hide();
		if (!graph_panel.hidden) {
			update_chart();
		}
		
		update_dist_layers();	
	}
}

function species_search_results(oj) {		// EXT JS version
	var species_info = oj.responseText.evalJSON();
	var species = species_info.species_list;
	
	if (species.length == 0) {
		alert("Species " + $F("species") + " not found.");
		return true;
	}
	
	gQuery.sp_tsns = [];
	gSpeciesList = [];
	for (var i=0; i < species.length; i++) {
		if (gQuery.sp_tsns.indexOf(species[i]['sp_tsn']) == -1) {
			gQuery.sp_tsns.push(species[i]['sp_tsn']);
			gSpeciesList.push(species[i]);
		}
	}

	grid.store.loadData({species_list: species, num_species: species.length});
	
	// Update chart
	var graph_panel = Ext.getCmp("graph_and_env_panel");
	if (!graph_panel.hidden) {
		update_chart();
	}
	
	update_dist_layers();
	update_num_species();
}


// EXT JS version
function taxa_tree_clicked(selModel, node) {
	// When a new taxon tree is selected, clear currnetly selected species.
	gQuery.sp_tsn = [];
	gQuery.clearTemporal(); 
	grid.selModel.clearSelections();

	var rank = node.attributes.sp_rank;
	var scientific = node.attributes.scientific;
	var sp_tsn = node.attributes.sp_tsn;
	gSearchOptions['rank'] = rank;
	gSearchOptions['rank_tsn'] = sp_tsn;
	
	gQuery.taxaColumn = node.attributes.id;
	gQuery.sp_rank = "sp_" + rank + " = '" + scientific + "'";
	
	switch (rank) {
		case "all":
			gQuery.sp_rank = "";
			gSearchOptions['rank'] = null;
			gSearchOptions['rank_tsn'] = null;
			break;
	}
	
	gAutoSuggest.SearchOptions = gSearchOptions;
	
	update_dist_layers();
	get_species(true);
	
	var graph_panel = Ext.getCmp("graph_and_env_panel");
	if (!graph_panel.hidden) {
		update_chart();
	}
}


// Called when user picked a species from auto suggestion
function choose_species(sp_tsn) { /* EXT JS version */
	if (sp_tsn == "" && $F('species') != "") {
		var species = $F('species');
		species_search(species);
	} else {
		gQuery.sp_tsns = [sp_tsn];
	}

	var graph_panel = Ext.getCmp("graph_and_env_panel");
	if (!graph_panel.hidden) {
		update_chart();
	}
	
	update_dist_layers();
}


function update_chart() {
	var taxa_node = grid_simple.getSelectionModel().getSelectedNode();
	if (taxa_node == null || taxa_node.attributes.sp_rank == "all") {
		var all_taxa = true;
	} else {
		var all_taxa = false;
	}
	if (all_taxa && gQuery.spatial == "" && gQuery.sp_tsn.length == 0 && gQuery.sp_tsns.length == 0) {
		$$('div.chart_area').invoke('toggle');
		var graph_button = $('tool_graph');
		graph_button.src = gIconBase + "icon_" + graph_button.id + ".png";
		graph_button.removeClassName("button_selected");
		return true;
	}

	// Update chart
	$('div_chart').style.left = 0 + "px";
	$('charts_div').update("<img src='" + gIconBase + "ajax_loader.gif' style='margin-left:310px; margin-top:25px'>");
	$('range_select').hide();
	gQuery.clearTemporal();
	var parameters = gQuery.toQueryString('chart') + "&mode=sp";
	var url = gPlone + "dist_sp_chart_url?" + parameters;

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

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

function roi_updated() {
	gQuery.clearTemporal();
	
	// Update species list so it reflects ROI
	if (gQuery.sp_tsn.length == 0) {
		// do not update species list, if one or more species are selected.
		get_species(true);
	}
		
	update_dist_layers();
	
	var graph_panel = Ext.getCmp("graph_and_env_panel");
	if (!graph_panel.hidden) {
		update_chart();
	}
}

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

// When the slidebar is moved. Called by slider_dropped in dist_map_common.js.
function time_range_changed() {
	if (gQuery.sp_tsn.length == 0) {
		get_species(true);
	}
	update_dist_layers();
}


function set_taxa_column() {
	var taxa_node = grid_simple.getSelectionModel().getSelectedNode();
	if (taxa_node == null) {
		gQuery.taxaColumn = "all_taxa";
	} else {
		gQuery.taxaColumn = taxa_node.attributes.id; 
		// For deeper taxa tree node than class, it doesn't maatter as the dist_layer is sp_dist_xxx.
	}
}

function status_change() {
	var status_ids = ['status_e', 'status_t', 'status_cr', 'status_en', 'status_vu', 'status_nt', 'status_lc', 'status_dd'];
	var status = [];
	for (var i = 0; i < status_ids.length; i++) {
		if ($(status_ids[i]).checked) {
			status.push("'" + $F(status_ids[i]) + "'");
		}
	}
	
	if (status.length > 0) {
		gSearchOptions['protected_status'] = status.join(",");
		get_protected_species(gSearchOptions['protected_status']);
	} else {
		gSearchOptions['protected_status'] = "";
		gQuery.sp_tsns = [];
		set_taxa_column();
		get_species(true);
		update_dist_layers();
		var graph_panel = Ext.getCmp("graph_and_env_panel");
		if (!graph_panel.hidden) {
			update_chart();
		}	
	}
	gAutoSuggest.SearchOptions = gSearchOptions;	
}

function get_protected_species(status_chosen) {
	var url = gPlone + "getProtectedSpecies?status=" + status_chosen;

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

function set_protected_species(oj) {
	var species = oj.responseText.evalJSON();
	
	gQuery.sp_tsns = species.collect(function(s) {return s.sp_tsn});
	get_species(true);
	update_dist_layers();
	var graph_panel = Ext.getCmp("graph_and_env_panel");
	if (!graph_panel.hidden) {
		update_chart();
	}	
	
}

function set_record_count() {
	if ($('check_record_count').checked) {
		gSearchOptions['record_count'] = $F('record_count');
	} else {
		var h = $H(gSearchOptions);
		h.unset('record_count');
		gSearchOptions = h.toObject();
	}
	
	clear_species_list();
	set_taxa_column();
	gAutoSuggest.SearchOptions = gSearchOptions;
	get_species(true);
	update_dist_layers();
}

function record_count_enter(event) {
	var keyPressed = event.which || event.keyCode;
	if(keyPressed == Event.KEY_RETURN || keyPressed == 14){
		set_record_count();
	}
}

function profile_option() {
	if ($('check_profile').checked) {
		gSearchOptions['profile_only'] = true;
	} else {
		gSearchOptions['profile_only'] = false;
		var h = $H(gSearchOptions);
		h.unset('profile_only');
		gSearchOptions = h.toObject();
	}
	
	set_taxa_column();
	gAutoSuggest.SearchOptions = gSearchOptions;
	get_species(true);
	update_dist_layers();
}

function map_loaded() {
	get_species(true);	
	grid.render();
    grid.on("bodyscroll", list_scrolled);
    grid.on("rowclick", row_clicked);
	Ext.getCmp("grid_simple").getRootNode().expand();
    
    window_resize();	
}

function list_scrolled(scrollLeft, scrollTop ) {
	var column_header_height = 32;
	var visible_height = grid.getInnerHeight();
	
	var view = grid.getView();
	var list_body = $(view.mainBody.id);
	var list_height = list_body.getHeight();
	
	if (!gLockDetectScroll && (visible_height + scrollTop + column_header_height > list_height * 0.9)) {
		get_species(false);
	}
}

function data_loaded(theStore, records, options) {
	/*
	if (options.params.provider_list == 1) {
		store_simple.removeAll();
		var providers = theStore.reader.jsonData.providers;
		var records = store_simple.reader.readRecords(providers);
		store_simple.add(records.records);
		
		// Update #datasets
		update_num_datasets();
	}
	*/
	store.remoteGroup = false;
	store.remoteSort = false;
	gLockDetectScroll = false;
	update_num_species();

}


function get_species(initial_load) {
	gLockDetectScroll = true;

	store.baseParams = gQuery.query("facts");
    var params = store.baseParams;
    params["num_species"] = gPageSize;
    params["order_by"] = "obis_taxa, max(species_profiles.scientific_name)";
    params["species_only"] = true;
    
    var node = grid_simple.selModel.getSelectedNode();
    if (node != null) {
    	if (node.attributes.sp_rank != "all") {
		    params["rank"] = node.attributes.sp_rank;
		    params["rank_tsn"] = node.attributes.sp_tsn;
    	}
    }
    
	store.remoteGroup = true;
	store.remoteSort = true;
    if (initial_load) {
		gSpeciesListStartAt = 0;
	    params["start_at"] = gSpeciesListStartAt;
    	store.load({params: params});
    } else {
    	gSpeciesListStartAt += gPageSize;
	    params["start_at"] = gSpeciesListStartAt;
	    
	    // initial_load = false means auto scroll. In this case, keep sp_tsns but clear sp_tsn to get next page.
	    // Otherwise, the next page contains only undesired list of species.
		var tsns = "";
		if (gQuery.sp_tsns.length != 0) {
			tsns = gQuery.sp_tsns.join(",");
		}
	    params["sp_tsn"] = tsns;		
	    
	    store.proxy.load(params, store.reader, function(records, args, status) {
			store.remoteGroup = false;
			store.remoteSort = false;
	    	if (records.records.length > 0) {
		    	store.add(records.records);
		    	gLockDetectScroll = false;
	    	}
	    });
    }	
}

function update_num_species() {
	if (gQuery.sp_tsn.length > 0) {
		var num_species = gQuery.sp_tsn.length;
	} else {
		var num_species = store.reader.jsonData.num_species;
	}
	$("num_species").update(num_species);	
	
}
