//bind to keydown event , to clear gazetteer search results
function bindClearGazToKeyDown()
{
	$("#"+gazetteerid).bind("keydown", clearGazResults);	
}

//clears gazetteer search results
function clearGazResults()
{
	$("#gazResults").empty();
}

//bind to key down event, to clear species search results
function bindClearSpeciesToKeyDown()
{
	$("#"+speciessearchid).bind("keydown", clearSpeciesSearchResults);	
}

//clear species search results
function clearSpeciesSearchResults()
{
	$("#search-results").empty();
}

//bind to key up event, to search gazetteer (auto-search)
function bindAutoGazSearch()
{
	$("#"+gazetteerid).bind("keyup", autoSearchGazetter);  
}

//bind to focus event to clear gazetteer results
function clearGazExampleOnFocus()
{
	$("#"+gazetteerid).bind("focus", clearGazetteer);	
}

//bind to blur event, show gazetteer search example
function showGazExampleOnBlur()
{
	$("#"+gazetteerid).bind("blur", showGazExample);
}

//bind to focus event, to clear species search results
function clearSpeciesOnFocus()
{
	$("#"+searchspeciesid).bind("focus", clearSearchSpecies); 
}

//bind to blur event, show species search example
function showSpeciesExampleOnBlur()
{
	$("#"+searchspeciesid).bind("blur", showSearchSpeciesExample);  	
}

//show species search example
function showSearchSpeciesExample()
{
	$("#"+searchspeciesid).val("e.g. Robin");
}

//clear species search values
function clearSearchSpecies()
{
	$("#"+searchspeciesid).val("");
}

//show gazetteer search example
function showGazExample()
{
	$("#"+gazetteerid).val("e.g. Newcastle");
}
  
//clear gazetteer search example
function clearGazetteer()
{				
	$("#"+gazetteerid).val("");
}  

//redirect users to url
//params: 
//url - string
function redirect(url)
{
	window.location = url;
}

//close dialog box, with given id
//params:
//id - string
function closeDialog(id)
{
	if($("#"+id).dialog('isOpen')==true)
	{
		$("#"+id).dialog('close');	
	}
}

//open dialog box with given id, and populate with given html
//params:
//id - string
//html - string 
function openDialog(id, html)
{
	if($("#"+id).dialog('isOpen')==true)
	{
		closeDialog(id);	
	}	
	
	$("#"+id+" > p").html(html);
	
	$("#"+id).dialog('open');
}

//initialise next step dialog box
//params:
//width - int
//height - int
function initialiseNextStepDialog(width, height)
{
	initialiseDialog("next_step", "Proceed ...", height, width);
}

//initialise message dialog box
//params:
//width - int
//height - int
function initialiseMessageDialog(width, height)
{
	initialiseDialog("notification", "Message ...", height, width);
}

//initialise clustering dialog message box
//params:
//width - int
//height - int
function initialiseClusterDialog(width, height)
{
	initialiseDialog("clusterdialog", "Clustering ...", height, width);
}

//generic dialog initialisation function
//params:
//id - string
//title - string
//height - integer
//width - integer
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
//params:
//id_west - string			
//id_south - string
//id_east - string
//id_north - string
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 to search gazetteer after each keypress
//only performs search after keyup trigger
//params:
//event - event object, supplied from keyup trigger
function autoSearchGazetter(event)
{
	var id = event.target.id;
	var value = String($("#"+id).val());                
	if(value.length > 2)
	{
		searchPlaces(id);
	}                
}

//initialise gazetteer search
function initGaz()
{				
	//new WKT reader
	openlayers_wkt_reader = new OpenLayers.Format.WKT();

	//new Google Geocoder	
	geocoder = new GClientGeocoder();
		
	south_west = new GLatLng(54.4459927, -2.7011446);
	north_east = new GLatLng(55.8200714, -0.7469102);
	
	//calculate suitable centre point
	maxExtent = new GLatLngBounds(south_west, north_east);
	centrePoint = maxExtent.getCenter();
	
	limitGazToUK();
}

