
function bindClearGazToKeyDown()
{
	$("#"+gazetteerid).bind("keydown", clearGazResults);	
}

function clearGazResults()
{
	$("#gazResults").empty();
}

function bindClearSpeciesToKeyDown()
{
	$("#"+speciessearchid).bind("keydown", clearSpeciesSearchResults);	
}

function clearSpeciesSearchResults()
{
	$("#search-results").empty();
}

function bindAutoGazSearch()
{
	$("#"+gazetteerid).bind("keyup", autoSearchGazetter);  
}

function clearGazExampleOnFocus()
{
	$("#"+gazetteerid).bind("focus", clearGazetteer);	
}

function showGazExampleOnBlur()
{
	$("#"+gazetteerid).bind("blur", showGazExample);
}

function clearSpeciesOnFocus()
{
	$("#"+searchspeciesid).bind("focus", clearSearchSpecies); 
}

function showSpeciesExampleOnBlur()
{
	$("#"+searchspeciesid).bind("blur", showSearchSpeciesExample);  	
}

function showSearchSpeciesExample()
{
	$("#"+searchspeciesid).val("e.g. Robin");
}

function clearSearchSpecies()
{
	$("#"+searchspeciesid).val("");
}

function showGazExample()
{
	$("#"+gazetteerid).val("e.g. Newcastle");
}
   
function clearGazetteer()
{				
	$("#"+gazetteerid).val("");
}  

function redirect(url)
{
	window.location = url;
}

function closeDialog(id)
{
	if($("#"+id).dialog('isOpen')==true)
	{
		$("#"+id).dialog('close');	
	}
}

function openDialog(id, html)
{
	if($("#"+id).dialog('isOpen')==true)
	{
		closeDialog(id);	
	}	
	
	$("#"+id+" > p").html(html);
	
	$("#"+id).dialog('open');
}

function initialiseNextStepDialog(width, height)
{
	initialiseDialog("next_step", "Proceed ...", height, width);
}

function initialiseMessageDialog(width, height)
{
	initialiseDialog("notification", "Message ...", height, width);
}

function initialiseClusterDialog(width, height)
{
	initialiseDialog("clusterdialog", "Clustering ...", height, width);
}

function initialiseDialog(id, title, height, width)
{
	$.ui.dialog.defaults.bgiframe = true;
	$("#"+id).dialog({
		title: title,
		autoOpen:false,
		modal:true,
		stack:true,
		height:height,
		width:width,
		resizable:false
	});
}

var step = "";
var species_detail_url = "../../search/species/details/";

var searchrecordsurl = '../explore/records/?format=json&'
			
//redefine search for records url, based on updated bbox			
function searchRecords(id_west, id_south, id_east, id_north)
{				
	var bbox = parseFloat($("#"+id_west).val())+","+parseFloat($("#"+id_south).val())+","+parseFloat($("#"+id_east).val())+","+parseFloat($("#"+id_north).val());				
	var url = searchrecordsurl;
	url += "bbox="+bbox+"&q=";
	
	return url;				
}

var openlayers_wkt_reader;
var gmap;
var geoXml;
var geocoder;
var south_west;
var north_east;
var maxExtent;
var centrePoint;

var dragStartPointMarker;
var dragStartPointMap;

function autoSearchGazetter(event)
{
	var id = event.target.id;
	var value = String($("#"+id).val());                
	if(value.length > 2)
	{
		searchPlaces(id);
	}                
}

//initialise gazetteer search
function initGaz()
{					
	openlayers_wkt_reader = new OpenLayers.Format.WKT();
			
	geocoder = new GClientGeocoder();
	
	south_west = new GLatLng(54.4459927, -2.7011446);
	north_east = new GLatLng(55.8200714, -0.7469102);
	
	maxExtent = new GLatLngBounds(south_west, north_east);
	centrePoint = maxExtent.getCenter();
	
	limitGazToUK();
}

function limitGazToUK()
{
	geocoder.setBaseCountryCode('uk');
	geocoder.setViewport(maxExtent);	
}

function searchPlaces(gaz_id)
{
	var searchterm = $("#"+gaz_id).val();

	var gridMatch = /^[A-Z]{2}\d{6}$/;

	var tosearchfor = "";
	limitGazToUK();

	if(gridMatch.test(searchterm))
	{		
		tosearchfor = sixFigureGridRefToLatLng(searchterm, true);					
		geocoder.getLocations(tosearchfor, processGazResults)
		//can now use latlng.lat, and latlng.lng to query google geocoding services
	}
	else
	{
		tosearchfor = searchterm;					
		geocoder.getLocations(tosearchfor, processGazResults);		
	}				
}

