var map;
var icon;
var myIcons;
var colors;
var borderClrs;
var wmMarkers;
var wmSpecies;

var epsfact;
var minpts;
var drawextra;
var showall;
var lastShownCenter;
var lastShownZoom;
var no_update;

var om;


function onLoad(lat,lng,zoom,maptype,permalinkSpecified)
{
  
if (GBrowserIsCompatible())
{
	mapDiv = document.getElementById("map");
	
	om = new OverlayMessage( mapDiv );
	
	map = new GMap2(mapDiv);
	
	map.setUIToDefault();
	
	if (locationSpecified==1) {
		map.setMapType(G_PHYSICAL_MAP);
		centerOnSearch(search_latlng,latLngBox);
	}
	else if (permalinkSpecified==1) {
		for (i=0; i<map.getMapTypes().length; i++) {
			if (map.getMapTypes()[i].getName() == maptype) {
				map.setCenter(new GLatLng(lat,lng), zoom, map.getMapTypes()[i]);
				maptypeFound = 1;
			}
		}
		if (maptypeFound != 1) {
			map.setCenter(new GLatLng(lat,lng), zoom, G_HYBRID_MAP);
		}
	}
	else {
		if (logged_in ==0) {
			map.setCenter(new GLatLng(0,0), 2, G_PHYSICAL_MAP);
		}
		else {
			map.setCenter(new GLatLng(home_lat,home_lng), 5, G_PHYSICAL_MAP);
		}
	}
		
	wmMarkers = new Array();
	wmSpecies = new Array();
	
	//Params
	epsfact = 20;
	minpts = 1;
	drawextra = 0.1;
	showall = 0;
	
	lastShownCenter = map.getCenter();
	lastShownZoom = map.getZoom();
	no_update = false;
	
	//The colors
	colors = new Array();
	colors[0] = 'green';
	colors[1] = 'blue';
	colors[2] = 'orange';
	colors[3] = 'purple';
	colors[4] = 'red';
	
	borderClrs = new Array();
	borderClrs[0] = '#ffcc66';
	borderClrs[1] = '#00ff80';
	borderClrs[2] = '#ff66ff';
	borderClrs[3] = '#6666ff';
	borderClrs[4] = '#cc66ff';
	borderClrs[5] = '#008080';
	borderClrs[6] = '#800000';
	borderClrs[6] = '#9933FF';
	borderClrs[6] = '#339966';
	borderClrs[6] = '#FF6666';
	borderClrs[6] = '#999900';
	borderClrs[6] = '#FFCC66';
	
	useIcon = [ "generic", "pestlemortar", "generic", "strawberry", "beans", "tubers", "carrot", "nuts", "cherries", "apple", "grapes", "cabbage", "tea", "fruit"];
	useIconSizeX = [ "58", "53", "58", "57", "58", "51", "66", "77", "69", "61", "69", "61", "77", "61"];
	useIconSizeY = [ "49", "55", "49", "49", "58", "53", "43", "66", "49", "51", "61", "47", "52", "53"];
	useIconShadowSizeX = [ "83", "81", "83", "82", "88", "78", "88", "111", "94", "87", "100", "85", "104", "88"];
	useIconShadowSizeY = useIconSizeY;
	useIconAnchorX = [ "29", "26", "29", "28", "29", "25", "33", "38", "34", "30", "34", "30", "38", "30"];
	useIconAnchorY = [ "24", "27", "24", "24", "29", "26", "21", "33", "24", "25", "30", "23", "26", "26"];
	useIconInfoWindowAnchorX = useIconAnchorX;
	useIconInfoWindowAnchorY = useIconAnchorY;
	
	myIcons = new Array();
	for (i=0;i<useIcon.length;i++) {
		myIcons[i] = new GIcon();
		myIcons[i].image = "img/"+useIcon[i]+".png";
		myIcons[i].shadow = "img/"+useIcon[i]+"-shadow.png";
		myIcons[i].iconSize = new GSize(useIconSizeX[i], useIconSizeY[i]);
		myIcons[i].shadowSize = new GSize(useIconShadowSizeX[i], useIconShadowSizeY[i]);
		myIcons[i].iconAnchor = new GPoint(useIconAnchorX[i], useIconAnchorY[i]);
		//myIcons[i].infoWindowAnchor = new GPoint(useIconInfoWindowAnchorX[i], useIconInfoWindowAnchorY[i]);
		myIcons[i].infoWindowAnchor = new GPoint(25, 25);
	}		
		            
	// Create our "tiny" marker icon
	icon = new GIcon();
	icon.image = "img/mm_20_red.png";
	icon.shadow = "img/mm_20_shadow.png";
	icon.iconSize = new GSize(12, 20);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);
	
	//Add move event
	GEvent.addListener(map, 'moveend', function() {
		infowindow_checker();
		if (document.getElementById('permalink').style.display == '') {
			setPermalink();
		}
	});
	
	//Add zoom event
	GEvent.addListener(map, 'zoomend', function() {
		if (map.getCurrentMapType().getName()=="Terrain" && map.getZoom()==G_PHYSICAL_MAP.getMaximumResolution()) {
			map.setMapType(G_HYBRID_MAP);
		}
		showData();
	});
	
	showData(true);
	
  }
}

function infowindow_checker() {
	if (no_update) {}
	else {
		showData();
	}
}

function setPermalink() {
	lat = map.getCenter().lat();
	lng = map.getCenter().lng();
	zoom = map.getZoom();
	maptype = map.getCurrentMapType().getName();
	document.getElementById('permalink_text').value = 'http://' + window.location.hostname + '/index.php?lat=' + lat + '&lng=' + lng + '&zoom=' + zoom + '&maptype=' + maptype;	
}