//limits Google Gazetteer to UK
function limitGazToUK()
{
	geocoder.setBaseCountryCode('uk');
	geocoder.setViewport(maxExtent);	
}

//executes search of Google Gazetteer
//params:
//gaz_id - string
function searchPlaces(gaz_id)
{
	//term typed in by user
	var searchterm = $("#"+gaz_id).val();

	//regular expression to match 6fig grid references
	var gridMatch = /^[A-Z]{2}\d{6}$/;

	var tosearchfor = "";
	limitGazToUK();
	
	//check if grid reference given
	if(gridMatch.test(searchterm))
	{		
		//execute search for 6fig grid reference
		tosearchfor = sixFigureGridRefToLatLng(searchterm, true);					
		geocoder.getLocations(tosearchfor, processGazResults)		
	}
	else
	{
		//execute search for other location types
		tosearchfor = searchterm;					
		geocoder.getLocations(tosearchfor, processGazResults);		
	}				
}

//function to process results from Google Gazetteer search
//params:
//results - XML/JSON/TEXT
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;
	
	//checking some results were returned
	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"))
				{	//abort previous request
					if (ajax != null)
					{					
						ajax.abort();
					}
					
					var point_ = results.Placemark[i].Point;
					//determine if the location is valid in terms of creating a new species sighting
					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)
									{	//determine apropriate zoom level based on address accuracy returned from Google
										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
							{
								//display no results message
								$("#gazResults").append(no_results_msg);
							}
					});
				}			
			}
		}
		else
		{
			//display no results message
			$("#gazResults").append(no_results_msg);	
		}
		
	}	
	else
	{		
		//display no results message
		$("#gazResults").append(no_results_msg);		
	}			
}

//function to add a new GLatLng marker to the map
//params:
//lng - double,float (longitude)
//lat - double,float (latitude)
function setMarker(lng, lat)
{
	newgmarker.setLatLng(new GLatLng(lat, lng));
}

//function zoom to point at given zoom level
//params:
//lng - double,float (longitude)
//lat - double,float (latitude)
//zoom - integer
function zoomTo(lng, lat, zoom)
{
	gmap.setCenter(new GLatLng(lat, lng), zoom);
}
			
//function define new location for record for gazetteer
//params:
//lng - double,float (longitude)
//lat - double,float (latitude)
function setLocation(lng, lat)
{
	var location = "POINT("+lng+" "+lat+")";    
	$("#id_1-location").val(location);
	
	var markerlocation = new GLatLng(lat, lng);
	
	newgmarker = initMarkerEvents(newgmarker);	
	
	newgmarker.setLatLng(markerlocation);

}

//function to initialise gazetteer search, 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 marker_options;
var single_marker_image;
var icon_single;