function processGazResults(results)
{	
	clearGazResults();
	var zoomLevel = 5;
	var gazhtml = "";
	var no_results_msg = "<em>No results to display</em><br>";
	var gazResultsToDisplay = new Array();
	
	var match_counter = 0;
	
	if(results.Placemark)
	{
		if(results.Placemark.length > 0)
		{
			for(var i = 0; i < results.Placemark.length; i++)
			{
				var address = "";
				var addressaccuracy = 0;
				
				address = results.Placemark[i].address;			
				addressaccuracy = results.Placemark[i].AddressDetails.Accuracy;
				
				if ((address != undefined)||(address != "undefined"))
				{
					if (ajax != null)
					{					
						ajax.abort();
					}
					
					var point_ = results.Placemark[i].Point;
					
					ajax = $.getJSON("../../validlocation/?lat="+point_.coordinates[1]+"&lon="+point_.coordinates[0], function (data){
							
							var valid = Boolean(data[0].Valid);
							
							if (valid == true)
							{
								var point = new OpenLayers.Geometry.Point(point_.coordinates[0], point_.coordinates[1]);
					
									if(addressaccuracy > 3)
									{
										switch(addressaccuracy)
										{
											case 4:
												zoomLevel = 12;
											break;
											case 5:
												zoomLevel = 11;
											break;
											case 6:
												zoomLevel = 10;
											break;	
											case 7:
												zoomLevel = 9;
											break;
											case 8:
												zoomLevel = 8;
											break;
											case 9:
												zoomLevel = 7;
											break;
										}
						
										var _event = "zoomTo("+point.x+","+point.y+","+zoomLevel+"); ";
						
										if(searchtype == "record")
										{
											_event += "setMarker("+point.x+","+point.y+");";
										}
						
										var gazlink = "<a onclick=\""+_event+"\" href=\"#map\">"+address+"</a><span>&nbsp;</span><br>";
																				
										$("#gazResults").append("<strong>- </strong>"+gazlink);
									}
							}
							else
							{
								$("#gazResults").append(no_results_msg);
							}
					});
				}			
			}
		}
		else
		{
			$("#gazResults").append(no_results_msg);	
		}
		
	}	
	else
	{		
		$("#gazResults").append(no_results_msg);		
	}			
}

function setMarker(lng, lat)
{
	newgmarker.setLatLng(new GLatLng(lat, lng));
}

//zoom to point at given zoom level
function zoomTo(lng, lat, zoom)
{
	gmap.setCenter(new GLatLng(lat, lng), zoom);
}
			
//define new location for record
//for gazetteer
function setLocation(lng, lat)
{
	var location = "POINT("+lng+" "+lat+")";    
	$("#id_1-location").val(location);
	
	var markerlocation = new GLatLng(lat, lng);
	//newgmarker = new GMarker(markerlocation, marker_options);
	newgmarker = initMarkerEvents(newgmarker);	
	//gmap.addOverlay(newgmarker);
	newgmarker.setLatLng(markerlocation);

}

//if accessing the geocoder url directly
function configureGazetteerSearch()
{
	var dict = new Object();
	var params = new Array()
	var values = new Array()
	
	params.push('sensor');
	values.push(false);
	params.push('format') ;
	values.push('json');
	params.push('oe');
	values.push('utf8')
	params.push('ll');
	values.push(-1.61567+","+54.983);
	params.push('gl');
	values.push('uk');
	params.push('spn');
	values.push(maxExtent.toSpan())
	params.push('output');
	values.push('json');
		
	dict.params = params;
	dict.values = values;
	
	var google_geocoding_url = "http://maps.google.com/maps/geo?";
	
	for(var i = 0; i < dict.params.length; i++)
	{
		google_geocoding_url += dict.params[i]+"="+dict.values[i]+"&";                   
	}
	
	google_geocoding_url += "?q="	
}

//var media_url;
var marker_options;
var single_marker_image;
var icon_single;

function initSingleMarker()
{

//media_url = "{{MEDIA_URL}}";

single_marker_image = media_url+"sumo/tpl/img/map-key-single.png";
icon_single = new GIcon(G_DEFAULT_ICON);
icon_single.image = single_marker_image;
icon_single.iconSize = new GSize(23,29);

marker_options = { 
	draggable: true,
	bouncy: true,
	autoPan:true,
	dragCrossMove:true,
    icon: icon_single
};

}

function setInitialExtent()
{
	$("#north").val(north_east.lat());
	$("#south").val(south_west.lat());
	$("#east").val(north_east.lng());
	$("#west").val(south_west.lng());			
}

function bindClearMapToSearch(id)
{
	$("#"+id).bind("keydown", function(){
		clearAllMarkers();
		addKMLExtent();
	});
	
	$("#jquery-live-search").empty();
	
}