function createMarker(point,cluster,sighting_id,species_id,certainty_of_id,in_season,author_id,latin_name,common_name,species_author_id,primary_use,edible_rating,medicinal_rating,date_sighted,comment,photo,edible_uses,medicinal_uses) {
	
	if (common_name!="unspecified") {
		commonNameHTML='<div class="common_name_text" id="value1"><a style="text-decoration: none;" href="http://en.wikipedia.org/wiki/Special:Search/'+common_name+'" target="_blank">'+common_name+'</a></div>';
	}
	else {
		commonNameHTML='<div class="common_name_text" id="value1">unspecified</div>';
	}
	
	if (latin_name!="unspecified") {
		latinNameHTML='<div class="latin_name_text" id="value2"><a style="text-decoration: none;" href="http://en.wikipedia.org/wiki/Special:Search/'+latin_name+'" target="_blank">'+latin_name+'</a></div>';
	
	}
	else {
		latinNameHTML='<div class="latin_name_text" id="value2">unspecified</div>';
	}
	
	if (edible_rating==0) {
		edibilityRating="0/5";
	}
	else {
		edibilityRating="";
		for (i=1 ; i <= edible_rating ; i++) {
			edibilityRating=edibilityRating+'<img src="img/rating_apple.png" />';
		}
	}
	
	if (medicinal_rating==0) {
		medicinalRating="0/5";
	}
	else {
		medicinalRating="";
		for (i=1 ; i <= medicinal_rating ; i++) {
			medicinalRating=medicinalRating+'<img src="img/rating_heart.png" />';
		}
	}
	
	if (certainty_of_id==0) {
		certaintyRating="0/5";
	}
	else {
		certaintyRating="";
		for (i=1 ; i <= certainty_of_id ; i++) {
			certaintyRating=certaintyRating+'<img src="img/rating_star.png" />';
		}
	}
	
	if (photo != "0") {
		edibilityRatingHTML='<div class="shortproperty" id="field4">Edibility rating :<div class="mrks">'+edibilityRating+'</div></div>';
		medicinalRatingHTML='<div class="shortproperty" id="field5">Medicinal rating :<div class="mrks">'+medicinalRating+'</div></div>';
		certaintyRatingHTML='<div class="shortproperty" id="field3">Certainty of ID :<div class="mrks">'+certaintyRating+'</div></div>';
		headerHTML = '<div class="leftinfo"><img style="margin-bottom: 10px; margin-top: 25px; margin-left: 30px; float: right;" width="120" height="120" src="img/sightings/' + photo + '"/>'+commonNameHTML+latinNameHTML+edibilityRatingHTML+medicinalRatingHTML+certaintyRatingHTML+'</div>';
	}
	else {
		edibilityRatingHTML='<div id="field4" class="markerField"><div id="property4" class="markerProperty">Edibility Rating :</div><div id="value4" class="markerValue">'+edibilityRating+'</div></div>';
		medicinalRatingHTML='<div id="field5" class="markerField"><div id="property5" class="markerProperty">Medicinal Rating :</div><div id="value5" class="markerValue">'+medicinalRating+'</div></div>';
		certaintyRatingHTML='<div id="field3" class="markerField"><div id="property3" class="markerProperty">Certainty of Identification :</div><div id="value3" class="markerValue">'+certaintyRating+'</div></div>';
		headerHTML = '<div class="leftinfo2">'+commonNameHTML+latinNameHTML+'</div>'+edibilityRatingHTML+medicinalRatingHTML+certaintyRatingHTML;
	}
	
	edibleUseHTML="";
	if (edible_uses!="") {
		edibleUseHTML='<div id="field6" class="markerField"><div id="property6" class="markerProperty">Edible uses :</div><div id="value6" class="markerValueUses">'+edible_uses+'</div></div>';
	}
	medicinalUseHTML="";
	if (medicinal_uses!="") {
		medicinalUseHTML='<div id="field7" class="markerField"><div id="property7" class="markerProperty">Medicinal uses :</div><div id="value7" class="markerValueUses">'+medicinal_uses+'</div></div>';
	}
	
	inSeasonHTML='<div id="field8" class="markerField" style="padding-top:7px;"><div id="property8" class="markerProperty">In season when sighted :</div><div id="value8" class="markerValue">'+in_season+'</div></div>';
		
	var commentHTML = "";
	if (comment != "") {
		commentHTML='<div id="field8b" class="markerField" style="padding-top:3px; padding-bottom:12px;"><div id="property8b" class="markerProperty">Comments :</div><div id="value8b" class="markerValue" style="font-style:italic; font-size:0.7em; text-align:justify; padding-left:50px; max-width:320px;">"'+comment+'"</div></div>';
	}
	sightingHTML='<div id="field9" style="clear:both; float:right; #float:none; #margin-left:172px;"><div id="sighting_text" style="float:left; font-size:small; font-family: sans-serif;">Sighted by&nbsp;</div><div id="sighting_author" style="float:left; color: blue; clear:none; font-size:small; font-family: sans-serif;">'+author_id+'</div><div id="sighting_text2" style="float:left; font-size:small; font-family: sans-serif;">&nbsp;on&nbsp;</div><div id="sighting_date" style="float:left; clear:none; color: blue; font-size:small; font-family: sans-serif;">15th May 2009</div></div>';
	
	var markerHTML=headerHTML+edibleUseHTML+medicinalUseHTML+inSeasonHTML+commentHTML+sightingHTML;
	
	var deleteMarkerHTML = "";
	if (author_id == username) {
			deleteMarkerHTML = '<a href="javascript:deleteMarker('+sighting_id+')"><img src="img/delete_2.png" height="44" width="72" style="padding:4px; margin-top:4px;" alt="Delete marker" border="0" /></a>';
	}
	
	var newIcon;
	if( cluster == -1 ) {
		newIcon = new GIcon(myIcons[primary_use]);
	}
	else
	{
		newIcon = new GIcon(icon);
		var clustClr = cluster-1;
		while( clustClr >= colors.length ){clustClr = clustClr - colors.length; }
		newIcon.image = "img/mm_20_" + colors[clustClr] + ".png";
	}
	
	var rectBounds = new GLatLngBounds(new GLatLng(point.y-0.05,point.x-0.05), new GLatLng(point.y+0.05,point.x+0.05) );
	
	var marker = new GMarker(point, newIcon);
	GEvent.addListener(marker, "infowindowopen", function() { no_update = true; });
	GEvent.addListener(marker, "infowindowclose", function() { no_update = false; showData();});
	GEvent.addListener(marker, 'click', function() {
			if (map.getZoom()<G_PHYSICAL_MAP.getMaximumResolution()-3) {
				fullZoom=G_PHYSICAL_MAP.getMaximumResolution()-3;
			}
			else {
				fullZoom=G_PHYSICAL_MAP.getMaximumResolution();
			}
			zoomHTML='<div id="zoomLink" style="float:right; #float:none; #margin-left:172px; clear:both;">'+deleteMarkerHTML+'<a href="javascript:map.setCenter(new GLatLng('+point.y+','+point.x+'),'+fullZoom+');\"><img src="img/zoom2withtext.png" height="44" width="43" style="padding:4px; margin-top:4px;" alt="Zoom in" border="0" /></a></div>';
		marker.openInfoWindowHtml(markerHTML+zoomHTML);
	});
	return marker;
}

