/*Weeds.js*/
/*Functions related to the weeds layer*/

/*FUNCTIONS
-------------------
	Map Related
-getNumPlants
-unselectWeeds
-showAll
-displayWeeds
-addWeedsLayer
-rescaleWeeds
---------------------
	Page Specific
-plantCNameChange
-plantSNameChange
-clearPlantPicklist
-viewAtlas
-getReport
*/

function getPlantList(type, report){
    if(report == undefined || report == null)
	    report = false;
/*State - IMI code, type - species / common, pid = the field to look for for the id, used for the atlas*/
    if(atlasField == null || atlasField == undefined)
        atlasField = "null";
	var url = host + "/imi/requests/list/plants?state=" + imiStateCode + "&pid=" + atlasField + "&type=" + type;
	var ret = "";
	var xmlhttp = newXHR();
	xmlhttp.open("GET",url,false);
	xmlhttp.send(null);
	var plantList = xmlhttp.responseText;		
	var jsonPL = eval(plantList)
	/*make sure the name is the proper format*/
	if(type == 'common')
		type='common_name'
	if(type == 'scientific')
		type='scientific_name'
	/*Loop through the returned object*/
	if(report == true){
		ret = "<option id='reportDefault' value='by Scientific Name' name='sciNameReport'>by Scientific Name</option>";
		for (var i = 0; i < jsonPL.length; i++){
			ret = ret + "<option id='" + eval("jsonPL[i]." + atlasField) + "' value='" + jsonPL[i].id + "' name='" + jsonPL[i].id + "'>" + eval("jsonPL[i]." + type) + "</option>";
		}
	}
	else{		
		for (var i = 0; i < jsonPL.length; i++){
			ret = ret + "<option id='" + eval("jsonPL[i]." + atlasField) + "' value='" + jsonPL[i].id + "' name='" + jsonPL[i].id + "'>" + eval("jsonPL[i]." + type) + "</option>";
		}
	}
	return ret	
}
/*---------------------------------------------------------------------------------------------------------------------------------------
/*getNumPlants()*/
/*Find out how many plants were returned*/
/*makes a python request which counts all the rows returned from a SELECT COUNT(*) statement based on the currently selected species
if no rows are returned, show an alert*/
function getNumPlants()
{
	var psn = document.getElementById('plantSNameSelect');
	var scientific = psn.options[psn.selectedIndex].text;
    /*Ask python to return the number of plants for a selected species, pass the state code, the scientific name of the selected species, and the field used in the DB to store the scientific name*/
	var numPlantsURL = host + "/imi/requests/list/numplants?state=" + imiStateCode + "&scientific=" + scientific + "&sciname=" + sciname;
	var xmlhttp = newXHR();
	xmlhttp.open("GET",numPlantsURL,true);
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4){
			var numOfWeeds = xmlhttp.responseText;      
			     if( numOfWeeds < 1)
				{   
                    /*If no weeds are returned, display an error*/
					alert('There is no data available at the moment for ' + scientific + '.');
				}
		}
	}
	xmlhttp.send(null);
}
/*---------------------------------------------------------------------------------------------------------------------------------------*/
/* Map Specific Functions */
/*---------------------------------------------------------------------------------------------------------------------------------------*/

/*
function picklistQuery(id)
{
	if(id == null || id == undefined)
		id = 'plantSNameSelect';
	var psn = $('plantSNameSelect');
	var scientific = psn.options[psn.selectedIndex].text;
	map.currentWeed = scientific;
	var weeds = map.getLayersByName("WEEDS")[0];
	weeds.mergeNewParams({'layers':"PGWEEDS", 'scientific':scientific});
	weeds.setVisibility(true);
	getNumPlants();
}*/

//filters = [{'plid':'plantSNameSelect', 'filter':'scientific'}, {'plid':'agencySelect', 'filter':'agency'}]
var paramstring, weeds;
function filterWeeds()
{
    weeds = map.getLayersByName("WEEDS")[0];
	paramstring = "weeds.mergeNewParams({'layers':\"PGWEEDS\"";
	//Loop through the elements in the filters object
	for(var i = 0; i < filters.length; i++)
	{
	//Get the pick list id
		var plid = filters[i].plid;
	//Get the filter title
		var filter = filters[i].filter;
	//Get the picklist element
		var plel = $(plid);
	//Get the picklist's current value
		var value = plel.options[plel.selectedIndex].text;
	//Set the paramstring (i.e. Filtername : Value)
		paramstring += ",'" + filter + "':\"" + value + "\"";
	}
	paramstring += "});";
	eval(paramstring);
        weeds.setVisibility(true);
        /*If there is no species data, show an alert*/
        /*find out how many weeds were returned*/
        getNumPlants();
}

/*For contributing organizations*/
function filterWeedsContrib()
{
    if($('agencySelect').selectedIndex != 0){
        var weeds = map.getLayersByName("WEEDS")[0];
	    var paramstring = "weeds.mergeNewParams({'layers':\"PGWEEDS\"";
	    //Loop through the elements in the filters object
	    for(var i = 0; i < filters.length; i++)
	    {
	    //Get the pick list id
		    var plid = filters[i].plid;
	    //Get the filter title
		    var filter = filters[i].filter;
	    //Get the picklist element
		    var plel = $(plid);
	    //Get the picklist's current value
		    var value = plel.options[plel.selectedIndex].text;
	    //Set the paramstring (i.e. Filtername : Value)
		    paramstring += ",'" + filter + "':\"" + value + "\"";
	    }
	    paramstring += "});";
        console.log(weeds)
	    eval(paramstring);
            weeds.setVisibility(true);
            /*If there is no species data, show an alert*/
            /*find out how many weeds were returned*/
            //getNumPlants();
    }
    else
        unselectWeeds();
}


