#!/usr/bin/perl

use CGI qw(param);
use DBI;
use Encode;

# print "Content-type: text/html\n\n";

$user = param("user");
$track = param("track");
$year = param("year");
$radius = 100;	# za izbor slik

# print "$noflights,$clat,$clong\n";
@kmllink=();
@igcfile=();
@type=();
@dist=();
@aspeed=();
@extensions=('trk','fre','tri','fai','crt');
@kmltype=('Track','Free flight','Triangle','FAI Triangle','Competition route');
$files = 'http://www.photoglide.info/files';
$homedir="/var/www/www.photoglide.info";
$resfile = $homedir.'/files/'.$user.'/flights'.$year.'/'.$track.'.igc.res';
$barofile = '/files/'.$user.'/flights'.$year.'/'.$track.'.gif';
$timezone = ''; $flstart = ''; $flend = '';
$maxlift = ''; $maxsink = ''; $maxsl = ''; $maxspeed = '';
$tsr = ''; $tsravg = '';

open (results,$resfile);
while (<results>) {
	$rec=$_;
	($type,$r1,$r2,$r3,$r4,$r5,$r6,$r7,$r8,$r9,$r10,$r11,$r12,$r13)=split(/,/,$rec);
	$r13=~s/\n//; $r13=~s/\r//; $r13=~s/ //;
	if ($type eq 'FRE') {
		$dmaxFree=sprintf("%.2f",$r1/1000); $avgsFree=$r2;
		$ofree[1]=$r3; $ofree[2]=$r4; $ofree[3]=$r5; $ofree[4]=$r6; $ofree[5]=$r7; 
		$L[1]=$r8; $L[2]=$r9; $L[3]=$r10; $L[4]=$r11;
	}
	if ($type eq 'TRI') {
		$dmaxTriN=sprintf("%.2f",$r1/1000); $avgsTriN=$r2;
		$d1[0]=$r3; $d2[0]=$r4; $d3[0]=$r5; $gapTri[0]=$r6;
		$otriN[1]=$r7; $otriN[2]=$r8; $otriN[3]=$r9;
		$trisxN=$r10; $trisyN=$r11; $triexN=$r12; $trieyN=$r13;
	}
	if ($type eq 'FAI') {
		$dmaxTriF=sprintf("%.2f",$r1/1000); $avgsTriF=$r2;
		$d1[1]=$r3; $d2[1]=$r4; $d3[1]=$r5; $gapTri[1]=$r6;
		$otriF[1]=$r7; $otriF[2]=$r8; $otriF[3]=$r9;
		$trisxF=$r10; $trisyF=$r11; $triexF=$r12; $trieyF=$r13;
	}
	if ($type eq 'DAT') {
		$maxlat=$r1;$minlat=$r2;$maxlong=$r3;$minlong=$r4;
		$maxaltb=$r5; $maxaltg=$r6; $pilot=$r7; $date=$r8; $glider=$r9; $th=$r10; $tm=$r11; $ts=0;
	}
	if ($type eq 'MSC') {
		$maxlift=$r1;$maxsink=$r2;$lsint=$r3;
		$tsravg=$r4;$tsrmin=$r5;$tsrmax=$r6;
		$thermals=$r7; # if ($thermals eq '') { $thermals = '' };
		$thermals =~ s/\n//;
		if ($tsravg == 1000) {
			$thermalradius = "cannot determine or > 100m";
			$tsravg = ''; $tsrmin = ''; $tsrmax = '';
		}
		else {
			$thermalradius = sprintf("%d/%d/%d m",$tsravg,$tsrmin,$tsrmax);
		}
		$maxspeed=$r8;
		$maxspeed =~ s/\n//;
	}
	if ($type eq 'TIM') {
		$timezone=$r1;$bth=$r2;$btm=$r3;$bts=$r4;$eth=$r5;$etm=$r6;$ets=$r7;$th=$r8;$tm=$r9;$ts=$r10;
	}
}
close (results);

$kml=0;
foreach $ext (@extensions) {
	$kmlfile = $homedir.'/files/'.$user.'/flights'.$year.'/'.$track.'-'.$ext.'.kml';
#	print $kmlfile;
	if (-e $kmlfile) {
		push (@kmllink,$files.'/'.$user.'/flights'.$year.'/'.$track.'-'.$ext.'.kml');
		if ($ext eq 'trk') { push (@dist,''); push (@type,$kmltype[0]); push(@aspeed,0); }
		if ($ext eq 'fre') { push (@dist,$dmaxFree); push (@type,$kmltype[1]); push(@aspeed,$avgsFree); }
		if ($ext eq 'tri') { push (@dist,$dmaxTriN); push (@type,$kmltype[2]); push(@aspeed,$avgsTriN); }
		if ($ext eq 'fai') { push (@dist,$dmaxTriF); push (@type,$kmltype[3]); push(@aspeed,$avgsTriF); }
		if ($ext eq 'crt') { push (@type,$kmltype[4]); }
		$kml++;
	}
}
#print $kml;
$clatd=($maxlat+$minlat)/2; $clongd=($maxlong+$minlong)/2;