function createCluster(point,cluster,ids,size,rectBounds) 
{
	var newIcon = new GIcon(icon);
	var xspan = 36;
	var yspan = 36;
	newIcon.image = "clusterimg2.php?count="+size+"&xspan="+xspan+"&yspan="+yspan;
	newIcon.iconSize = new GSize(xspan,yspan);
	newIcon.iconAnchor = new GPoint(xspan/2,yspan/2);
	newIcon.shadow = '';
	newIcon.shadowSize = GSize(0,0);
	var marker = new GMarker(point, newIcon);
	GEvent.addListener(marker, 'click', function() {
			clusterHTML='<div id="clusterfield1" class="markerField"><div id="clusterproperty1" class="markerProperty">Cluster # : '+cluster+'</div></div>\
			<div id="clusterfield2" class="markerField"><div id="clusterproperty2" class="markerProperty">Number of items : '+size+'</div></div>\
			<a href=\"javascript:zoom('+rectBounds.getSouthWest().lng()+','+rectBounds.getNorthEast().lng()+','+rectBounds.getSouthWest().lat()+','+rectBounds.getNorthEast().lat()+')\"><img src=\"img/zoom2withtext.png\" height="44" width="43" alt=\"Zoom in\" border=\"0\" style=\"float:right;\" /></a>';
			marker.openInfoWindowHtml(clusterHTML);
	});
	
	return marker;
}

