/* ADT21 : fonctions de traitement pour les cartographies */

var date = new Date();
var dateJour=date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
//ajout de la date et heure pour differencier les fichier dans le cache du proxy google
var browser=navigator.userAgent.toLowerCase();

var marqueurs = new Array();
var nb_element = 0;

var map_proximite;
var map_localisation;
var geoXml;
var repertXml;
var rechXml;
var rechEnCours = 0;
var centerMap ;
var boundsMap ;
var zoomMap;
var agrandi = 0;

function init_view_map(){



	    var id_map = 'sentier_carte_generale';
	    if(agrandi == 1)
		id_map = 'sentier_carte_agrandi';
	if(document.getElementById(id_map))
	{
	    map_generale = map_init_generale(id_map);
	}

// 	if(document.getElementById('adt21_detail_localisation'))
// 	{
// 		map_localisation = map_init_localisation('adt21_detail_localisation');
// 	}
}


function map_init(div_id, lat, lng, zoom){

	var map = new GMap2(document.getElementById(div_id));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMenuMapTypeControl());
map.addMapType(G_PHYSICAL_MAP);
map.addMapType(G_SATELLITE_3D_MAP);
	map.setCenter(new GLatLng(lat ,lng), zoom);
	//permet de zoomer avec la molette de la souris
	map.enableScrollWheelZoom();

	return map;
}

function map_init_generale(div_id){



	var map = new GMap2(document.getElementById(div_id));
	//centre la carte sur le point fournit en paramètre (14=zoom)

      map.setCenter(new GLatLng(47.5 ,  5), 8);
	if(agrandi == 1)
	{
	 map.addControl(new GLargeMapControl());
	 map.addControl(new GMenuMapTypeControl());
	  map.addMapType(G_PHYSICAL_MAP);
	  map.addMapType(G_SATELLITE_3D_MAP);
	  var ovcontrol = new GOverviewMapControl(new GSize(150,150));

        map.addControl(ovcontrol);

        //permet de zoomer avec la molette de la souris
        map.enableScrollWheelZoom();
	}
	if(gpx_complet != '')
// 		LoadGPXFileIntoGoogleMap(map, gpx_complet, '#590000', '4', 0);
        if(gpx != '')
//                LoadGPXFileIntoGoogleMap(map, gpx, '#340000', '5', 1);
                LoadGPXFileIntoGoogleMap(map, gpx, '#B40014', '5', 1);
        geoXml = new GGeoXml(flux_etapes);

        map.addOverlay(geoXml);
        var listener =GEvent.addListener(geoXml, 'load', function() {
            if (geoXml.loadedCorrectly()) {
                //zoomToGeoXML(map, geoXml);
                //repertXml.gotoDefaultViewport(map);
            }
        });


/*
	GEvent.addListener(geoXml2, 'load', function() {
		if (geoXml2.loadedCorrectly()) {
			zoomToGeoXML(map, geoXml2);
	}
	});*/

	return map;
}
function LoadGPXFileIntoGoogleMap(map, filename, colour, width, center)
		{
	// Remove any existing overlays from the map.
	//map.clearOverlays();

	var request = google.maps.XmlHttp.create();
	request.open("GET", filename, true);
	request.onreadystatechange = function()
	{
		if (request.readyState == 4)
		{
			parser = new GPXParser(request.responseXML, map);
			parser.SetTrackColour(colour);					// Set the track line colour
			parser.SetTrackWidth(width);							// Set the track line width
			parser.SetMinTrackPointDelta(0.001);				// Set the minimum distance between track points
                        if(center == 1){
                              parser.CenterAndZoom(request.responseXML, G_NORMAL_MAP); // Center and Zoom the map over all the points.
                              id_time = setTimeout(""+parser.CenterAndZoom(request.responseXML, G_NORMAL_MAP),1000);
                        }
			parser.AddTrackpointsToMap();						// Add the trackpoints
			parser.AddWaypointsToMap();							// Add the waypoints



		}
	}
	request.send(null);
}


function getQueryString()
{
	var result = new Array();
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++)
	{
		var pos = parms[i].indexOf('=');
		if (pos > 0)
		{
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			result[key] = val;
		}
	}

	return result;
}




function map_view_recherche(map, id, distance, typeObj){

	/*if(rechEnCours == 1)
	{
		map.removeOverlay(rechXml);
	}*/

	rechXml = new GGeoXml(flux_recherche+"?id="+id+"&distance="+distance+"&objet="+typeObj+"&date="+dateJour);
	map.addOverlay(rechXml);

	marqueurs.push(rechXml);

	rechEnCours = 1;
}

function map_view_recherche_clear_all(map){
	for (i = 0; i < marqueurs.length; i++)
	{
		map.removeOverlay(marqueurs[i]);
	}

}

function zoomToGeoXML(map, geoXml) {

	var center = geoXml.getDefaultCenter();
	var span = geoXml.getDefaultSpan();
	var sw = new GLatLng(center.lat() - span.lat() / 2,
			center.lng() - span.lng() / 2);
	var ne = new GLatLng(center.lat() + span.lat() / 2,
			center.lng() + span.lng() / 2);
	var bounds = new GLatLngBounds(sw, ne);

	centerMap = center;
	boundsMap = bounds;
	map.setCenter(center);
	map.setZoom(map.getBoundsZoomLevel(bounds));


}


function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
  return decodeURIComponent( escape( s ) );
}

var Utf8 = {

	// public method for url encoding
	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// public method for url decoding
	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}