function clearAllMarkers()
{	
	gmap.clearOverlays();	
	markerClusterer.clearMarkers();	
}

var static_marker_options;
var single_static_marker_image;
var icon_single_static;

function initStaticMarker()
{

single_static_marker_image = media_url+"sumo/tpl/img/map-key-single.png";
icon_single_static = new GIcon(G_DEFAULT_ICON);
icon_single_static.image = single_static_marker_image;
icon_single_static.iconSize = new GSize(23,29);

static_marker_options = {	
	clickable: true,
	draggable: false,
	bouncy: false,
	autoPan:false,
	dragCrossMove:false,
    icon: icon_single_static,
	zIndexProcess: setZIndexOrder
}

}

 function setZIndexOrder(marker,b) {       
		return 10000000;
      }


function createStaticMarker(lat, lng, title, species_id, species_record_id, index)
{		
	var point = new GLatLng(lat, lng);
	var marker = new GMarker(point, static_marker_options);
	marker.species_title = title;
	marker.species_id = species_id;
	marker.species_record_id = species_record_id;
	marker.index = index;	
	return marker;
}

function resetMap()
{
	gmap.setCenter(centrePoint, 8);	
}


//used in inline_summary
function addStaticMap(location, page)
{
var wkt_f = new OpenLayers.Format.WKT();
var wkt_location = wkt_f.read(location);

var width = 200;

if(page == "summary")
{
	width = 600;	
}

var google_static = "http://maps.google.com/maps/api/staticmap?center="+wkt_location.geometry.y+","+wkt_location.geometry.x+"&markers=color:red|"+wkt_location.geometry.y+","+wkt_location.geometry.x+"&zoom=14&size="+width+"x200&maptype=roadmap&sensor=false&key="+google_static_key;

return google_static;
}

function initMarkerEvents(newgmarker)
{
    /*issue relates to species_detail_url*/
	GEvent.addListener(newgmarker, "click", function(latlng)
	{ 							
		gmap.openInfoWindowHtml(latlng, "<label>I saw :</label> <br><a href=\""+species_detail_url+species_id+"\"><strong>"+species+"</strong></a><label> at "+latlng+"</label>");
	});
	
	GEvent.addListener(newgmarker, "dblclick", function(latlng)
	{ 			
		gmap.closeInfoWindow();
	});
	
	GEvent.addListener(newgmarker, "dragend", function(latlng){
		validateLocationDragMarker(latlng);
	});	
		
	GEvent.addListener(newgmarker, "dragstart", function(latlng){			 
			dragStartPointMarker = latlng;											 
	});
	
	return newgmarker;
}

function initMap(mapid) {
  if (GBrowserIsCompatible()) {
	
	var mapTypes = G_DEFAULT_MAP_TYPES;
	for(var i = 0; i < mapTypes.length; i++){
		mapTypes[i].getMaximumResolution = function(latlng){ return 18;};
		mapTypes[i].getMinimumResolution = function(latlng){ return 8;};
	}

	gmap = new GMap2(document.getElementById(mapid), {mapTypes: mapTypes});
    resetMap();
		
    if (needmarker == true)
	{        
		newgmarker = new GMarker(centrePoint, marker_options);								
        newgmarker = initMarkerEvents(newgmarker);			
        gmap.addOverlay(newgmarker);

		addCentreScreenOverlay(mapid);

        GEvent.addListener(gmap, "moveend", validateLocationDragMap);	
    	GEvent.addListener(gmap, "zoomend", validateLocationDragMap);

	}	 
	
	gmap.addControl(new GSmallMapControl());  
  gmap.addControl(new GMapTypeControl()); 
  }
  
  
}

function addCentreScreenOverlay(mapid)
{
	var width = $("#"+mapid).width() / 2;
var height=	$("#"+mapid).height() / 2;
	
	var screen_overlay = new GScreenOverlay("http://maps.gstatic.com/intl/en_ALL/mapfiles/drag_cross_67_16.png", new GScreenPoint(width,height, "pixels"), new GScreenPoint(7,0, "pixels"), new GScreenSize(16, 16, "pixels"));	
	gmap.addOverlay(screen_overlay);
}

function addKMLExtent()
{			
    geoXml = new GGeoXml("http://s.eyeproject.org.uk/kml/new_eyerecordingextents_kml.kml");    
	gmap.addOverlay(geoXml);
	geoXml.redraw(true);		
}

function validateLocationDragMarker(latlng)
{
	if (ajax != null)
	{
		ajax.abort();
	}	
	var point = "lat="+latlng.lat()+"&lon="+latlng.lng();
	
	ajax = $.getJSON("../../validlocation/?"+point, function (data){
			
			var valid = Boolean(data[0].Valid);
			
			if (valid == false)
			{				
				newgmarker.setLatLng(dragStartPointMarker);					
			}
			else
			{
				gmap.setCenter(latlng);	
			}
			
	});
}