function showData(opt_forceredraw)
{	
	var forceredraw = opt_forceredraw || false;
		
	var bounds = map.getBounds();
	var newCenter = map.getCenter();
	var dist = drawextra*bounds.toSpan().lng();
	
	if( forceredraw == false && (Math.sqrt( Math.pow( lastShownCenter.lat() - newCenter.lat(), 2 ) + Math.pow( lastShownCenter.lng() - newCenter.lng(), 2)  ) < dist) && ( lastShownZoom == map.getZoom() )  )
	{
		//Movement not big enough, no redraw
		return;
	}
	
	lastShownCenter = map.getCenter();
	lastShownZoom = map.getZoom();
		
	om.Set('Loading...<br/><img src="img/loading.gif" />');
	
	var minx = -180;
	var maxx =  180;
	var miny = -90;
	var maxy =  90;
	if( map.getZoom() > 1 && bounds.isFullLat() == false )
	{
		miny = bounds.getSouthWest().lat();
		maxy = bounds.getNorthEast().lat();
	}
	if( map.getZoom() > 1 && bounds.isFullLng() == false )
	{	
		minx = bounds.getSouthWest().lng();
		maxx = bounds.getNorthEast().lng();
	}   
	
	var downloadFile = 'data2.php?maxx='+maxx+'&minx='+minx+'&maxy='+maxy+'&miny='+miny+'&minpts='+minpts+'&epsfact='+epsfact+'&drawextra='+drawextra+'&showall='+showall+'&unum='+unum;
	
	GDownloadUrl(downloadFile, function(data, responseCode) {
		if (responseCode == 200)
		{
			
			var marker;
			var wmMarkersLength = wmMarkers.length;
			var wmSpeciesLength = wmSpecies.length;
			
			var xmlDoc = GXml.parse(data);
			if (!xmlDoc) 
			{
				return;
			}
			var errors = xmlDoc.documentElement.getElementsByTagName("error");
			
			if( errors.length == 0 )
			{
				//SHOW SPECIES
				var species = xmlDoc.documentElement.getElementsByTagName("species");
				
				for (var i=0 ; i < species.length ; i++)
				{
				  	species_item = [parseInt(species[i].getAttribute("species_id")),species[i].getAttribute("common_name"),species[i].getAttribute("latin_name"),species[i].getAttribute("species_author_id"),species[i].getAttribute("primary_use"),species[i].getAttribute("edible_rating"),species[i].getAttribute("medicinal_rating"),species[i].getAttribute("edible_uses"),species[i].getAttribute("medicinal_uses")];
					wmSpecies.push(species_item);
				}
				
				//SHOW MARKERS
				var markers = xmlDoc.documentElement.getElementsByTagName("marker");
				
				for (var i=0 ; i < markers.length ; i++)
				{
				  	var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
										   parseFloat(markers[i].getAttribute("lng")));
					var species_author_id;
					var common_name;
					var latin_name;
					
					for (var j=wmSpecies.length-species.length; j < wmSpecies.length ; j++)
					{
						if (wmSpecies[j][0] == parseInt(markers[i].getAttribute("species_id")))
						{
							if (wmSpecies[j][2]=="") {
								latin_name = "unspecified";
							}
							else {
								latin_name = wmSpecies[j][2];
							}
							if (wmSpecies[j][1]=="") {
								common_name = "unspecified"
							}
							else {
								common_name = wmSpecies[j][1];
							}
							species_author_id = wmSpecies[j][3];
							primary_use = wmSpecies[j][4];
							edible_rating = wmSpecies[j][5];
							medicinal_rating = wmSpecies[j][6];
							
							edible_uses_string = wmSpecies[j][7];
							if (edible_uses_string != "") {
								edible_uses_array = edible_uses_string.split(', ');
								edible_uses_code = "";
								for (k=0;k<edible_uses_array.length;k++) {
									edible_uses_code = edible_uses_code + "<a href=\"http://en.wikipedia.org/wiki/Special:Search/" + edible_uses_array[k] + "\" target=\"_blank\" class=\"external\">" + edible_uses_array[k] + "</a>, ";
								}
								edible_uses_code = edible_uses_code.replace(/\,\ $/,'');
							}
							else { edible_uses_code = ""; }
							
							medicinal_uses_string = wmSpecies[j][8];
							if (medicinal_uses_string != "") {
								medicinal_uses_array = medicinal_uses_string.split(', ');
								medicinal_uses_code = "";
								for (k=0;k<medicinal_uses_array.length;k++) {
									medicinal_uses_code = medicinal_uses_code + "<a href=\"http://en.wikipedia.org/wiki/Special:Search/" + medicinal_uses_array[k] + "\" target=\"_blank\" class=\"external\">" + medicinal_uses_array[k] + "</a>, ";
								}
								medicinal_uses_code = medicinal_uses_code.replace(/\,\ $/,'');
							}
							else { medicinal_uses_code = ""; }
						}							
					}
					
					var in_season = markers[i].getAttribute("in_season");
					if (in_season==1) {
						in_season="Yes";
					}
					else if (in_season==0) {
						in_season="No";
					}
					else if (in_season==-1) {
						in_season="unspecified";
					}
					
					var comment = markers[i].getAttribute("comment");
					
					marker = new createMarker(point,parseFloat(markers[i].getAttribute("clust")),parseFloat(markers[i].getAttribute("sighting_id")),parseInt(markers[i].getAttribute("species_id")),markers[i].getAttribute("certainty_of_id"),in_season,markers[i].getAttribute("author_id"),latin_name,common_name,species_author_id,primary_use,edible_rating,medicinal_rating,markers[i].getAttribute("date_sighted"),comment,markers[i].getAttribute("photo"),edible_uses_code,medicinal_uses_code);
					map.addOverlay(marker);
					wmMarkers.push(marker);
				}
				
				// SHOW CLUSTERS
				var clusters = xmlDoc.documentElement.getElementsByTagName("cluster");
				
				for( var i=0 ; i < clusters.length ; i++ )
				{
					var minx = parseFloat(clusters[i].getAttribute("minx"));
					var maxx = parseFloat(clusters[i].getAttribute("maxx"));
					var miny = parseFloat(clusters[i].getAttribute("miny"));
					var maxy = parseFloat(clusters[i].getAttribute("maxy"));
					
					var clustSize = parseFloat(clusters[i].getAttribute("size"));
					var cluster = parseFloat(clusters[i].getAttribute("id"));
					
					//CREATE A SEMI-TRANSPARANT RECTANGLE
					//Choose a color mod_{colors.length}
					var clustClr = cluster;
					while( clustClr > borderClrs.length ){clustClr = clustClr - colors.length; }
					
					var rectBounds = new GLatLngBounds(new GLatLng(miny,minx),new GLatLng(maxy,maxx));
					var rect = new Rectangle(rectBounds,borderClrs[clustClr]);
					map.addOverlay(rect);
					wmMarkers.push(rect);
					
					//CREATE A NUMBER BOX FOR THE CLUSTER
					
					var ids = clusters[i].getAttribute("ids");
					var point = new GPoint(minx+(maxx-minx)/2,miny+(maxy-miny)/2);
					
					marker = createCluster(point,cluster,ids,clustSize,rectBounds);
					map.addOverlay(marker);
					wmMarkers.push(marker);
				}
				
				
				//Remove old markers
				for( var cnt=1 ; cnt<=wmMarkersLength ; cnt++ )
				{
					marker = wmMarkers.shift();
					map.removeOverlay(marker);
					
				}
				for( var cnt=0 ; cnt<wmSpeciesLength ; cnt++ ) {
					wmSpecies.shift();
				}
				
				om.Clear();
			
				lastShownCenter = map.getCenter();
				lastShownZoom = map.getZoom();
			}
			else
			{
				//error tag in xml file
				om.Set('Loading failed');
			}
		}
		else
		{
			om.Set('Loading failed');
		}
	}
	);

}

var dp_cal = null;
function checkCal(date_element) {
	if (dp_cal == null) {
		dp_cal = new Epoch('epoch_popup','popup',date_element);
	}
}

var typing_pause_common;
var typing_pause_latin;
var addPointListener;
var addMarkerFields = {};
function addPointDialogue(username, openTab)
{
	//Add click event
	addPointListener = GEvent.addListener(map, 'click', function(overlay, point) {		
		
			if (overlay) {
				
			}
			else if (point) {
				if (map.getZoom()>=G_HYBRID_MAP.getMaximumResolution()-2) {
					createMarkerInfoWindow(point.y,point.x);
				}
				else {
					alert("Please zoom in further before adding your marker");
				}
			}			
	});
	
}

var sid = new Date().getTime() + '_' + addphoto_sid;

