/**
 * @author stefan
 */

/*
function GMapsAPILoaded() {
	alert ("GMapsAPILoaded()");
	var e = document.createElement("div");
	e.id = "api_is_loaded";
}
*/


/*if (document.getElementById("track_view_script_container") == null) {
	alert("add script");
 	var e = document.createElement("script");
    e.src = "http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA61JqGkc4KeAh3PvwHkB1bxTa8dVwHQsM89IKgwF3wdgmUFyiXxQT0NN_gO12VLMl70qBSsMVsQIiIw&callback=GMapsAPILoaded";
    e.type= "text/javascript";
	e.id =  "track_view_script_container"
    document.getElementsByTagName("head")[0].appendChild(e); 
	//document.write('<div id="track_view_script_container"><script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA61JqGkc4KeAh3PvwHkB1bxTa8dVwHQsM89IKgwF3wdgmUFyiXxQT0NN_gO12VLMl70qBSsMVsQIiIw" type="text/javascript"><\/script></div>');
}*/

//function waitForGMapsAPI() {
	/*setInterval(function () {
	  if (document.getElementById("api_is_loaded") != null) {
	  	clearInterval();
	  }
		
	},10);	*/
	//while (document.getElementById("api_is_loaded") == null) {
	  //;
//	}

//}

function display_map_with_plot(container,plot_container){
	var mymap = new GMap2(container);
	mymap.setMapType(G_PHYSICAL_MAP);
	mymap.setCenter(new GLatLng(48.1331, 11.6618), 11);
	mymap.setUIToDefault();
	//mymap.addControl(new GLargeMapControl());
	
	//makeShape();
	
	var marker = new GMarker(new GLatLng(48.1331, 11.6618));
	
	GDownloadUrl("karwendelhaus.gpx", function(data, responseCode) {
		var xml = GXml.parse(data);
	  	var markers = xml.documentElement.getElementsByTagName("trkpt");
	  	var track_points = [], heights = [], distances = [];
		var lat_min = parseFloat(markers[0].getAttribute("lat"));
		var lat_max = lat_min;
		var lon_min = parseFloat(markers[0].getAttribute("lon"));
		var lon_max = lon_min;
		var height, lon, lat, lat_before, lon_before;
		var dist = 0.0;
		var new_dist = 0.0;
  		for (var i = 0; i < markers.length; i++) {
			lat = parseFloat(markers[i].getAttribute("lat"));
			lon = parseFloat(markers[i].getAttribute("lon"));
			// Improve this!
			height = parseFloat(markers[i].childNodes[1].firstChild.data);
			lat_min = (lat < lat_min) ? lat : lat_min;
			lat_max = (lat > lat_max) ? lat : lat_max;
			lon_min = (lon < lon_min) ? lon : lon_min;
			lon_max = (lon > lon_max) ? lon : lon_max;
			track_points.push(new GLatLng(lat,lon));
		
			heights.push(height);
			if (i > 0) {
				new_dist = compute_distance(lat_before,lon_before,lat,lon);
				distances.push(new_dist);
				dist += new_dist;
			}
			lat_before = lat;
			lon_before = lon;
 	 	}
		marker.setLatLng(track_points[0]);
		var lat_center = (lat_min + lat_max)/2.0;
		var lon_center = (lon_min + lon_max)/2.0;
		//alert(lat_min + " " + lat_max + " " + lon_min + " " + lon_max + " " + lat_center + " " + lon_center);
		//alert("complete distance: " + dist + " km.");
		//alert ("dtances.length: " + distances.length);
		plot_height(plot_container,heights,distances,dist,track_points,marker);
		mymap.savePosition();
		mymap.panTo(new GLatLng(lat_center,lon_center));
		//alert (markers.length);
		var poly_line = new GPolyline(track_points, "#ff0000", 5);
    	mymap.addOverlay(poly_line);
		mymap.addOverlay(marker);
	});
}

var svgns = "http://www.w3.org/2000/svg";