/* function unselectWeeds()
 	Clear all weeds
*/
function unselectWeeds()
{
	clearPlantPicklist();
	var weeds = map.getLayersByName("WEEDS")[0];
	weeds.setVisibility(false);
	map.currentWeed = "";
	map.agency = "";
}

/* function showAll()
 	show all the weeds at once
*/
function showAll()
{
	var weeds = map.getLayersByName("WEEDS")[0];
	weeds.mergeNewParams({'layers':"PGALLWEEDS"});
	rescaleWeeds();
	weeds.setVisibility(true);
	map.currentWeed = "all";
	/*If there is are picklists for common and scientific names, reset their values*/
	if ($('plantCNameSelect') && $('plantSNameSelect')){
		clearPlantPicklist()
	}
}

/* function showAll()
 	show all the weeds at once
*/
function displayWeeds(features)
{
    if(windowOpen == 1) //if a window has been opened
    {
        windowOpen = 0;
        win.close(); //close it
    }
}

/* function addWeedsLayer()
 	add the weeds layer to the map
*/
function addWeedsLayer(){
	//using postgis layer: pgWeeds
	var weedsparams = {
		layers: "PGWEEDS",
		srs: EPSG,
		format: "image/gif", //should be png, transparency broken in IE
		transparent: "true"
	}
	var weedsoptions = {
		gutter:20,
		buffer:0,
		isBaseLayer: false
	}
	var weeds = new OpenLayers.Layer.WMS( "WEEDS", host + "/cgi-bin/mapserv?map=/var/data/mapserver/" + imiStateCode + "/imi.map&", 
	weedsparams, weedsoptions);
	map.addLayers([weeds]);
	weeds.setVisibility(false);
	map.currentWeed = "by Scientific Name";
}
/* function rescaleWeeds()
 	changes the weed icon size based on the map resolution / zoom level
*/
function rescaleWeeds()
{
    var weeds = map.getLayersByName("WEEDS")[0];
    var res = map.getResolution();
    //resolution starts at 2600 and goes down to about 2
    //we want our zoomed out size to be 5, and zoomed in to be 10
    //we make the base size 5, then increase the size proportionately to the res
    //we take square root to make it a less exponential ratio. or something.
    var size = 5 + 10 * (1 - Math.sqrt(res/2600));
    var style = "SYMBOL circle COLOR 255 0 0 OUTLINECOLOR 0 255 0 SIZE "+size;
    weeds.mergeNewParams({'map.layer[PGWEEDS].class[0].style[0]':style});
}
/*---------------------------------------------------------------------------------------------------------------------------------------*/
/* Page Specific Functions */
/*---------------------------------------------------------------------------------------------------------------------------------------*/

/*function plantCNameChange() | plantSNameChange()
-When plant's common name is changed, change the scientific name list
cNamePickListID and sNamePickListID must be the same for both the following functions
*/
function plantCNameChange(){
	var pcn = $('plantCNameSelect');
	$('plantSNameSelect').value = pcn.value;
}

function plantSNameChange(){
	var psn = $('plantSNameSelect');	
	$('plantCNameSelect').value = psn.value;
}

/*Function clearPlantPicklist()
	-Sets the common and scientific name select lists to default values when the Contributing Organization select list is changed
*/
function clearPlantPicklist(){
	var pcn = $('plantCNameSelect');
	var psn = $('plantSNameSelect');
	pcn.selectedIndex = 0;
	psn.selectedIndex = 0;
}
/*Function clearPicklist()
	-Clear a given picklist
*/
function clearPicklist(id){
	var pid = $(id);
	pid.selectedIndex = 0;
}
/*Function clearPicklistArray()
	-Clear a given picklist
*/
function clearPicklistArray(list){
	if(list != null){
		for(var i=0; i < list.length; i++){
			var curId = list[i];
			var pid = $(curId);
			pid.selectedIndex = 0;
		}f
	}
}
/*Function viewAtlas(url)
	-When the atlas button is clicked, get the currently selected plant's value (which will be either a USDA symbol or number) from the plant common name picklist and open the atlas information

url - used to set the link for the atlas button
*/
function viewAtlas(url){
	//pass in the URL and div to place the atlas button in   
	//theLink = "http://www.biol.vt.edu/digital_atlas/index.php?do=plant&plant=";
	
	var clist = $('plantCNameSelect');
	var pid = clist.options[clist.selectedIndex].id
	if (pid != 0)
	{
		url = url + pid;
		window.open(url);
	}
	else
		alert("There is currently no atlas available for this species.");
}
/*Function getReport(reportURL, picklistID)
	-When the report button is clicked, open a new page and show the report based on either the url alone or the url + picklist value
url - used to set the link for the atlas button
picklistID - the ID of the picklist
*/
function getReport(reportURL, picklistID)
{
	if (picklistID == null || picklistID == undefined)
		picklistID == null
	if (reportURL == null || reportURL == undefined)
		return;
		
	//sample reportURL =  "http://bsm07.freac.fsu.edu/iMapInvasives/florida/iswg_rpt.cfm?iswg=";
	if (reportURL && picklistID != null){
		pid = $(picklistID)
		reportURL += pid.options[pid.selectedIndex].text;
		window.open(reportURL);
		pid.selectedIndex = 0;
	}
	else if (reportURL){
		window.open(reportURL);
	}	
	else
		alert("There is currently no report available.");
}