function createMarkerInfoWindow (lat,lng) {
	
	if (map.getInfoWindow().isHidden() == false || selectingNewInfoWindow == true) {
		// scrape values from existing field
		openTab = map.getInfoWindow().getSelectedTab();
		addMarkerFields.common = $('common').value;
		addMarkerFields.latin = $('latin').value;
		addMarkerFields.certainty_0 = $('certainty').options[0].value;
		addMarkerFields.certainty_index = $('certainty').selectedIndex;
		addMarkerFields.date = $('date').value;
		addMarkerFields.in_season = $('in_season').selectedIndex;
		addMarkerFields.group_index = $('group').selectedIndex;
		addMarkerFields.groupname_index = $('groupname').selectedIndex;
		if (addMarkerFields.group_index == "2") {
			addMarkerFields.groupname_values = new Array();
			addMarkerFields.groupname_text = new Array();
			for (i=0; i<$('groupname').length; i++) {
				addMarkerFields.groupname_values[i] = $("groupname").options[i].value;
				addMarkerFields.groupname_text[i] = $("groupname").options[i].text;
			}
		}
		addMarkerFields.comments = $('comments').value;
		addMarkerFields.uploaded_img_filename = $('uploaded_img_filename').value
		addMarkerFields.uploaded_img_src = $(sid+'photoform0_img').src;
		addMarkerFields.uploaded_img_lat = new Number($('uploaded_img_lat').value);
		addMarkerFields.uploaded_img_lat_string = $(sid+'photoform0_img_lat').innerHTML;
		addMarkerFields.uploaded_img_lng = new Number($('uploaded_img_lng').value);
		addMarkerFields.uploaded_img_lng_string = $(sid+'photoform0_img_lng').innerHTML;
		addMarkerFields.uploaded_img_date = $('uploaded_img_date').value;
		addMarkerFields.uploaded_img_date_string = $(sid+'photoform0_img_date').innerHTML;
		addMarkerFields.uploaded_img_date_visibility = $(sid+'photoform0_img_date').style.visibility;
		addMarkerFields.uploaded_img_lat_visibility = $(sid+'photoform0_img_lat').style.visibility;
		addMarkerFields.uploaded_img_lng_visibility = $(sid+'photoform0_img_lng').style.visibility;
		addMarkerFields.uploaded_img_visibility = $(sid+'photoform0_img').style.visibility;
		addMarkerFields.uploaded_img_location_visibility = $(sid+'photoform0_location_choice').style.visibility;
		addMarkerFields.uploaded_gps_location_checked = $(sid+'photoform0_uploaded_gps_location').checked;
		addMarkerFields.uploaded_gps_location_disabled = $(sid+'photoform0_uploaded_gps_location').disabled;
		addMarkerFields.uploaded_gps_location_onclick = $(sid+'photoform0_uploaded_gps_location').onclick;
		addMarkerFields.uploaded_current_location_checked = $(sid+'photoform0_uploaded_current_location').checked;
		addMarkerFields.uploaded_current_location_onclick = $(sid+'photoform0_uploaded_current_location').onclick;
		addMarkerFields.uploaded_original_location_div = $(sid+'photoform0_original_location').innerHTML;
		addMarkerFields.img_submit_value = $('photoform0_submit').value;
		addMarkerFields.img_submit_onclick = $('photoform0_submit').onclick;
	}
	else {
		addMarkerFields.common = '';
		addMarkerFields.latin = '';
		addMarkerFields.certainty_index = '0';
		addMarkerFields.certainty_0 = -1;
		addMarkerFields.date = '';
		addMarkerFields.in_season = '';
		addMarkerFields.group_index = 0;
		addMarkerFields.groupname_index = 0;
		addMarkerFields.comments = '';
		addMarkerFields.uploaded_img_filename = '';
		addMarkerFields.uploaded_img_src = '';
		addMarkerFields.uploaded_img_lat = '';
		addMarkerFields.uploaded_img_lat_string = '';
		addMarkerFields.uploaded_img_lng = '';
		addMarkerFields.uploaded_img_lng_string = '';
		addMarkerFields.uploaded_img_date = '';
		addMarkerFields.uploaded_img_date_string = '';
		addMarkerFields.uploaded_img_date_visibility = 'hidden';
		addMarkerFields.uploaded_img_lat_visibility = 'hidden';
		addMarkerFields.uploaded_img_lng_visibility = 'hidden';
		addMarkerFields.uploaded_img_visibility = 'hidden';
		addMarkerFields.uploaded_img_location_visibility = 'hidden';
		addMarkerFields.uploaded_gps_location_checked = false;
		addMarkerFields.uploaded_gps_location_disabled = true;
		addMarkerFields.uploaded_gps_location_onclick = null;
		addMarkerFields.uploaded_current_location_checked = true;
		addMarkerFields.uploaded_current_location_onclick = null;
		addMarkerFields.uploaded_original_location_div = '<input type="radio" id="'+sid+'photoform0_uploaded_current_location" name="'+sid+'photoform0_marker_location" checked=true/> Use current latitude and longitude';
		addMarkerFields.img_submit_value = 'Next ->';
		addMarkerFields.img_submit_onclick = function () {map.getInfoWindow().selectTab(0);};
	}
	dp_cal=null; //if a calendar has already been created by another window box, we want to destroy it to make sure it recreates itself with the new infowindow
	var validator = "validateAddPointForm("+lat+","+lng+",document.getElementById(\'addPointForm\'),false); addPointValidated=false;";
	if (addMarkerFields.group_index == "2") {
		groupnames_open = '<select style="margin-left:8px;" id="groupname" name="groupname">';
		groupnames_close = '</select>';
		groupnames_options = '';
		for (i=0; i<addMarkerFields.groupname_values.length; i++) {
			groupnames_options = groupnames_options + '<option value="'+addMarkerFields.groupname_values[i]+'">'+addMarkerFields.groupname_text[i]+'</option>';
		}
		groupnames_html = groupnames_open+groupnames_options+groupnames_close;
	}
	else {
		groupnames_html = '<select style="margin-left:8px; display:none;" id="groupname" name="groupname"></select>';
	}
	requiredInfo = '<form onsubmit="javascript:'+validator+' return false;" method="get" id="addPointForm"> \
		<div class="markerField" style="margin-top:10px;">\
			<div class="markerInputProperty">Common name : </div>\
			<div class="markerInput"><input value ="'+addMarkerFields.common+'" type="text" id="common" style="width: 200px" onkeyup="elementval=this.value; elementid=this.id; clearTimeout(typing_pause_common); typing_pause_common=setTimeout(\'showResult(elementval,elementid)\',750);" autocomplete="off">\
			<div class="livesearch1" style="display:none;" id="common_hints"></div></div>\
				<div class="form_errors" id="common_error"></div></div>\
		<div class="markerField"><div class="markerInputProperty">Latin name : </div>\
			<div class="markerInput"><input value ="'+addMarkerFields.latin+'" type="text" id="latin" style="width: 200px" onkeyup="elementval=this.value; elementid=this.id; clearTimeout(typing_pause_latin); typing_pause_latin=setTimeout(\'showResult(elementval,elementid)\',750);" autocomplete="off">\
				<div class="livesearch2" style="display:none;" id="latin_hints"></div></div>\
			<div class="form_errors" id="latin_error"></div></div>\
		<div class="markerField"><div class="markerInputProperty">Certainty of plant identification: </div>\
			<div class="markerInput"><select id="certainty" name="certainty" onclick="javascript:if (this.options[0].value==\'-1\') {this.options[0].value=0;};"> \
				<option value="'+addMarkerFields.certainty_0+'" selected="selected">0</option> \
				<option value="1">1</option> \
				<option value="2">2</option> \
				<option value="3">3</option> \
				<option value="4">4</option> \
				<option value="5">5</option> \
				</select></div>\
			<div class="form_errors" id="certainty_error"></div></div> \
		<div class="markerField"><div class="markerInputProperty">Date sighted : </div>\
			<div class="markerInput"><input value="'+addMarkerFields.date+'" id="date" type="text" autocomplete="off" onmouseover="javascript:checkCal(this)" style="width: 200px"></div>\
			<div class="form_errors" id="date_error"></div></div> \
		<div class="markerField"><div class="markerInputProperty">In season when sighted\?: </div>\
			<div class="markerInput"><select id="in_season" name="in_season">\
				<option value="-1" selected="selected">--</option> \
				<option value="0">no</option> \
				<option value="1">yes</option> \
				</select></div></div> \
		<div class="markerField"><div class="markerInputProperty">Make this marker visible to: </div>\
			<div class="markerInput"><select id="group" name="group" onchange="chainedSelect(window.self,this.value,unum)">\
				<option value="public" selected="selected">everyone</option> \
				<option value="private">me only</option> \
				<option id="mygroup" value="mygroup">one of my groups</option> \
				<option value="newgroup">a new group</option> \
				</select></div> \
				'+groupnames_html+'</div> \
		<div class="markerField"><div class="markerInputProperty">Additional comments : </div>\
			<div class="markerInput"><input value="'+addMarkerFields.comments+'" type="text" id="comments" maxlength="200" style="width:200px;"></div>\
			</div> \
		<input type="hidden" id="author" value="'+username+'"> \
		<input type="hidden" id="uploaded_img_filename" value="'+addMarkerFields.uploaded_img_filename+'"> \
		<input type="hidden" id="uploaded_img_lat" value="'+addMarkerFields.uploaded_img_lat+'"> \
		<input type="hidden" id="uploaded_img_lng" value="'+addMarkerFields.uploaded_img_lng+'"> \
		<input type="hidden" id="uploaded_img_date" value="'+addMarkerFields.uploaded_img_date+'"> \
		<div style="float:right; #float:none; #margin-left:370px; clear:both; margin-top:10px;"><input type="Submit" value="Add marker"></div></form>';
	checkFileFunction = "checkFile('photoform0', '"+sid+"');";
	photoInfo = '<form class="photoupload_form" METHOD="POST" enctype="multipart/form-data" name="photoform0" id="photoform0" action="uploader2/upload.cgi?sID='+sid+'photoform0" target="photoform0_iframe"> \
			<div class="markerField" style="margin-top:8px;"> \
			<div class="markerInputProperty" style="width: 130px;">Choose photo : </div> \
				<div class="markerInput"><input id="filename_'+sid+'" type="file" name="file0" onchange="'+checkFileFunction+'" /></div> \
			</div> \
			<div class="markerField" style="margin-top: 10px;"> \
			<div class="markerInputProperty" style="width: 130px; text-align: right; padding-top: 20px;"> \
				<div style="visibility: '+addMarkerFields.uploaded_img_date_visibility+';" id="'+sid+'photoform0_img_date">'+addMarkerFields.uploaded_img_date_string+'</div> \
				<div style="visibility: '+addMarkerFields.uploaded_img_lat_visibility+'; margin-top: 5px;" id="'+sid+'photoform0_img_lat">'+addMarkerFields.uploaded_img_lat_string+'</div> \
				<div style="visibility: '+addMarkerFields.uploaded_img_lng_visibility+'; margin-top: 5px;" id="'+sid+'photoform0_img_lng">'+addMarkerFields.uploaded_img_lng_string+'</div> \
			</div> \
			<div class="markerInput" style="width: 210px; height:100px; margin-left: 20px;"> \
				<img style="position: absolute; visibility: '+addMarkerFields.uploaded_img_visibility+';" src="'+addMarkerFields.uploaded_img_src+'" id="'+sid+'photoform0_img"> \
					<div style="visibility: hidden; position: relative; top:40px; left:25px;" id="'+sid+'photoform0_progress_gubbins"> \
						<div style="width: 10em; height: 1em; position: relative; background: #cccccc; float: left;" id="progressb1" class="progressBox"> \
							<div style="width: 0; height: 100%; position: absolute; top: 0; left: 0; background: #00df00;" class="progressBar" id="'+sid+'photoform0_progress">&nbsp;</div> \
						</div> \
						<div class="fileName" id="'+sid+'photoform0_fileName"></div> \
					</div> \
				</div> \
			</div> \
			</form> \
			<div style="visibility: '+addMarkerFields.uploaded_img_location_visibility+'; padding-top: 10px;" class="markerField" id="'+sid+'photoform0_location_choice"> \
			<div class="markerInputProperty" style="width: 130px; padding-top: 20px;">Marker location : </div> \
				<div style="font-size: 0.7em;" class="markerInput"> \
					<input type="radio" id="'+sid+'photoform0_uploaded_gps_location" name="'+sid+'photoform0_marker_location"/> Use latitude and longitude from image<br /> \
					<div id="'+sid+'photoform0_original_location">'+addMarkerFields.uploaded_original_location_div+'</div> \
					<input type="radio" id="'+sid+'photoform0_uploaded_new_location" name="'+sid+'photoform0_marker_location" value="" onclick="selectNewInfoWindowLocation(\''+sid+'photoform0\');" /> Choose new latitude and longitude \
				</div> \
			</div> \
			<div style="float:right; #float:none; #margin-left:370px; clear:both;"><input id="photoform0_submit" type="button" value="'+addMarkerFields.img_submit_value+'"></div> \
			<iframe style="border: 0; height: 0; width: 0; padding: 0; position: absolute; visibility: hidden" name="photoform0_iframe" id="photoform0_iframe" src="uploader2/blank.html" class="loader"></iframe>';
	requiredTab = new GInfoWindowTab('Basic info', requiredInfo);
	photoTab = new GInfoWindowTab('Add photo', photoInfo);
	map.openInfoWindowTabsHtml(new GLatLng(lat,lng), [requiredTab, photoTab], {selectedTab:openTab,noCloseOnClick:true,onOpenFn:function () {initFormChoices()}});
	if (selectingNewInfoWindow == true) {
		selectingNewInfoWindow = false;
	}
}

