//***********************************************************************************
//Map Functions
//***********************************************************************************
var existingMarkers = [];   //already drawn marker/point 

//Load the xml to get channels
var doc = xmlLoad("/ota/xml/channels.xml");

function onMapLoad()
{
}

function onGDirectionsLoad(){}

function handleErrors()
{
	var str = "";
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.");
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.");
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given.");
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.");
	else alert("An unknown error occurred.");
}

function search(str, country, radius, licensed, digital, addMarker)
{
	document.getElementById("channels").innerHTML = '';
	existingMarkers = [];

	map.clearOverlays();

	var loc = str + ", " + country;

	geocoder.getLatLng(loc, function( point ) 
	{
		if( !point ) 
		{
			alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
		}
		else if(point != startPnt)
		{
			startPnt = point;
			if(startMarker != undefined) startMarker.hide();
			if(transmitterCircle != undefined) transmitterCircle.hide();
			
			var icon = new GIcon(G_DEFAULT_ICON, "images/dd-end.png");
			icon.clickable = true;
			if(addMarker) startMarker = createMarker(point, 'Latitude : ' + startPnt.lat().toFixed(4)+'&deg;, Longitude: '+startPnt.lng().toFixed(4) + '&deg;',true); //new GMarker(point, icon, false);

			map.addOverlay(startMarker);
			var rad = ((radius)*100000)/100000;

			// ==== It is necessary to make a setCenter call of some description before adding markers ====
			// ==== At this point we dont know the real values ====
			map.setCenter(startPnt);

			bounds = new GLatLngBounds(startPnt);
			transmitterCircle = drawCircle(point, rad, 360,"#6699cc",3,1,null,0);
			//transmitterCircle.hide();
		  
			updatePOI(radius,licensed,digital);

			// ===== determine the zoom level from the bounds =====
			map.setZoom(map.getBoundsZoomLevel(bounds));

			// ===== determine the centre from the bounds ======
			map.setCenter(bounds.getCenter());

			//updateMapZoom1(startPnt);
		}
	});
}

function updateMapZoom1(point){
    map_zoom1.setZoom(18);
	map_zoom1.panTo(point);
}
function updateMapZoom2(point){
    //map_zoom2.setZoom(16);
	//map_zoom2.panTo(point);
}

function drawCircle(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa)
{
	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

	var points = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step)
	{
		var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
		points.push(pint);
		bounds.extend(pint); //this is for fit function
	}
	fillColor = fillColor||liColor||"#0055ff";
	liWidth = liWidth||2;
	var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
	map.addOverlay(poly);
	return poly;
}

function createMarker(point,html,start) {
	var marker;
	if (start){
	var myIcon = new GIcon(G_DEFAULT_ICON); 
	myIcon.image = "/ota/images/iconb.png"; 
        marker = new GMarker(point,{icon:myIcon}); 
	} else{
        marker = new GMarker(point,{icon:myIcon}); 
	}
        GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html); drawGreatCirclePath(point); updateMapZoom2(point);});
        return marker;
      }

function markerExists(lat,lon){
	for (var i = 0; i < existingMarkers.length; i++){ 
      if(existingMarkers[i] == lat + '-' + lon){ 
         return true;
      } 
	} 
	return false;		
}

function drawGreatCirclePath(point){
			var lat1 = parseFloat(startPnt.lat().toString().parseDeg().toRad())*180/Math.PI;
		        var lon1 = parseFloat(startPnt.lng().toString().parseDeg().toRad())*180/Math.PI;
			var lat2 = parseFloat(point.lat().toString().parseDeg().toRad())*180/Math.PI;
			var lon2 = parseFloat(point.lng().toString().parseDeg().toRad())*180/Math.PI;
		

			var pt1 = new GLatLng(lat1, lon1);
			var pt2 = new GLatLng(lat2, lon2);

			var pts = [pt1];
	        	greatCirclePath(pts, pt2, 32);
			var Gline = new GPolyline(pts, '#ff0000', 4, 0.5);
			map.addOverlay(Gline);
}

function showChannels(lat,lon){
	var channels = doc.getElementsByTagName("Channel").length;
	var html = '';
	for(var i = 0; i < channels; i++ )
	{
		var curPOI = doc.getElementsByTagName("Channel")[i];
		var channelLat = Number(curPOI.attributes.getNamedItem("lat").value); 
		var channelLon = Number(curPOI.attributes.getNamedItem("lon").value); 
		if(channelLat==lat && channelLon==lon){
			html += curPOI.attributes.getNamedItem("channel").value + ' - ' + curPOI.attributes.getNamedItem("callsign").value + ' (' + curPOI.attributes.getNamedItem("city").value + ')<br/>';
			
			
		}
	}
	var c = document.getElementById("channels");
	c.innerHTML = html;
}