function getMapCentre()
{
	return gmap.getCenter();			
}

function validateLocationDragMap()
{
	var centre = getMapCentre();
    
	if (ajax != null)
	{
		ajax.abort();
	}	
	var point = "lat="+centre.lat()+"&lon="+centre.lng();
	
	ajax = $.getJSON("../../validlocation/?"+point, function (data){
			
			var valid = Boolean(data[0].Valid);
			
			if (valid == true)
			{				
				newgmarker.setLatLng(centre);
				dragStartPointMap = centre;
                setLocation(centre.lng(), centre.lat());
			}
			else
			{				
				newgmarker.setLatLng(dragStartPointMap);
			}			
	});
}

function sixFigureGridRefToLatLng(gridref, forgaz)
{
	var os6x = getOSRefFromSixFigureReference(gridref);

	var easting = os6x.easting;
	var northing = os6x.northing;

	var latlng = os6x.toLatLng();

	var lat = latlng.lat;
	var lng = latlng.lng;
	
	if(forgaz)
	{
		var coordinate = new GLatLng(lat, lng);
	}
	else
	{
		var coordinate = new Object()        
		coordinate.lat = lat;
		coordinate.lng = lng;	
	}        
	return coordinate;
}

function addColumnHeadingRecordTable(id)
{
	$("#"+id).append("<tr><td><strong>Species:</strong></td><td><strong>Date sighted:</strong></td><td><strong>Options:</strong></td></tr>");	
}

function resetRecordTable(rowcontainerid)
{	 
	$("#"+rowcontainerid).empty();
}

function appendNewRowRecords(rowcontainerid, html)
{	
	$("#"+rowcontainerid).append(html);
}

function createMatchedRecords(odd_even, species_id, species_record_id, species__common_name, species__scientific_name, location, description, datetime)
{
	var html = "";
	var htmlclass = "";	
	var result = String(odd_even / 2);
	
	html = "<tr id=row_"+odd_even+"";
	
	if(result.indexOf(".")!=-1)
	{
		htmlclass = "highlight";
		html += " class=\""+htmlclass+"\">";
	}	
	else
	{
		html += ">";		
	}
	
	var startindex = 0;
	
	html += "<td>";
	html += "<a href=\"/search/species/details/"+species_id+"\">"+odd_even +") " + species__common_name + " "+species__scientific_name+"</a>";
	html += "</td>";		
	
	html += "<td>";
	html += datetime;
	html += "</td>";		
	
	html += "<td>";	
	html += "<a href=\"/search/records/details/"+species_record_id+"\">View</a>"
	html += "</td>";		
	
	html += "</tr>";
	
	return html;
}

function processNonPrettyDateTime(datetime)
{
	var datetimesplit = datetime.split(" ");
	var date_ = datetimesplit[0];
	var date = String(date_).split("-");
	return date[2]+"/"+date[1]+"/"+date[0];
}

function showNumberOfMatches(count)
{
	$("#numberofmatchedrecords").html(count);
}
var clustermarkersdefault = new Array();
var clustermarkers = new Array();
var markerClusterer;
//var markerClustererDefault;
var maxZoomLevel = 12;
var gridSize = 200;
var styles = null;

function refreshDefaultClusters()
{
	if (markerClusterer != null) 
	{
    	markerClusterer.clearMarkers();
    }			
	
	markerClusterer = new MarkerClusterer(gmap, clustermarkersdefault, {styles: styles, maxZoom: maxZoomLevel, gridSize: gridSize});
	
	resetMap();
	
}

function refreshClusters()
{
	if (markerClusterer != null) 
	{
    	markerClusterer.clearMarkers();
    }			

	markerClusterer = new MarkerClusterer(gmap, clustermarkers, {styles: styles, maxZoom: maxZoomLevel, gridSize: gridSize});
	
	clustermarkers.length = 0;
}

function addMarkerToDefaultCluster(marker)
{
	clustermarkersdefault.push(marker);
}

function addMarkerToCluster(marker)
{
	clustermarkers.push(marker);
}

function checkDefaultClustering()
{
	if($("#cluster_on").attr("checked") == true) 	
	{		
		//clearAllMarkers();	
		refreshDefaultClusters();
	}	
	
	closeDialog("clusterdialog");	
}

function checkClustering()
{		
	if($("#cluster_on").attr("checked") == true) 	
	{		
		//clearAllMarkers();	
		refreshClusters();
	}	
	
	closeDialog("clusterdialog");

}