/*
 Position Report Details
*/

//globals
var prMap;
var greenIcon;  // map icon
var blueIcon;	// map icon

//create the google map object
function createMap() {
    prMap = new GMap2(document.getElementById("minimap"));

    prMap.addMapType(G_PHYSICAL_MAP); 
	prMap.addControl(new GSmallMapControl());
	prMap.addControl(new GMapTypeControl());
	prMap.setCenter(new GLatLng(40, -40), 2);
	prMap.enableDoubleClickZoom();
	prMap.enableScrollWheelZoom();

    //monitor the window resize event and let the map know when it occurs
    if (window.attachEvent) { 
		window.attachEvent("onresize", function() {prMap.checkResize()} );
    } else {
		window.addEventListener("resize", function() {prMap.checkResize()} , false);
    }
}

//create icons used on the map
function createIcons() {
    //create icons for the markers
    baseIcon = new GIcon();
    baseIcon.image = "images/markers/mm_20_green.png";
    baseIcon.shadow = "images/markers/mm_20_shadow.png";
    baseIcon.iconSize = new GSize(12, 20);
    baseIcon.shadowSize = new GSize(22, 20);
    baseIcon.iconAnchor = new GPoint(6, 20);
    baseIcon.infoWindowAnchor = new GPoint(5, 10);
    baseIcon.infoShadowAnchor = new GPoint(18, 20);        
    baseIcon.src = 'images/markers/mm_20_green.png';
    greenIcon = baseIcon;
	blueIcon = new GIcon(baseIcon);
	blueIcon.image = "images/markers/mm_20_blue.png";
    blueIcon.src = 'images/markers/mm_20_blue.png';
}

function createInfoHtml(site) {
	var Callsign = getElement(site.getElementsByTagName("Callsign")[0]);
	var Gridsquare = getElement(site.getElementsByTagName("Gridsquare")[0]);
	var Course = getElement(site.getElementsByTagName("Course")[0]);
	var Speed = getElement(site.getElementsByTagName("Speed")[0]);
	var Latitude = getElement(site.getElementsByTagName("Latitude")[0]);
	var Longitude = getElement(site.getElementsByTagName("Longitude")[0]);
	var Comment = getElement(site.getElementsByTagName("Comment")[0]);
	var ReportTime = getElement(site.getElementsByTagName("ReportTimeStr")[0]); 
	var html = 
	    '<div id="infowindow">' +
			'<table>' +
				'<tr><td colspan="2"><b>' + Callsign + '</b></td></tr>' +
				'<tr><td>Course</td><td>' + Course + '&nbsp;</td></tr>' +
				'<tr><td>Speed</td><td>' + Speed + '&nbsp;</td></tr>' +
				'<tr><td>Location</td><td>' + Latitude + " / " + Longitude + "  " + Gridsquare + '</td></tr>' +
				'<tr><td colspan="2">' + Comment + '&nbsp;</td></tr>' +
				'<tr><td>Report received</td><td>' + ReportTime + '</td></tr>' +
			'</table>' +
		'</div>';
	return html;
}

// Creates a marker whose tooltip displays the report time and info window displays station details
function createMarker(point, site, icon) {
	//show report time as hint
	var ReportTime = getElement(site.getElementsByTagName("ReportTimeStr")[0]); 
	var marker = new PdMarker(point, icon);
	marker.setTooltip(ReportTime);

	// Show this marker's details in the info window when it is clicked
	var html = createInfoHtml(site);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
		});
		
  return marker;
}

//resize the map when window is resized
function onResize() {
	prMap.onResize();
}

//use SOAP to make call to web service
function showStationReportsFor(StationCall) {
	showStatus('Loading. Please wait...');
	prMap.clearOverlays();
	
	//an empty GLatLngBounds object 
	var bounds = new GLatLngBounds();

	//
	var request = GXmlHttp.create();
	request.open("POST", "../ws/wsPositions.asmx", true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			var sites = xmlDoc.documentElement.getElementsByTagName("Positions");
			for (var i = 0; i < sites.length; i++) {
				var Callsign = getElement(sites[i].getElementsByTagName("Callsign")[0]); 
				Callsign = Callsign.toUpperCase();
				//skip smtp reports - not sure how to handle smtp reports !!!
				if (Callsign.indexOf("SMTP") == 0) continue;
				
				var lat = getElement(sites[i].getElementsByTagName("Lat")[0]); 
				var lon = getElement(sites[i].getElementsByTagName("Lon")[0]); 
				var point = new GPoint(parseFloat(lon), parseFloat(lat)); 
				var Gridsquare = getElement(sites[i].getElementsByTagName("Gridsquare")[0]);

				//create the marker
				if (i == 0) {
					var firstMarker = createMarker(point, sites[i], blueIcon);
					prMap.addOverlay(firstMarker);
				} else {
					var marker = createMarker(point, sites[i], greenIcon);
					prMap.addOverlay(marker);
				}
                //each time a marker is added, extend the bounds rect to include it
                latlng = new GLatLng(parseFloat(lat), parseFloat(lon));
                if (!bounds.contains(latlng)) {
					bounds.extend(latlng);
				}
			}

			//determine the zoom level and center from the bounds rect 
			if (!bounds.isEmpty() && !bounds.isFullLng()) {
				var zoomLevel = prMap.getBoundsZoomLevel(bounds);
				if (zoomLevel > 10) zoomLevel = 10;

				//determine the center from the bounds
				var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
				var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
				
				//adjust the map
				prMap.setCenter(new GLatLng(clat, clng), zoomLevel);
			}
			showStatus('');
		}
	}
	request.setRequestHeader("Content-Type", "text/xml; charset=utf-8")
	request.setRequestHeader("SOAPAction", "http://www.winlink.org/GetPositionReportsForStation")
	request.send(
		'<?xml version="1.0" encoding="utf-8"?>' +
		'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
		'	<soap:Body>' +
		'	<GetPositionReportsForStation xmlns="http://www.winlink.org/">' +
        '           <strSecurityCode>14435FE8-C24A-4EAD-9A52-82AC644B0D43</strSecurityCode>' +
		'			<strStationCall>' + StationCall + '</strStationCall>' + 
		'	</GetPositionReportsForStation>' +
		'	</soap:Body>' +
		'</soap:Envelope>'
	);
}

function initPage() {
	var args = getQueryString();
	var Callsign = args['callsign'];
	document.title = 'Position Reports for ' + Callsign;
	if (GBrowserIsCompatible()) { 
		createMap();
		createIcons();
		showStationReportsFor(Callsign)
	} else {
		document.write("This web page is not compatible with your browser.");
	}
}