function initFormChoices() {
	 $('certainty').selectedIndex = addMarkerFields.certainty_index;
	 $('in_season').selectedIndex = addMarkerFields.in_season;
	 $('group').selectedIndex = addMarkerFields.group_index;
	 $('groupname').selectedIndex = addMarkerFields.groupname_index;
	 
	 $(sid+'photoform0_uploaded_gps_location').checked = addMarkerFields.uploaded_gps_location_checked;
	 $(sid+'photoform0_uploaded_gps_location').disabled = addMarkerFields.uploaded_gps_location_disabled;
	 $(sid+'photoform0_uploaded_current_location').checked = addMarkerFields.uploaded_current_location_checked;
	 $(sid+'photoform0_uploaded_gps_location').onclick = addMarkerFields.uploaded_gps_location_onclick;
	 $(sid+'photoform0_uploaded_current_location').onclick = addMarkerFields.uploaded_current_location_onclick;
	 
	 $('photoform0_submit').onclick = addMarkerFields.img_submit_onclick;
}

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr, validateSilently){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		if (validateSilently == false) {
			document.getElementById("date").value="The date format should be : mm/dd/yyyy";
		}
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		if (validateSilently == false) {
			document.getElementById("date").value="Please enter a valid month";
		}
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		if (validateSilently == false) {
			document.getElementById("date").value="Please enter a valid day";
		}
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		if (validateSilently == false) {
			document.getElementById("date").value="Please enter a valid 4 digit year between "+minYear+" and "+maxYear;
		}
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		if (validateSilently == false) {
			document.getElementById("date").value="Please enter a valid date";
		}
		return false
	}
