﻿    var osMap, vectorLayer, curname2, screenOverlay, gridProjection, hoverControl, frdbi; 
    function init() 
    	{ 
        // Creates the map
        var options = {restrictedExtent: new OpenSpace.MapBounds(400000, 70000, 520000, 180000)};
        osMap = new OpenSpace.Map("map",options); 
        osMap.setCenter(new OpenSpace.MapPoint(440000,120000 ), 3);
        vectorLayer = osMap.getVectorLayer();
        gridProjection = new OpenSpace.GridProjection();
		hoverControl = new OpenLayers.Control.SelectFeature(vectorLayer,{multiple: false, click:true, onSelect: onFeatureClick, onUnselect: offFeature });
		osMap.addControl(hoverControl);
		hoverControl.activate();
		screenOverlay = new OpenSpace.Layer.ScreenOverlay("coords");
		screenOverlay.setPosition(new OpenLayers.Pixel(380, 10));
		osMap.addLayer(screenOverlay);
		osMap.events.register("mousemove", osMap, createCursorPos);
		document.getElementById('listholder').style.visibility = "hidden";
        }

    var	grid100	= new Array
								(
									"SV", "SW", "SX", "SY", "SZ", "TV", "TW",
									"SQ", "SR", "SS", "ST", "SU", "TQ", "TR",
									"SL", "SM", "SN", "SO", "SP", "TL", "TM",
									"SF", "SG", "SH", "SJ", "SK", "TF", "TG",
									"SA", "SB", "SC", "SD", "SE", "TA", "TB",
									"NV", "NW", "NX", "NY", "NZ", "OV", "OW",
									"NQ", "NR", "NS", "NT", "NU", "OQ", "OR",
									"NL", "NM", "NN", "NO", "NP", "OL", "OM",
									"NF", "NG", "NH", "NJ", "NK", "OF", "OG",
									"NA", "NB", "NC", "ND", "NE", "OA", "OB",
									"HV", "HW", "HX", "HY", "HZ", "JV", "JW",
									"HQ", "HR", "HS", "HT", "HU", "JQ", "JR",
									"HL", "HM", "HN", "HO", "HP", "JL", "JM"
								);

	function ENToGridRef( anEast, aNorth )
		{
		var	result = null;
		with( Math )
			result = grid100[ floor(anEast/100000) + 7*floor(aNorth/100000) ] + floor( (anEast%100000) / 10 ).pad(4) +  floor( (aNorth%100000) / 10 ).pad(4);
		return result;
		}

	Number.prototype.pad = function( length )
					{
					var	result	= "" + this + "";
					var	sign	= "";
					var	decimal	= "";
					var	point;
					if( (result.charAt(0) == "+") || (result.charAt(0) == "-") )
						{
						sign	= result.substr( 0, 1 );
						result	= result.substr( 1 );
						}
					point = result.indexOf(".");
					if( point >= 0 )
						{
						decimal	= result.substr( point );
						result	= result.substr( 0, point );
						}
					var j = length - result.length;
					for (i=0;i<j;i++)
						{
						result = "0" + result;
						}
					return sign + result + decimal;
					}

	function createCursorPos(e)
        {
        pt = osMap.getLonLatFromViewPortPx(e.xy);
        OSGR = ENToGridRef(pt.lon ,pt.lat)
        screenOverlay.setHTML("<DIV id=\"OS\">" +	OSGR +	" </DIV>");
        }
 
    function onFeatureClick(feature)
		{
		if (typeof(hoverControl.handlers) != "undefined")
	    	{
     		hoverControl.handlers.feature.stopDown = false;
     		}

     	var myx = feature.geometry.components[0].x ;
     	var myy = feature.geometry.components[0].y ;
     	var myz = feature.geometry.components[1].x - myx ;
     	var squery = ("?east=" + myx + "&amp;north=" + myy + "&amp;gsize=" + myz + "&amp;spec=" + curname2) ;
    	//frdbi = document.getElementById('frdbich').checked ;
		if ( frdbi ) {squery += "&list=FRDBI"};
     	//alert ( squery );
     	OpenLayers.loadURL("fungus.php",squery, this, parseRecords, onFail );
    	//document.getElementById('Speclist').innerHTML = "<p><em>R</em>ecords for Gridsquare: </p>" ;

		//for (var name in feature) {
		//if ( feature.hasOwnProperty(name)) {
		//alert(name);
		//}
		//}
		//alert ( feature.id[2] );
     	//alert ( feature.style.fillColor );
     	//alert ( feature.attributes);
     	//alert ( feature.data );
     	//alert ( feature.layer );
     	//alert ( feature.geometry.component[0].point[0]);
     	//var featlen = feature.geometry.components.length;
     	//for ( var i = 0; i<featlen; i++) {
		//alert (feature.geometry.components[i]);
		//}
     	}
     	
    function parseRecords(result)
    	{
        var text = result.responseText;
        var lines = text.split('\n');
        var foottxt = "<p><em>R</em>ecords for selected Gridsquare: </p><p>";
        var newcells = [] ;
		//document.getElementById('list').style.display = "block";
		document.getElementById('listholder').style.visibility = "visible";
		document.getElementById('listtitle').innerHTML = "Records in the selected 1Km grid square";
        emptytable();
       	for (var i = 0; i < lines.length; i++)
        {
        var columns = lines[ i ].split('|');                    
        var newrow = document.getElementById('list').insertRow(i+1) ;
        for (var j=0; j<=8; j++)
        {
		newcells[j] = newrow.insertCell(j);
		newcells[j].innerHTML = columns[j+3];
		}
    	}
     	}

	function emptytable()
		{
		var table = document.getElementById('list');
		var rowcount = table.rows.length ;
		//alert (rowcount);
		if (rowcount > 1) {
		for (var i=1; i<rowcount ;i++)
		{
		table.deleteRow(1);
		}
		}
		}

	function offFeature()
		{
		emptytable();
		//document.getElementById('list').style.display = "none";
		document.getElementById('listholder').style.visibility = "hidden";
	   	//document.getElementById('Speclist').innerHTML = "" ;
		}
        
    function getSpecies(curname, name, Ename, Auth, specID, TaxonNum )
    	{
    	curname2 = curname;
    	frdbi = document.getElementById('frdbich').checked ;
    	var spectxt = "<h2>Profile: " + curname + " " + Auth +"</h2>" ;
    	spectxt2 = "<p>Entered as: " + name + "<br />English name: " + Ename + "</p>" ;
    	spectxt2 += "<p>View the <a class='txtlink' href='http://www.basidiochecklist.info/DisplayResults.asp?intGBNum=" + specID + "' target='_blank'>CBIB</a> description</p>" ;
    	spectxt2 += "<p><b>National Records</b></p>"
		spectxt2 += "<p>View the data on the <a class='txtlink' href='http://data.nbn.org.uk/interactive/map.jsp?srchSp=" + TaxonNum + "' target='_blank'>NBN</a> interactive map</p>";
		spectxt2 += "<p>View the records on the <a class='txtlink' href='http://www.fieldmycology.net/FRDBI/FRDBIrecord.asp?intGBNum=" + specID + "' target='_blank'>FRDBI</a></p>";
		if (frdbi) { spectxt2 += "<p><b>HFRG and FRDBI Records</b></p>"; } else { spectxt2 += "<p><b>HFRG Records</b></p>" ;}
		document.getElementById('Maptxt').innerHTML = spectxt ;
    	document.getElementById('Mapfoot').innerHTML = spectxt2 ;
    	//document.getElementById('Speclist').innerHTML = "" ;
		emptytable();
		//document.getElementById('list').style.display = "none";
		document.getElementById('listholder').style.visibility = "hidden";
		document.getElementById('photo').style.display = "none";
		document.getElementById('map').style.display = "block";
		//var frdbi = document.getElementsById('frdbich').value ;
		//alert (frdbi);
        osMap.setCenter(new OpenSpace.MapPoint(440000,130000 ), 3);
    	getPhotos(curname);
    	getMarkers(curname);
    	}
        
    function getMarkers(squery)
    	{
    	squery = "?spec=" + squery;
    	var frdbi = document.getElementById('frdbich').checked ;
		if ( frdbi ) {squery += "&list=FRDBI"};
 	  	osMap.clearMarkers();
        vectorLayer.destroyFeatures();
        var markersFile = "fungus.php";
        OpenLayers.loadURL(markersFile, squery , this, plotMarkers, onFail); 
      	}
      	
    function plotMarkers(result)            
        { 
		var style_red =
		{
		strokeColor: "#FF0000",
		strokeOpacity: 0.6,
		strokeWidth: 1,
		fillColor: "#FF0000",
		fillOpacity: 0.1
		};
		var listtext = "";               
        var text = result.responseText; 
        var lines = text.split('\n');
        var foottxt = "<p>" + (lines.length) + " Records | Jun 2011</p>" ;
        foottxt += "<p>To see more details of the record click in the marked 1Km area on the map.</p>";
        document.getElementById('Mapfoot').innerHTML += foottxt ;
       	var newcells = [] ;
		var j=0;
        for (var i = 0; i < lines.length; i++)
        {                    
        var columns = lines[ i ].split('|');
        if (columns.length >1 ) {                   
        var x = parseFloat(columns[ 0 ]);                        
        var y = parseFloat(columns[ 1 ]);
        var z = parseFloat(columns[ 2 ]);
		if (x > 1 )
    	{
        var pos = new OpenSpace.MapPoint(x + z/2, y + z/2);                        
        osMap.createMarker(pos);
        if (z==10000) { z=0 };
        var points = []; 
        points.push(new OpenLayers.Geometry.Point(x,y));
        points.push(new OpenLayers.Geometry.Point(x + z,y));
		points.push(new OpenLayers.Geometry.Point(x + z,y + z));
        points.push(new OpenLayers.Geometry.Point(x,y+ z));
		var linearRing = new OpenLayers.Geometry.LinearRing(points);
		var polygonFeature = new OpenLayers.Feature.Vector(linearRing, null, style_red);
		vectorLayer.addFeatures([polygonFeature]);
		}
 		else
        {
        listtext = "Records with no grid reference";
   		document.getElementById('listholder').style.visibility = "visible";
        var newrow = document.getElementById('list').insertRow(j+1) ;
        for (var k=0; k<=8; k++)
        {
		newcells[k] = newrow.insertCell(k);
		newcells[k].innerHTML = columns[k+3];
		}
		j=j+1;
		}
		}
	    }
	    document.getElementById('listtitle').innerHTML = listtext;             
        }     
                                       
    function getPhotos(squery)
    	{
    	squery = "?name=" + squery ;
    	var photoFile = "photo.php";
    	OpenLayers.loadURL(photoFile, squery, this, parsePhotos, onFail);
    	//document.getElementById('photo').innerHTML = "awaiting photo" ;
    	}
    	
    function parsePhotos (result)
    	{
        var text = result.responseText;
        text = text.substr(0,text.length-1);
        var lines = text.split(';');
        var photowidth = 0 ;
        document.getElementById('thumbs').innerHTML = "<div id='thumb' ><a href=#maptxt onclick=\"selectMap()\"><img src=\"images/hants.gif\" width='50px' height='50px' alt='' /></a></div>";
        if ( text.length > 1 ) {
        for (var i=0; i<lines.length ; i++ )
        {
        var columns = lines[i].split(',');
        var photoID = columns[0];
        var filename = "images/Fungi/" + columns[1] + ".jpg";
        var photographer = columns[4];
        var orient = columns[5];
        orient = orient.charAt(0);
        var hfrgno = columns[6];
        if ( orient == "H" ) {photowidth = 470 ; } else {photowidth = 310 ; }
        document.getElementById('thumbs').innerHTML += "<div id='thumb' ><a href=#maptxt onclick=\"selectPhoto('" + filename + "'," + photowidth + ",'" + photographer + "'," + hfrgno + ")\"><img src=\"" + filename + "\" width='50px' height='50px' alt='' /></a></div>" ;
        }
        }
     	}
     	
     	
    function selectPhoto (filename,width,photographer,hfrgno)
    	{
		emptytable();
		//document.getElementById('list').style.display = "none";
		document.getElementById('listholder').style.visibility = "hidden";
		document.getElementById('photo').style.display = "block";
		if (hfrgno == 0) {
    	document.getElementById('photo').innerHTML = "<img src=\"" + filename + "\" width='" + width + "' alt='' /><p>Photo &copy; " + photographer + "</p>" ;
		} else {
    	document.getElementById('photo').innerHTML = "<a href='record.php?hfrgno=" + hfrgno + "'><img src=\"" + filename + "\" width='" + width + "' alt='' /></a><p>Photo &copy; " + photographer + "</p>" ;
		}
		document.getElementById('map').style.display = "none";
    	}
    	
    function selectMap()
    	{
		document.getElementById('photo').style.display = "none";
		document.getElementById('map').style.display = "block";
        //osMap.setCenter(new OpenSpace.MapPoint(440000,130000 ), 3);
    	}
     	             
    function onFail(e)            
        {                
        alert("Cannot load file");            
        }
        
	function showrss(hfrgno)
		{
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  		xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
		xmlhttp.onreadystatechange=function()
		  {
		  if (xmlhttp.readyState==4 && xmlhttp.status==200)
		    {
 		   document.getElementById("rssOutput").innerHTML=xmlhttp.responseText;
		    }
		  }
		//("GET","getrss.php?q="+str,true)
		xmlhttp.open("GET","blogrss.php?hfrg="+hfrgno,true);
		xmlhttp.send();
		}
		
	function showMarker ( x,y,z,Scale )
		{
		var style_red =
		{
		strokeColor: "#FF0000",
		strokeOpacity: 0.6,
		strokeWidth: 1,
		fillColor: "#FF0000",
		fillOpacity: 0.1
		};
		osMap.setCenter(new OpenSpace.MapPoint(x + z/2, y + z/2 ), Scale);
    	var pos = new OpenSpace.MapPoint(x + z/2, y + z/2);
    	osMap.createMarker(pos);
        var points = []; 
        points.push(new OpenLayers.Geometry.Point(x,y));
        points.push(new OpenLayers.Geometry.Point(x + z,y));
		points.push(new OpenLayers.Geometry.Point(x + z,y + z));
        points.push(new OpenLayers.Geometry.Point(x,y+ z));
		var linearRing = new OpenLayers.Geometry.LinearRing(points);
		var polygonFeature = new OpenLayers.Feature.Vector(linearRing, null, style_red);
		vectorLayer.addFeatures([polygonFeature]);
		}