function plot_height(container_element, height_values, distances, complete_distance,t_points, map_marker) {
	var hp = container_element;
	var width = parseInt(hp.style.width);
	var height = parseInt(hp.style.height);
	
	var px_heights = [];
	var px_latlng = [];
	
	var dist_sum = 0.0;
	var avg_height = 0.0;
	var avg_num = 0;
	//alert ("distances.length: " + distances.length + "px_dist " + px_dist);
	var min_height = height_values[0];
	var max_height = height_values[0];
	var offset_left = 50;  // reserve 50 px on the left
	var offset_top = 10; // 5 px border on the top
	var offset_bottom = 20; // 20 px on the bottom;
	var offset_right = 1 // 1px on the right;
	var plot_color = "red";
	
	height = height - offset_top - offset_bottom;
	width = width - offset_left - offset_right;
	var px_dist = complete_distance / width;

	for	(var i = 0; i < distances.length; i++) {
		min_height = (height_values[i] < min_height) ? height_values[i] : min_height;
		max_height = (height_values[i] > max_height) ? height_values[i] : max_height;
		avg_height += height_values[i];
		avg_num++;
		dist_sum += distances[i];
		if (dist_sum >= px_dist) {
		if (i < 10) {
			//alert(height_values[i]);
		}
			
			px_heights.push(avg_height/avg_num);
			px_latlng.push(t_points[i]);
			avg_height = 0.0;
			avg_num = 0;
			dist_sum -= px_dist;
		}
	}
	
	max_height *= 1.05;
	min_height *= 0.95;
	
    var svgElement = document.createElementNS(svgns,"svg");
	svgElement.setAttributeNS(null,"version",1.1);
	svgElement.setAttributeNS(null,"width","100%");
	svgElement.setAttributeNS(null,"height","100%");
  	hp.appendChild(svgElement);

    //alert (px_heights.length);
	var points_str = "";
	for (var i = 0; i < px_heights.length; i++) {
		
		var hy = height * (px_heights[i]-min_height)/(max_height-min_height);
		
		points_str = points_str + (i+offset_left) + "," + (height-1-hy+offset_top) + " ";
	}
	var shape = document.createElementNS(svgns, "polyline");
    shape.setAttributeNS(null, "points", points_str);
    shape.setAttributeNS(null, "fill", "none");
    shape.setAttributeNS(null, "stroke", plot_color);
    shape.setAttributeNS(null, "stroke-width", "4");
    svgElement.appendChild(shape);
	
	var ruler = document.createElementNS(svgns,"line");
	ruler.setAttributeNS(null,"x1",offset_left);
	ruler.setAttributeNS(null,"y1",offset_top);
	ruler.setAttributeNS(null,"x2",offset_left);
	ruler.setAttributeNS(null,"y2",offset_top+height-1);
    ruler.setAttributeNS(null, "stroke", "black");
	ruler.setAttributeNS(null, "stroke-width", "2");
	svgElement.appendChild(ruler);

	var axis = document.createElementNS(svgns,"line");
	axis.setAttributeNS(null,"x1",offset_left);
	axis.setAttributeNS(null,"y1",offset_top);
	axis.setAttributeNS(null,"x2",offset_left);
	axis.setAttributeNS(null,"y2",offset_top+height-1);
    axis.setAttributeNS(null, "stroke", "black");
	axis.setAttributeNS(null, "stroke-width", "2");
	svgElement.appendChild(axis);

	axis = document.createElementNS(svgns,"line");
	axis.setAttributeNS(null,"x1",offset_left+width);
	axis.setAttributeNS(null,"y1",offset_top);
	axis.setAttributeNS(null,"x2",offset_left+width);
	axis.setAttributeNS(null,"y2",offset_top+height-1);
    axis.setAttributeNS(null, "stroke", "black");
	axis.setAttributeNS(null, "stroke-width", "2");
	svgElement.appendChild(axis);
	
	axis = document.createElementNS(svgns,"line");
	axis.setAttributeNS(null,"x1",offset_left);
	axis.setAttributeNS(null,"y1",offset_top);
	axis.setAttributeNS(null,"x2",offset_left+width);
	axis.setAttributeNS(null,"y2",offset_top);
    axis.setAttributeNS(null, "stroke", "black");
	axis.setAttributeNS(null, "stroke-width", "2");
	svgElement.appendChild(axis);

	axis = document.createElementNS(svgns,"line");
	axis.setAttributeNS(null,"x1",offset_left);
	axis.setAttributeNS(null,"y1",offset_top+height-1);
	axis.setAttributeNS(null,"x2",offset_left+width);
	axis.setAttributeNS(null,"y2",offset_top+height-1);
    axis.setAttributeNS(null, "stroke", "black");
	axis.setAttributeNS(null, "stroke-width", "2");
	svgElement.appendChild(axis);
	// add axis texts
	
	var num_texts = Math.floor(height / 30);
	
	var unit = (max_height - min_height) / num_texts;
	
	if (unit < 50) unit = 50;
	if (unit >  50 && unit < 100) unit = 100;
	if (unit >  100 && unit < 200) unit = 200;
	if (unit >  200 && unit < 250) unit = 250;
	if (unit >  250 && unit < 300) unit = 300;
	if (unit >  300 && unit < 400) unit = 400;
	if (unit >  400 && unit < 500) unit = 500;
		
	var mark_height = (Math.floor(min_height / unit) + 1) * unit;
	
	while (mark_height < max_height) {
		var text_elem = document.createElementNS(svgns,"text")
		var text_data = document.createTextNode("" + mark_height + " m");
		var hy = height * (mark_height-min_height)/(max_height-min_height);
	    text_elem.setAttributeNS(null, "x", "0");
   	 	text_elem.setAttributeNS(null, "y", height-1-hy+offset_top + 4);
   		text_elem.setAttributeNS(null, "fill", "black");
   	 	text_elem.setAttributeNS(null, "text-anchor", "start");

    	text_elem.appendChild(text_data);
    	svgElement.appendChild(text_elem);
		
		
		var height_mark = document.createElementNS(svgns,"line");
		height_mark.setAttributeNS(null,"x1",offset_left-2);
		height_mark.setAttributeNS(null,"y1",height-1-hy+offset_top);
		height_mark.setAttributeNS(null,"x2",offset_left+2);
		height_mark.setAttributeNS(null,"y2",height-1-hy+offset_top);
    	height_mark.setAttributeNS(null, "stroke", "black");
		height_mark.setAttributeNS(null, "stroke-width", "1");
		svgElement.appendChild(height_mark);	
		
		mark_height += unit;
	}
	
	// the other axis
	num_texts = Math.floor(width / 50);
	
	var unit = (complete_distance) / num_texts;
	
	if (unit < 1) unit = 1;
	if (unit >  1 && unit < 2) unit = 2;
	if (unit >  2 && unit < 4) unit = 4;
	if (unit >  4 && unit < 5) unit = 5;
	if (unit >  5 && unit < 10) unit = 10;
	if (unit >  10 && unit < 20) unit = 20;
	if (unit >  20 && unit < 50) unit = 50;
		
	var mark_width = unit;
	
	while (mark_width < (complete_distance-unit)) {
		var text_elem = document.createElementNS(svgns,"text")
		var text_data = document.createTextNode("" + mark_width + " km");
		var hx = width * (mark_width)/(complete_distance);
	    text_elem.setAttributeNS(null, "x", offset_left + hx-15);
   	 	text_elem.setAttributeNS(null, "y", height + offset_top + 15);
   		text_elem.setAttributeNS(null, "fill", "black");
   	 	text_elem.setAttributeNS(null, "text-anchor", "start");

    	text_elem.appendChild(text_data);
    	svgElement.appendChild(text_elem);
		
		
		var height_mark = document.createElementNS(svgns,"line");
		height_mark.setAttributeNS(null,"x1",offset_left+hx);
		height_mark.setAttributeNS(null,"y1",height-1-2+offset_top);
		height_mark.setAttributeNS(null,"x2",offset_left+hx);
		height_mark.setAttributeNS(null,"y2",height-1+2+offset_top);
    	height_mark.setAttributeNS(null, "stroke", "black");
		height_mark.setAttributeNS(null, "stroke-width", "1");
		svgElement.appendChild(height_mark);	
		
		mark_width += unit;
	}
	
	hp.onmousemove = function(evt){
		posx = evt.clientX - hp.offsetLeft;
		posy = evt.clientY - hp.offsetTop;
		if (posx > offset_left) {
			ruler.setAttributeNS(null, "x1", posx);
			ruler.setAttributeNS(null, "x2", posx);
			map_marker.setLatLng(px_latlng[posx-offset_left]);
		}
		//alert("mouse over " + posx + ", " + posy);
	};

}

 
 function compute_distance(lat1, lon1, lat2, lon2) {
 	var dx = 71.5 * (lon1 - lon2);
	var dy = 111.3 * (lat1 - lat2);
	
	return Math.sqrt (dx*dx + dy*dy);
 }