return true
}

function findField (field,field_names) {
	for (j=0; j<field_names.length; j++) {
		if (field == field_names[j]) {
			return j;
		}
	}
	return -1;
}

var getstr;
var addPointValidated = false;
function validateAddPointForm (lat,lng,addPointForm,validateSilently) {
	addPointValidated = false;
	var field_names = ['latin', 'common', 'date', 'certainty'];
	var field_acceptable = [true, true, true, true];
	var field_values = [];
	for (i=0; i<2; i++) {
		field_values[i]=document.getElementById(field_names[i]).value;
		if (field_values[i].length==0) {
			field_acceptable[i]=false;
		}
	}
	date_value=document.getElementById("date").value;
	if (isDate(date_value, validateSilently) == false) {
		field_acceptable[2]=false;
	}
	certainty_value=document.getElementById("certainty").value;
	if (certainty_value == -1) {
		field_acceptable[3]=false;
	}
	group_value=document.getElementById("group").value;
	var group_id_value;
	if (group_value == "mygroup") {
		group_id_value = document.getElementById("groupname").value;
	}
	else if (group_value == "public") {
		group_id_value = 10000000;
	}
	else if (group_value = "private") {
		group_id_value = unum;
	}
	inseason_value=document.getElementById("in_season").value;
	group_value=document.getElementById("group").value;
	comment_value=document.getElementById("comments").value;
	author_value=document.getElementById("author").value;
	img_filename_value = $('uploaded_img_filename').value;
	img_date_value = $('uploaded_img_date').value;
	img_lat_value = $('uploaded_img_lat').value;
	img_lng_value = $('uploaded_img_lng').value;
	var error_messages = ['Please specify the plant\'s latin name', 'Please specify the plant\'s common name', 'Please specify a date in mm/dd/yyyy format', 'Please specify your certainty of the plant identification'];
	
	if ((field_acceptable[0] == true || field_acceptable[1] == true) && field_acceptable[2] == true && field_acceptable[3] == true) {
		addPointValidated = true;
		getstr = "?lat="+lat+"&lng="+lng+"&latin="+field_values[0]+"&common="+field_values[1]+"&author="+author_value+"&date="+date_value+"&certainty="+certainty_value+"&in_season="+inseason_value+"&gid="+group_id_value+"&comment="+comment_value+"&img_fn="+img_filename_value+"&img_date="+img_date_value+"&img_lat="+img_lat_value+"&img_lng="+img_lng_value;
		if (validateSilently != true) {
			submissionCheck(lat,lng,getstr,field_acceptable[0],field_acceptable[1]);
		}
		return;
	}
	else {
		if (validateSilently != true) {
			//print errors;
			for (i=0; i<field_names.length; i++) {
				if (field_names[i] != "author") {
					if (field_acceptable[i] == false) {
						document.getElementById(field_names[i] + "_error").innerHTML="*";
					}
					else {
						document.getElementById(field_names[i] + "_error").innerHTML="";
					}
				}
			}
			alert("Some required information is missing. Please complete the fields marked with a *");
		}
	}
}