//function to initialise google marker and icon options
function initSingleMarker()
{

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 to set the initial extent values for north, south, east, west
function setInitialExtent()
{
	$("#north").val(north_east.lat());
	$("#south").val(south_west.lat());
	$("#east").val(north_east.lng());
	$("#west").val(south_west.lng());			
}

//function to clear map search, clear markers and add the extent
//params:
//id - string
function bindClearMapToSearch(id)
{
	$("#"+id).bind("keydown", function(){
		clearAllMarkers();
		addKMLExtent();
	});
	
	$("#jquery-live-search").empty();
	
}

//function to clear all markers from the map, and markerclusterer
function clearAllMarkers()
{	
	gmap.clearOverlays();	
	markerClusterer.clearMarkers();	
}

var static_marker_options;
var single_static_marker_image;
var icon_single_static;

//function to initialise a single marker, icon, and size
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 to fix zindex issue with jquery dialogs and google markers
 function setZIndexOrder(marker,b) {       
		return 10000000;
      }

//function to create a new static google maps marker
//params:
//lat - double/float (latitude)
//lng - double/float (longitude)
//species_id - string
//species_record_id - string
//index - integer
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 to reset map
function resetMap()
{
	gmap.setCenter(centrePoint, 8);	
}


//function used to create a static map on the summary page when uploading a sighting
//params:
//location - string (WKT formatted)
//page - string
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 to initialise marker events on supplied marker (click, dblclick, dragend, dragstart)
//params:
//newgmarker - Google Marker
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 to initiase a google map
//params:
//mapid - string (html-based id)
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 to add a cross to the centre of the map for orientation purposes
//mapid - string
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 to add the defined kml extents to which the eyeproject covers
function addKMLExtent()
{			
    geoXml = new GGeoXml("http://s.eyeproject.org.uk/kml/new_eyerecordingextents_kml.kml");    
	gmap.addOverlay(geoXml);
	geoXml.redraw(true);		
}

//function to validate the location of a marker once stopped dragging i.e. ensure it is within the bounds of the kml extent
//latlng - Google LatLng
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 to retrieve the centre of the map
//returns:
//GLatLng
function getMapCentre()
{
	return gmap.getCenter();			
}

//function to validate that the map centre is always within the bounds of the eye kml
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 to convert 6 figure grid reference to latitude / longitude
//params:
//gridref - string
//forgaz - boolean (determines if response is for the gazetteer)
//returns:
//GLatLng
//JS Object
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 to add column heading html
//params:
//id - string (html based id)
function addColumnHeadingRecordTable(id)
{
	$("#"+id).append("<tr><td><strong>Species:</strong></td><td><strong>Date sighted:</strong></td><td><strong>Options:</strong></td></tr>");	
}

//function to empty the record table
//params:
//id - string (html based id)
function resetRecordTable(rowcontainerid)
{	 
	$("#"+rowcontainerid).empty();
}

//function to add new rows to the record table
//params:
//rowcontainerid - string (html based id)
//html - string
function appendNewRowRecords(rowcontainerid, html)
{	
	$("#"+rowcontainerid).append(html);
}

//function
//params:
//odd_even - string (determine current row styling)
//species_id - string
//species_record_id - string
//species__common_name - string
//species_scientific_name - string
//location - string
//description - string
//datetime - string (sighted)
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 to convert date to pretty print ("xx/xx/xxxx")
//datetime - string
function processNonPrettyDateTime(datetime)
{
	var datetimesplit = datetime.split(" ");
	var date_ = datetimesplit[0];
	var date = String(date_).split("-");
	return date[2]+"/"+date[1]+"/"+date[0];
}

//function to show number of matched records returned
//count - integer
function showNumberOfMatches(count)
{
	$("#numberofmatchedrecords").html(count);
}

var clustermarkersdefault = new Array();
var clustermarkers = new Array();
var markerClusterer;
var maxZoomLevel = 12;
var gridSize = 200;
var styles = null;

//function to refresh default clusters
function refreshDefaultClusters()
{
	if (markerClusterer != null) 
	{
    	markerClusterer.clearMarkers();
    }			
	
	markerClusterer = new MarkerClusterer(gmap, clustermarkersdefault, {styles: styles, maxZoom: maxZoomLevel, gridSize: gridSize});
	
	resetMap();
	
}

//function to refresh visible clusters and create a new clusterer based on clustermarkers content.
function refreshClusters()
{
	if (markerClusterer != null) 
	{
    	markerClusterer.clearMarkers();
    }			

	markerClusterer = new MarkerClusterer(gmap, clustermarkers, {styles: styles, maxZoom: maxZoomLevel, gridSize: gridSize});
	
	clustermarkers.length = 0;
}

//function to add a new marker to the default clusterer
//marker - GMarker
function addMarkerToDefaultCluster(marker)
{
	clustermarkersdefault.push(marker);
}

//function to add a new marker to the clusterer
//marker - GMarker
function addMarkerToCluster(marker)
{
	clustermarkers.push(marker);
}

//function to check and refresh default clusters
function checkDefaultClustering()
{
	if($("#cluster_on").attr("checked") == true) 	
	{				
		refreshDefaultClusters();
	}	
	
	closeDialog("clusterdialog");	
}

//function to determine if clustering is enabled, and refreshes
function checkClustering()
{		
	if($("#cluster_on").attr("checked") == true) 	
	{				
		refreshClusters();
	}	
	
	closeDialog("clusterdialog");

}