# we have all the data to generate html file

#ABQIAAAAnJSLtH7vKWQ8Utb3xIpQJxQD3AWjVZLashdMcvCZiRv8xVcpTBSddcj9HmW9cgAN0-wHwxMHj1bT8w
printf "
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">

<title>Photoglide Track</title>
<script src=\"http://maps.google.com/maps?file=api&amp;hl=en&amp;v=2&amp;key=ABQIAAAAnJSLtH7vKWQ8Utb3xIpQJxR3eItLRX1hL7y2JaRklTV3FFAPyxTBdnlTbYBh68_6jTsL49q79FEiKw\" type=\"text/javascript\">

</script>
<script src=\"/files/js/labeledmarker.js\"></script>
<script language=\"JavaScript\" src=\"/overlib/Mini/overlib_mini.js\"></script>
<script src=\"/files/js/dragzoom.js\" type=\"text/javascript\"></script>
<script src=\"/files/js/elabel.js\" type=\"text/javascript\"></script>
<script src=\"/files/js/ctrs.js\" type=\"text/javascript\"></script>

<style>
	HTML {
	     overflow: scroll;
 		 height: 100%;
	}
	BODY, TD, IFRAME, INPUT, TEXTAREA {
		font-family: Verdana, Arial;
		font-size: 11px;
		color : black;
		text-decoration : none;
		padding: 0px;
		height: 100%;
	}
	table.framed {
		padding: 0px;
	}
	table.framed td {
		border-width: 1px 1px 1px 1px;
		border-style: solid solid solid solid;
		border-color: #e1e1e1;
		padding: 5px;
	}

	.tooltip {
		background-color:#ffffff;
		border:2px #006699 solid;
	}

	.labelstyle {background-color:#ffffff;font-weight:bold;}

	a.link:link { text-decoration: none; color: rgb(0,0,102); }
	a.link:visited { text-decoration: none; color: rgb(0,0,102); }
	a.link:hover { text-decoration: underline; color:black; background-color: rgb(204,255,152);}

</style>

</head>
<body onunload=\"GUnload()\" bgcolor=\"\#ffffff\">


<!-- you can use tables or divs for the overall layout -->

<table border=0 width=100%% height=75%%>

	<tr>
	<td valign=\"top\" align='left' width=80%% bgcolor=\"#ffffff\">
		&nbsp;$pilot / $glider<br>
		<div id=\"map\" style=\"width: 100%%; height: 100%%\"></div><br>
		<!-- img src=\"$barofile\" id=\"baro\" onClick=\"javascript:changeBaroSize();\" style=\"width:600px\" onmouseover=\"return overlib('Click for normal or zoomed size');\" onmouseout=\"return nd();\" -->
	</td>
	<td valign=\"top\" width=20%%>
		<div id=\"side_bar\"></div><br>
		<!-- input type=\"checkbox\" id=\"barosize\" onClick=\"javascript:changeBaroSize();\" -->
	</td>
	</tr>
</table>
<br>
<img id=\"ruller\" onclick=\"point_it(event,2);\" style=\"left: 4px; position: relative; top: -20px\" height=120 width=1 align=baseline border=0 hspace=0 src=\"/pics/assets/ruller3.gif\">
<img src=\"$barofile\" id=\"baro\" onclick=\"point_it(event,2);\" onmousemove=\"point_it(event,1);\" onmouseout=\"return nd();\" style=\"width:600px\">
<div id=\"posdata\" style=\"left: 610px; position: relative; top: -140px\"></div>
<div id=\"datastore\" style=\"visibility:show; left: 610px; position: relative; top: -140px\"></div>

<script type=\"text/javascript\">
//<![CDATA[

if (GBrowserIsCompatible()) {

	// icons
	var baseIcon = new GIcon();
	baseIcon.iconSize=new GSize(24,24);
//	baseIcon.shadowSize=new GSize(48,24);
	baseIcon.iconAnchor=new GPoint(12,24); 
	baseIcon.infoWindowAnchor=new GPoint(12,12);
	var planeicon = new GIcon(baseIcon, \"http://maps.google.com/mapfiles/kml/pal2/icon56.png\", null, \"http://maps.google.com/mapfiles/kml/pal2/icon56s.png\");
//	var planeicon = new GIcon(baseIcon, \"http://www.photoglide.info/pics/assets/aircraft-small2.png\", null);
	var planeicon = new GIcon(baseIcon, \"http://www.photoglide.info/pics/assets/paraglider5.gif\", null);
//	var crossicon = new GIcon(baseIcon, \"http://maps.google.com/mapfiles/kml/pal3/icon52.png\", null, \"http://maps.google.com/mapfiles/kml/pal3/icon52s.png\");
//	var cameraicon = new GIcon(baseIcon, \"http://maps.google.com/mapfiles/kml/pal4/icon46.png\", null, \"http://maps.google.com/mapfiles/kml/pal4/icon46s.png\");

	// this variable will collect the html which will eventually be placed in the side_bar
	var side_bar_html = \"<table border=0 width=220>\";
//	side_bar_html += '<tr><td bgcolor=\"#cccccc\"></td><td bgcolor=\"#cccccc\" align=\"right\">&nbsp;</td></tr>';
    
	// arrays to hold copies of the markers and html used by the side_bar
	// because the function closure trick doesnt work there
	var gmarkers = [];
	var infowins = [];
	var flightbox = [];
	var i = 0;
	var f = 0;
	var fNo = [];
	var latc = [];
	var longc = [];
	var markersts = 1;
	var showPanoramio = 0; showWebCams = 0; showCTR = 0;
	var line;
	var showMypics = 0;
	var mypics = [];
	var coordmarker = '';
	var rfai = 6378137;
	var loop = '';
	var looppt = 0;
";
#	koordinate 
	$trkfile = $homedir.'/files/'.$user.'/flights'.$year.'/'.$track.'-trk.kml';
	printf "// $trkfile \n";
	$doit = 0; @coordes = ();
	open (TRK,$trkfile);
	while (<TRK>) {
		$rec = $_;
		if (index($rec,'</coordinates>') != -1) { $doit = 0; }
		if ($doit == 1) {
			@coords = split(/ /,$rec)
		}
		if (index($rec,'<coordinates>') != -1) { $doit = 1; }
	}
	close (TRK);
	$n = $#coords; $s = $n/600;
	printf "var coords = [";
	for ($i=0; $i<$n; $i=$i+$s) {
		printf "'".$coords[int($i)]."',";
	}
	printf $coords[$n]."]\;";
#

printf "
	var help = 'help';
	var tip1 = 'UTC time,<br>in brackets is timezone for this geo. location';
	var tip2 = 'Number of circles for which thermal radiuses were computed';
	var tip3 = 'Circle radius in thermals';

	var tip4 = 'Show Panoramio photos';
	var tip5 = 'Show Webcams';
	var tip6 = 'Show Photoglide photos in radius of $radius km';
	var tip7 = 'Double click marker to delete ruller';
	var tip8 = 'Show CTRs';
	var barow;

	var mypicsicon = new GIcon();
	mypicsicon.image = \'/assets/square-greenonblack.gif\';
	mypicsicon.iconSize = new GSize(8, 8);
	mypicsicon.iconAnchor = new GPoint(4, 4);
	mypicsicon.infoWindowAnchor = new GPoint(12, 0);

	// A function to create the marker and set up the event window
	function createMarker(link,kmltype) {
		var marker = new GGeoXml(link);
		fNo[f] = 1;
		map.addOverlay(marker); 
		GEvent.addListener(marker, \"click\", function() {
		if (fNo[f] == 0) {
			map.addOverlay(marker); 
			fNo[f] = 1; }
		else {
			map.removeOverlay(marker);
			fNo[f] = 0; }
		});
		// save the info we need to use later for the side_bar
		gmarkers[i] = marker;

		// add a line to the side_bar html
		var boxchecked = 'checked';
		if (kmltype == 'Competition route') {
			boxchecked = '';
		}
		side_bar_html += '<tr><td colspan=2 bgcolor=\"#cccccc\"><input type=\"checkbox\" '+boxchecked+' name=\"flightbox[' + i + ']\" onclick=\"javascript:myclick(' + i + ')\">' + kmltype + '</td></tr>';	
		i++; f++;
		return marker;
	}

	// This function picks up the click and opens the corresponding info window
	function myclick(i) {
		f=i;
		GEvent.trigger(gmarkers[i], \"click\");
	}

	function panoramioOnOff() {
		showPanoramio = 1-showPanoramio;
		if (showPanoramio == 1) {
			map.addOverlay(panoramio);
		}
		else {
			map.removeOverlay(panoramio);
		}
	}

	// WebCams
	function webcamsOnOff() {
		showWebCams = 1-showWebCams;
		if (showWebCams == 1) {
			map.addOverlay(webcams);
		}
		else {
			map.removeOverlay(webcams);
		}
	}

//	knjiznica /files/js/ctrs.js
	function ctrOnOff() {
		var fill = 0;
		if (document.getElementById('ctrfill').checked == true) { fill = 1;}
		showCTR = 1-showCTR;
		if (showCTR == 1) {
			addCTRs(fill);
		}
		else {
			removeCTRs();
		}
	}

	function ctrFillOnOff() {
		var fill = 0;
		if (document.getElementById('ctrfill').checked == true) { fill = 1;}
		if (showCTR == 1) { 
			addCTRs(fill); 
		}
	}

	function showinfo(i) {
		f=i;
		GEvent.trigger(infowins[i], \"click\");
	}

	function showTooltip(infowin) {
		tooltip.innerHTML = infowin.tooltip;
		var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
		var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(infowin.getPoint(),map.getZoom());
		var anchor=infowin.getIcon().iconAnchor;
		var width=infowin.getIcon().iconSize.width;
		var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y)); 
		pos.apply(tooltip);
		tooltip.style.visibility=\"visible\";
	}

	function mymouseover(i) {
		showTooltip(infowins[i])
	}

	function mymouseout() {
		tooltip.style.visibility=\"hidden\";
	}

	function ShowHideMarkers() {
		for (var i=0; i<infowins.length; i++) {
			if (markersts == 1) {
				infowins[i].hide();
			}
			else {
				infowins[i].show();
			}
		}
		markersts = 1-markersts;
	}

	// Circle
	function drawCircle(map, center, radius, numPoints) {
		poly = [] ; 
		var lat = center.lat() ;
		var lng = center.lng() ;
		var d2r = Math.PI/180 ;                // degrees to radians
		var r2d = 180/Math.PI ;                // radians to degrees
		var Clat = (radius/6378) * r2d ;      //  using 3963 (miles) as earth radius = 6378 km
		var Clng = Clat/Math.cos(lat*d2r);
				
		//Add each point in the circle
		for (var i = 0 ; i < numPoints ; i++)
		{
			var theta = Math.PI * (i / (numPoints / 2)) ;
			Cx = lng + (Clng * Math.cos(theta)) ;
			Cy = lat + (Clat * Math.sin(theta)) ;
			poly.push(new GLatLng(Cy,Cx)) ;
		}

		//Remove the old line if it exists
		if(line)
		{
			map.removeOverlay(line) ;
		}
				
		//Add the first point to complete the circle
		poly.push(poly[0]) ;

		//Create a line with teh points from poly, red, 3 pixels wide, 80prc opaque
		line = new GPolyline(poly,'#0000ff', 1, 0.8) ;
				
//		map.addOverlay(line) ;
	}

	// Mypics
	function mypicsOnOff() {
		if (showMypics == 1) {
			for (var i=0; i<mypics.length; i++) {
				mypics[i].hide();
			}
			map.removeOverlay(line);
		}
		else {
			for (var i=0; i<mypics.length; i++) {
				mypics[i].show();
			}
			map.addOverlay(line);
		}
		showMypics = 1-showMypics;
	}

	function changeBaroSize() {
		if (document.getElementById(\"baro\").style.width == \"600px\") {
			document.getElementById(\"baro\").style.width=\"100%\";
		}
		else {
			document.getElementById(\"baro\").style.width=\"600px\";
		}
	}

	function findAlt (lat,long,e) {
		var photoURL = 'http://www.photoglide.info/cgi-bin/getelev.pl?'+lat+','+long;
		xmlHttp = new XMLHttpRequest();
		xmlHttp.onreadystatechange = function(){
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status != 200) {
//					alert ('error ne 200'+xmlHttp.responseText);
					xmlHttp = null;
					return;
				}
				var s = xmlHttp.responseText;
				if (s == null || s == '') {
					return;
				} else {
					if (e == 0) { document.getElementById(\"altbox\").innerHTML='Alt: '+s; }
					if (e == 1) { document.getElementById(\"datastore\").innerHTML='Gnd.elev: <b>'+s+'</b>'; }
				}
			}
		}
		
		xmlHttp.open(\"GET\", photoURL, true);
		xmlHttp.send(null);
	}
	
	function D2R(x) {
		var xr = Math.PI*x/180;
		return xr;
	}

	function calcDist(x0,y0,x1,y1) {
		x0 = D2R(x0);
		y0 = D2R(y0);
		x1 = D2R(x1);
		y1 = D2R(y1);
		var d = rfai*Math.acos(Math.sin(x1)*Math.sin(x0)+Math.cos(x1)*Math.cos(x0)*Math.cos(y1-y0));
		d = d/1000;
		d = Math.round(d*1000)/1000;
		return d;
	}

	function coordMarker(coord,html,lat,long) {
		var coordmarker = new GMarker(coord,planeicon);
		GEvent.addListener(coordmarker, \"click\", function() {
			coordmarker.openInfoWindowHtml(html);
			findAlt(lat,long,1)
		});
		return coordmarker;
	}

	function point_it(event,opt){
		var pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById(\"baro\").offsetLeft;
		var pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById(\"baro\").offsetTop;
		if (!pos_x) { pos_x = 0; }
		var el = coords[pos_x].split(',');
//		alert(el[1]+','+el[0]);
		var cs = coords[0].split(',');
		var d = calcDist(cs[1],cs[0],el[1],el[0]);
		var posinfo = 'lat: <b>'+el[1]+'°</b><br>long: <b>'+el[0]+'°</b><br>alt: <b>'+el[2]+' m</b><br>d-toff: <b>'+d+' km</b>';
		if (opt == 1) {
			if (coordmarker) { map.removeOverlay(coordmarker); }
			coord = new GLatLng(el[1],el[0]);
			coordmarker = coordMarker(coord,posinfo,el[1],el[0]);
			map.addOverlay(coordmarker);
		}

		document.getElementById(\"ruller\").style.left = pos_x+4+'px';
		document.getElementById(\"posdata\").innerHTML = posinfo; 
		document.getElementById(\"datastore\").innerHTML = '';
		if (opt == 2) {
			findAlt(el[1],el[0],1);
			looppt = pos_x;
		}
	}	

	function moveGlider() {
//		alert(looppt+'');
		var el = coords[looppt].split(',');
		var cs = coords[0].split(',');
		var d = calcDist(cs[1],cs[0],el[1],el[0]);
		var posinfo = 'lat: <b>'+el[1]+'°</b><br>long: <b>'+el[0]+'°</b><br>alt: <b>'+el[2]+' m</b><br>d-toff: <b>'+d+' km</b>';

		if (coordmarker) { map.removeOverlay(coordmarker); }
		coord = new GLatLng(el[1],el[0]);
		coordmarker = coordMarker(coord,posinfo);
		map.addOverlay(coordmarker);

		document.getElementById(\"ruller\").style.left = looppt+4+'px';
		document.getElementById(\"posdata\").innerHTML = posinfo; 
		document.getElementById(\"datastore\").innerHTML = '';

		looppt++;
		if (looppt == coords.length) { looppt = 0; }
	}

	function animateFlight() {
//		alert(loop);
		if (!loop) { loop = setInterval('moveGlider()',100); document.getElementById(\"animation\").value = 'Animation stop'; }
		else { clearTimeout(loop); loop = ''; document.getElementById(\"animation\").value = 'Animation start'; }
	}

	// create the map
	var map = new GMap2(document.getElementById(\"map\"),{draggableCursor: 'pointer', draggingCursor: 'move'});
	map.addMapType(G_PHYSICAL_MAP);
	map.addMapType(G_SATELLITE_3D_MAP);
	
	map.addControl(new GLargeMapControl());
	map.addControl(new GMenuMapTypeControl());
//	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
//	map.addControl(new MoreControl());
	map.addControl(new DragZoomControl({}, {backButtonEnabled: true}, {}), new GControlPosition(G_ANCHOR_BOTTOM_LEFT,new GSize(10,10)));

	map.setCenter(new GLatLng(%s,%s), 10, G_PHYSICAL_MAP);
	var panoramio = new GLayer(\"com.panoramio.all\");
	var webcams = new GLayer(\"com.google.webcams\");
//	map.addOverlay(panoramio);

//// custom map ////
	var myCopyright = new GCopyrightCollection('');
	myCopyright.addCopyright(new GCopyright('Blank',new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)),0,''));

	var myLayer = new GTileLayer(myCopyright);
	myLayer.getTileUrl =  function(tile, zoom) {
		return 'http://www.photoglide.info/assets/blank_map2.png';
	}
	var myLayer2 = new GTileLayer(myCopyright);
	myLayer2.getTileUrl =  function(tile, zoom) {
		return 'http://www.photoglide.info/assets/blank_map3.png';
	}
	myLayer.isPng = function() {return true;}
	var layerTransp = [ G_PHYSICAL_MAP.getTileLayers()[0], myLayer ];
	var myMap = new GMapType(layerTransp,G_PHYSICAL_MAP.getProjection(),'Ter.Transp');
	map.addMapType(myMap);
	var mapControl = new GHierarchicalMapTypeControl();
	mapControl.clearRelationships();
	mapControl.addRelationship(G_PHYSICAL_MAP, myMap, 'Ter.Transp');
//	map.addControl(mapControl);

	var layerTransp2 = [ G_SATELLITE_MAP.getTileLayers()[0], myLayer ];
	var myMap2 = new GMapType(layerTransp2,G_SATELLITE_MAP.getProjection(),'Sat.Transp');
	map.addMapType(myMap2);
	var mapControl2 = new GHierarchicalMapTypeControl();
	mapControl2.clearRelationships();
	mapControl2.addRelationship(G_SATELLITE_MAP, myMap2, 'Sat.Transp');
//	map.addControl(mapControl2);

	var layerTransp3 = [ G_NORMAL_MAP.getTileLayers()[0], myLayer2 ];
	var myMap3 = new GMapType(layerTransp3,G_NORMAL_MAP.getProjection(),'Blank');
	map.addMapType(myMap3);
	var mapControl3 = new GHierarchicalMapTypeControl();
	mapControl3.clearRelationships();
	mapControl3.addRelationship(G_NORMAL_MAP, myMap3, 'Blank');

////	end custom map ////

	// zoom	to area
	var bounds = new GLatLngBounds();
	bounds.extend(new GLatLng($maxlat,$minlong));
	bounds.extend(new GLatLng($minlat,$maxlong));
	var z=map.getBoundsZoomLevel(bounds);
	map.setZoom(z);

	GEvent.addListener(map, 'click', function(overlay, point) {
	if (point) {
		if (showCTR == 1) {
			for (var i=0; i<ctrpoly.length; i++) {
				if (ctrpoly[i].Contains(point)) {
					map.openInfoWindowHtml(point,'CTR '+ctrname[i]);
				}
			}
		}
//		document.getElementById(\"latbox\").innerHTML='Lat: '+point.y.toFixed(4);
//		document.getElementById(\"lonbox\").innerHTML='Long: '+point.x.toFixed(4);
		var posinfo = 'lat: <b>'+point.y.toFixed(4)+'°</b><br>long: <b>'+point.x.toFixed(4)+'°</b><br>';
		document.getElementById(\"posdata\").innerHTML = posinfo; 
		findAlt(point.y,point.x,1);
	}

 });

",$clatd,$clongd;

&myPics;

if ($timezone ne '') {
	$flstart = sprintf("%d:%02d:%02d (%s)",$bth,$btm,$bts,$timezone);
	$flend = sprintf("%d:%02d:%02d (%s)",$eth,$etm,$ets,$timezone);
}
if ($maxlift ne '') {
	$maxsl = sprintf("%.1f/%.1f",$maxlift,$maxsink);
}
if ($tsravg ne '') {
	$tsr = sprintf("%d/%d/%d",$tsravg,$tsrmin,$tsrmax);
}
if ( $maxspeed > 0) { $maxspeed = sprintf("%.1f km/h",$maxspeed*3.6) } else { $maxspeed = '' }
$fltime = sprintf("%d:%02d:%02d",$th,$tm,$ts);
$maxaltb = int($maxaltb);
$maxaltg = int($maxaltg);

for ($k=0; $k<$kml; $k++) {
	printf "	var marker = createMarker(\"%s\",\"%s\",\"%s %s\")\;\n",$kmllink[$k],$type[$k];

	if ($type[$k] eq 'Track') {
		printf "
		side_bar_html += '<tr><td align=\"right\" width=40%>Date:&nbsp;&nbsp;</td><td width=60%>$date</td></tr>';
		side_bar_html += '<tr><td align=\"right\" onmouseover=\"this.style.cursor=help; return overlib(tip1);\" onmouseout=\"return nd();\">Fl.start:&nbsp;&nbsp;</td><td>$flstart</td></tr>';
		side_bar_html += '<tr><td align=\"right\" onmouseover=\"this.style.cursor=help; return overlib(tip1)\" onmouseout=\"return nd();\">Fl.end:&nbsp;&nbsp;</td><td>$flend</td></tr>';
		side_bar_html += '<tr><td align=\"right\">Fl.time:&nbsp;&nbsp;</td><td>$fltime</td></tr>';
		side_bar_html += '<tr><td align=\"right\">Max.alt (b/g):&nbsp;&nbsp;</td><td>$maxaltb/$maxaltg m</td></tr>';
		side_bar_html += '<tr><td align=\"right\">Max.lift/sink:&nbsp;&nbsp;</td><td>$maxsl m/s</td></tr>';
		side_bar_html += '<tr><td align=\"right\">Max.speed:&nbsp;&nbsp;</td><td>$maxspeed</td></tr>';
		side_bar_html += '<tr><td align=\"right\" onmouseover=\"this.style.cursor=help; return overlib(tip2)\" onmouseout=\"return nd();\">No. of thermals:&nbsp;&nbsp;</td><td>$thermals</td></tr>';
		side_bar_html += '<tr><td align=\"right\" onmouseover=\"this.style.cursor=help; return overlib(tip3)\" onmouseout=\"return nd();\">R.avg/min/max:&nbsp;&nbsp;</td><td>$tsr m</td></tr>';
	";
	} 

	else {
		if ($type[$k] eq 'Competition route') {
			printf "
			map.removeOverlay(gmarkers[$k]);
			fNo[$k] = 0;
			";
		}
		else {
			$avspeed = sprintf("%.1f",$aspeed[$k]);
			printf "
			side_bar_html += '<tr><td align=\"right\">Distance:&nbsp;&nbsp;</td><td>$dist[$k] km</td></tr>';
			side_bar_html += '<tr><td align=\"right\">Av.Speed:&nbsp;&nbsp;</td><td>$avspeed km/h</td></tr>';
			";
		}
	}
}

printf "
	side_bar_html += '<tr><td colspan=2 bgcolor=\"#cccccc\" onmouseover=\"this.style.cursor=help; return overlib(tip4)\" onmouseout=\"return nd();\"><input type=\"checkbox\" name=\"panoramiobox\" onclick=\"javascript:panoramioOnOff()\">Panoramio photos</td></tr>';
	side_bar_html += '<tr><td colspan=2 bgcolor=\"#cccccc\" onmouseover=\"this.style.cursor=help; return overlib(tip5)\" onmouseout=\"return nd();\"><input type=\"checkbox\" name=\"webcamsbox\" onclick=\"javascript:webcamsOnOff()\">Webcams</td></tr>';
	side_bar_html += '<tr><td colspan=2 bgcolor=\"#cccccc\" onmouseover=\"this.style.cursor=help; return overlib(tip6)\" onmouseout=\"return nd();\"><input type=\"checkbox\" name=\"mypicsbox\" onclick=\"javascript:mypicsOnOff()\">Photoglide photos (r=$radius km)</td></tr>';
	side_bar_html += '<tr><td colspan=2 bgcolor=\"#cccccc\" onmouseover=\"this.style.cursor=help; return overlib(tip8)\" onmouseout=\"return nd();\"><input type=\"checkbox\" name=\"ctr\" onclick=\"javascript:ctrOnOff()\">CTR (<input type=\"checkbox\" id=\"ctrfill\" onclick=\"javascript:ctrFillOnOff()\" checked> fill)</td></tr>';

	side_bar_html += '<tr><td colspan=1 bgcolor=\"#cccccc\" onmouseover=\"this.style.cursor=help; return overlib(tip7)\" onmouseout=\"return nd();\"><input type=\"button\" id=\"distance\" onclick=\"javascript:measureDistance()\" value=\"Distance\"></td>';
	side_bar_html += '<td colspan=1 bgcolor=\"#cccccc\"><input type=\"button\" id=\"animation\" onclick=\"javascript:animateFlight()\" value=\"Animation start\"></td></tr>';

	side_bar_html += '<br><br><tr><td colspan=2 id=\"latbox\"></td></tr><tr><td colspan=2 id=\"lonbox\"></td></tr><tr><td colspan=2 id=\"altbox\"></td></tr><tr><td colspan=2 id=\"distbox\"></td></tr>';

	side_bar_html += '</table>';
	document.getElementById(\"side_bar\").innerHTML = side_bar_html;   

	// Measure distance
	function measureDistance()
	{
	  var marker1;
	  var marker2;
	  var label1;
	  var label2;
	  var button=0;
	  var dist=0;
	  var line;
	  var poly;

	  function measure(){
		if(marker1&&marker2)
		line = [marker1.getPoint(),marker2.getPoint()];
		dist=marker1.getPoint().distanceFrom(marker2.getPoint());
		dist=dist.toFixed(0)+\"m\";
		if(parseInt(dist)>10000){dist=(parseInt(dist)/1000).toFixed(1)+\"km\";}
		label1.setContents(dist);label2.setContents(dist);
		label1.setPoint(marker1.getPoint());
		label1.setContents(dist);
		label2.setPoint(marker2.getPoint());
		if(poly)map.removeOverlay(poly);
		poly = new GPolyline(line,'#FFFF00', 3, 1)
		map.addOverlay(poly);
//		document.getElementById(\"distbox\").innerHTML=dist;
		document.getElementById(\"posdata\").innerHTML='distance: <b>'+dist+'</b>';
	  }

	  document.getElementById(\"distance\").value=\"click on map\";

	  GEvent.addListener(map, 'click', function(overlay,pnt) 
	  {
	  if(pnt&&button==0)
	  {
		marker1 = new GMarker(pnt,{draggable: true});
		map.addOverlay(marker1);
		marker1.enableDragging();
		label1=new ELabel(pnt, dist,\"labelstyle\",new GSize(2,20),60);
		map.addOverlay(label1);
		marker2 = new GMarker(pnt,{draggable: true});
		map.addOverlay(marker2);
		marker2.enableDragging();
		label2=new ELabel(pnt, dist,\"labelstyle\",new GSize(2,20),60);
		map.addOverlay(label2);
	  }
	  GEvent.addListener(marker1,\"drag\",function(){measure();});
	  GEvent.addListener(marker1,\"dblclick\",function(){clr();});
	  GEvent.addListener(marker2,\"drag\",function(){measure();});
	  GEvent.addListener(marker2,\"dblclick\",function(){clr();});
	  document.getElementById(\"distance\").value=\"You Have a Ruler\";
	  button++;
	  });


	  function clr(){
		map.removeOverlay(poly);
		map.removeOverlay(marker1);
		map.removeOverlay(marker2);
		map.removeOverlay(label1);
		map.removeOverlay(label2);
		button=0;
		document.getElementById(\"distance\").value=\"New Ruler\";
//		document.getElementById(\"distbox\").innerHTML='';
		document.getElementById(\"posdata\").innerHTML='';
		dist=0;
		}
	}

}

else {
	alert(\"Sorry, the Google Maps API is not compatible with this browser\");
}

//]]>
</script>

</body>
</html>
";
# printf "$order[0] $order[1] $order[2] $order[3] $order[4] $order[5]";
print "<!-- end -->";


sub myPics {

	# MySQL CONFIG VARIABLES
	$host = "localhost";
	$database = "photoglide";
	$tablename = "picssi";
	$user = "photoglide";
	$pw = "photoglider";

	$coord = $clatd.','.$clongd;
	($x0,$y0) = split(/,/,$coord);
	$r=6378; #polmer zemlje;
	$pi = atan2(1,1) * 4;
	$x0=$x0*($pi/180); $y0=$y0*($pi/180);    # v radiane

#	$connect = DBI->connect('DBI:mysql:'.$database.';mysql_socket=/tmp/mysql.sock', $user, $pw) || print "Napaka $DBI::errstr";
	$connect = DBI->connect('DBI:mysql:'.$database.':localhost:33006', $user, $pw) || print "Napaka $DBI::errstr";

	$myquery = "SELECT * FROM $tablename";
	# $execute = $connect->query($myquery);
	$execute = $connect->prepare($myquery);
	$execute->execute();
	$i=0; $coordrow = '';
	while (@results = $execute->fetchrow_array()) {
		($x1,$y1)=split(/,/,$results[9]); $x1=$x1*($pi/180); $y1=$y1*($pi/180);
		$dist2=&acos(cos($x0)*cos($y0)*cos($x1)*cos($y1) + cos($x0)*sin($y0)*cos($x1)*sin($y1) + sin($x0)*sin($x1)) * $r;

		$newrowe = sprintf("%.5f%.5f|", $x1, $y1);	# če je koordinata ista kot ena od prejšnjih
		$ixrow = index($coordrow,$newrowe);

		if ($dist2 < $radius and $ixrow == -1) { 
			$coordrow = $coordrow.$newrowe;

			$thumbnail = $results[0];
			$thumbnail =~ s/\//\/thumbs\//;
	#		($mwidth, $mheight, $msize, $mformat) = $image->Ping('/home/photoglide/domains/photoglide.info/public_html/pics/'.$thumbnail);
#			($mwidth,$mheight)=&imgSize($homedir."/pics/$thumbnail");
#			$mwidth=$mwidth; $mheight=$mheight+40;
#			$mwidth=$mwidth.'px'; $mheight=$mheight.'px';		
			$mlink = "http://www.photoglide.info/index.php?option=com_content&view=frontpage&Itemid=58&query=coord&qstr=".$results[9];
			$results[1] = encode("Windows-1250", decode("utf8", $results[1]));
			printf "
			var opts = { 
				\"icon\": mypicsicon,
				\"clickable\": true,
				\"title\": \"$results[1]\"
			};

			var point = new GLatLng($results[9]);
			mypics[$i] = new LabeledMarker(point, opts);
			map.addOverlay(mypics[$i]);
			GEvent.addListener(mypics[$i], \"click\", function() {
				mypics[$i].openInfoWindowHtml('<div style=\"color:black; width:150px; height:150px;\"><b>$results[1]</b><br><a href=$mlink target=\"_blank\"><img src=\"/pics/$thumbnail\" border=0></a></div>');
			});	
			mypics[$i].hide();
			";
			$i++;
		}
	}
	print "
	startPoint = new GLatLng($coord);	// za krog 
	drawCircle(map, startPoint, $radius, 50);
	";
}


sub acos {
   my($x) = @_;
   if ($x > 1) {$x=1}
   my $ret = atan2(sqrt(1 - $x**2), $x);
   return $ret;
}