function submissionCheck(lat,lng,getstr,latin_acceptable,common_acceptable) {
	if (latin_acceptable == false && common_acceptable == true) {
		//do you want to force proceed?
		if (confirm("You have not entered a latin name.  We can only link you new markers to entries in the database of the same species if you specify the latin name.  If you wish to return and specify the latin name please press cancel.  Otherwise choose OK to submit your marker as a new species.")) {
			addPointToDB(lat,lng,getstr);
			return;
		}
	}
	else {
		addPointToDB(lat,lng,getstr);
		return;
	}
}
	
	
function addPointToDB (lat,lng,getstr) {
		GDownloadUrl('addpoint2.php'+getstr, function(addPointData, responseCode) {
			if (responseCode == 200) {
				var addpointresults = eval("(" + addPointData + ")");
				var success = addpointresults.success;
				if (success == 1) {
					map.closeInfoWindow();
					sid = new Date().getTime() + '_' + addphoto_sid;
					showData(true);
				}
				else {}
			}
			else {}
		});		
}

function cancelAddPoint(username) {
	GEvent.removeListener(addPointListener);
}

function deleteMarker (sighting_id) {
	GDownloadUrl('deletemarker.php?sighting_id='+sighting_id+'&username='+username, function(deleteMarkerData, responseCode) {
			if (responseCode == 200) {
				var deleteMarkerresults = eval("(" + deleteMarkerData + ")");
				var success = deleteMarkerresults.success;
				if (success == 1) {
					map.closeInfoWindow();
					showData(true);
				}
				else {}
			}
			else {}
		});
}

function zoom(minx,maxx,miny,maxy)
{
	var center = new GLatLng(miny+(maxy-miny)/2,minx+(maxx-minx)/2);
	
	var oldZoomLevel = map.getZoom();
	
	var sw = new GLatLng(miny,minx);
	var ne = new GLatLng(maxy,maxx);
	var bounds = new GLatLngBounds(sw, ne);
	var zoomLevel = map.getBoundsZoomLevel(bounds)
	
	if( oldZoomLevel == zoomLevel ){ zoomLevel++; }
	
	map.closeInfoWindow();
	
	map.setCenter(center, zoomLevel );
}


//_________RECTANGLE__________

// A Rectangle is a simple overlay that outlines a lat/lng bounds on the
// map. It has a border of the given weight and color and can optionally
// have a semi-transparent background color.
function Rectangle(bounds, opt_color, opt_weight) {
  this.bounds_ = bounds;
  this.weight_ = opt_weight || 2;
  this.color_ = opt_color || "#888888";
}
Rectangle.prototype = new GOverlay();

// Creates the DIV representing this rectangle.
Rectangle.prototype.initialize = function(map) {
  // Create the DIV representing our rectangle
  var div = document.createElement("div");
  div.style.border = this.weight_ + "px solid " + this.color_;
	div.style.backgroundColor = this.color_;
	div.style.MozOpacity = ".35";
	div.style.filter = "alpha(opacity=35);";
	div.style.opacity=".35";
  div.style.position = "absolute";

  // Our rectangle is flat against the map, so we add our selves to the
  // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
  // below the marker shadows)
  map.getPane(G_MAP_MAP_PANE).appendChild(div);

  this.map_ = map;
  this.div_ = div;
}

// Remove the main DIV from the map pane
Rectangle.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
}

// Copy our data to a new Rectangle
Rectangle.prototype.copy = function() {
  return new Rectangle(this.bounds_, this.weight_, this.color_,
                       this.backgroundColor_, this.opacity_);
}

// Redraw the rectangle based on the current projection and zoom level
Rectangle.prototype.redraw = function(force) {
	// We only need to redraw if the coordinate system has changed
	if (!force) return;
	
	// Calculate the DIV coordinates of two opposite corners of our bounds to
	// get the size and position of our rectangle
	var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
	var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());
	
	if( c1.x > c2.x )
	{
		// Rectangle drawn wrong over the world
		var boundNE = this.map_.getBounds().getNorthEast();
		var boundNExPix = this.map_.fromLatLngToDivPixel(boundNE).x;
		c2.x = c1.x + (boundNExPix-c1.x)/(boundNE.lng()-this.bounds_.getSouthWest().lng())*(this.bounds_.getNorthEast().lng()-this.bounds_.getSouthWest().lng());
	}
	
	// Now position our DIV based on the DIV coordinates of our bounds
	this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
	this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
	this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px";
	this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_) + "px";
}
