// prod.
//<script src="http://maps.google.com/maps?file=api&amp;v=2&key=ABQIAAAATqlHwG3-CM-NblMRMxP2NxRajfahhpj3khqJZtEMThMidOc0YxQmI1VyqB5OS6Pkap5Qf6TT0n9PPg" type="text/javascript">
// dev.
//<script src="http://maps.google.com/maps?file=api&amp;v=2&key=ABQIAAAATqlHwG3-CM-NblMRMxP2NxRo707mjIb_-CMOfWSg9n6J0qsBAhQC2AlJx_jE8hV4JhCcpAbn8m-KKQ" type="text/javascript">
// dev3.
// ABQIAAAATqlHwG3-CM-NblMRMxP2NxRw8UGbvsOPuOukYxtEsSOo-gJXthT_-6wJajhrXKV-zhoKpmj6Firwrw

var Langue = 'FR';
var Bdd = 'Q';
var DroitsCarto = "&copy;2009 FQCQ";
var LatiInit = 47.0;
var LongiInit = -72.0;
var ZoomInit = 7;
var host = 'mapqc.gpspleinair.com';

var map = null;
var bMapS = false;
var bMapC = true;
var bMapT = false;
var bdd = Bdd.toLowerCase();

var ie = document.all ? true : false;

var customTileLayer = null;

function InitMap()
{
	var copyCollection;
	if (Langue == 'EN')
		copyCollection = new GCopyrightCollection('Trails');
	else
		copyCollection = new GCopyrightCollection('Sentiers');
	var copyrightQ = new GCopyright(1, new GLatLngBounds(new GLatLng(44.5, -79), new GLatLng(62, -57)), 6, DroitsCarto);
	copyCollection.addCopyright(copyrightQ);

	var tilelayer = new GTileLayer(copyCollection, 6, 14);
	tilelayer.getTileUrl = CustomGetTileUrl;
	tilelayer.isPng = function() { return true;};
	tilelayer.getOpacity = function() { return 0.9; }

	customTileLayer = new GTileLayerOverlay(tilelayer);

	map.enableDoubleClickZoom();
	map.enableContinuousZoom();
	map.enableScrollWheelZoom();
	GEvent.addListener(map, "click", EventClickMap);
}

function CustomGetTileUrl(a,z) 
{
	var url = '';
	if (bMapS) {
		url = 'http://' + host + '/i2.php?a='+bdd+'s&x='+a.x+'&y='+a.y+'&z='+z;
	} else if (bMapC) {
		url = 'http://' + host + '/i2.php?a='+bdd+'c&x='+a.x+'&y='+a.y+'&z='+z;
	} else if (bMapT) {
		url = 'http://' + host + '/i2.php?a='+bdd+'t&x='+a.x+'&y='+a.y+'&z='+z;
	} else {
		url = '/images/vide.gif';
	}
	return url;
}

function SelectMap(m)
{
	var divLegendeSurface = document.getElementById('LegendeSurfacage');
	var divLegendeSentier = document.getElementById('LegendeSentier');
	CheckMap(m);
	bMapS = false;
	bMapC = false;
	bMapT = false;
	if (m == 'S') {
		bMapS = true;
//		divLegendeSurface.style.visibility = "hidden";
//		divLegendeSentier.style.visibility = "visible";
		divLegendeSurface.style.display = "none";
		divLegendeSentier.style.display = "block";
		customTileLayer.show();
	} else if (m == 'C') {
		bMapC = true;
		divLegendeSurface.style.display = "block";
		divLegendeSentier.style.display = "none";
		customTileLayer.show();
	} else if (m == 'T') {
		bMapT = true;
		divLegendeSurface.style.display = "none";
		divLegendeSentier.style.display = "block";
		customTileLayer.show();
	} else {
		divLegendeSurface.style.display = "none";
		divLegendeSentier.style.display = "none";
		customTileLayer.hide();
	}
	map.zoomOut();
	map.zoomIn();
}

function CheckMap(param)
{
	var F = document.getElementById('GROUP_MAP');
	if (F == null)
		return;
	for (var i = 0; i < F.SEL_MAP.length; i++) {
		if (F.SEL_MAP[i].value == param) {
			F.SEL_MAP[i].checked = true;
			break;
		}
	}
	SetCookie('FQCQ', param, date_exp, '/');
}

function RappelMap()
{
	var F = document.getElementById('GROUP_MAP');
	if (F == null)
		return;
	var m = GetCookie('FQCQ');
	if (m != null && m != '') {
		SelectMap(m);
	} else {
		SelectMap('C');
	}
}

function InitPosition()
{
	var f = extractUrlParams();
	if (f == null)
		return;
	var v = f['LATI'];
	if (v != null) {
		LatiInit = v;
	}
	v = f['LONGI'];
	if (v != null) {
		LongiInit = v;
	}
	v = f['ZOOM'];
	if (v != null) {
		ZoomInit = v * 1;
	}
}

function extractUrlParams ()
{
	if (location.search == null)
		return null;
	var t = location.search.substring(1).split('&');
	var f = [];

	for (var i=0; i<t.length; i++) {
		var x = t[i].split('=');
		f[x[0]]=x[1];
	}
	return f;
}

function load()
{
	map = new GMap2(document.getElementById("map"));

	InitMap();
	InitPosition();

	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	map.addMapType(G_PHYSICAL_MAP); 
	map.addControl(new GScaleControl());
	map.addControl(new GOverviewMapControl());
	map.setCenter(new GLatLng(LatiInit, LongiInit), ZoomInit);
	map.setMapType(G_PHYSICAL_MAP);
	map.enableDoubleClickZoom();
	map.enableContinuousZoom();
	map.enableScrollWheelZoom();
    map.addControl(new PanoMapTypeControl());
	map.addOverlay(customTileLayer);

	bLoad = true;
}

//////////////////////
function largeur_fenetre()
{
	if (window.innerWidth) {
		return window.innerWidth  ;
	} else if (document.documentElement && document.documentElement.clientWidth) {
 		return document.documentElement.clientWidth;
	} else {
		return screen.width - 50;
	}
}

function hauteur_fenetre()
{
	if (window.innerHeight) {
		return window.innerHeight  ;
	} else if (document.documentElement && document.documentElement.clientHeight) {
 		return document.documentElement.clientHeight;
	} else {
		return screen.height - 100;
	}
}

var old_w = 0;
var old_h = 0;

function Resize()
{
	var m = document.getElementById('map');
	var w = largeur_fenetre();
	var h = hauteur_fenetre();

	h = h - 65; // Header.
	w = w - 147; // partie droite de la fenetre.
w = w - 10;
	if (old_w == w && old_h == h)
		return;
	old_w = w;
	old_h = h;
	m.style.width = w + 'px';
	m.style.height = h + 'px';
	if (map != null)
		map.checkResize();
}

/////////////////////////////
// Altitude.

function EventClickMap(marker, point)
{
	if (point != null) {
		Altitude(point);
		ArcProche2(point);
	}
}

function Altitude(point)
{
	var request = GXmlHttp.create();
	var url = "/carto/alti.php?LATI=" + point.lat() + "&LONGI=" + point.lng();
	//url = url + "&DEBUG=1";
	if (ie) {
		url = url + '&RND=' + Math.random(); // probleme de cache avec ie.
	}
	request.open('GET', url, true);

	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var d = document.getElementById('Alti');
			var alti = request.responseText;
			if (alti.length < 1 || alti.length > 5)
				alti = '';
			else 
				alti = alti + ' m';
			d.innerHTML = alti;
		} // readyState.
	} // Fin de fonction.
	request.send(null);
}

///////////////////////////
// Arc proche.
var TabArc = new Array();

function TArc(iArc)
{
	this.iArc = iArc;
	this.polyline = null;
	this.Longueur = 0;
}

function ArcProche2(point)
{
	if (bMapT)
		Bdd = 'QT';
	else
		Bdd = 'Q';
	var request = GXmlHttp.create();
	var url = "/carto/trail.php?BDD=" + Bdd + "&CMD=ARC&DEBUG=0&LATI=" + point.lat() + "&LONGI=" + point.lng();
	if (ie) {
		url = url + '&RND=' + Math.random(); // probleme de cache avec ie.
	}
	request.open('GET', url, true);
	document.getElementById('wait').src = '/images/maprace/miniglobe.gif';

	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var iArc = request.responseText;
			if (iArc > 0) {
				var bTrouve = false;
				for (var i = 0; i < TabArc.length; i++) {
					if (TabArc[i].iArc == iArc) {
						map.removeOverlay(TabArc[i].polyline);
						TabArcEnleve(i);
						MajLongueur();
						bTrouve = true;
						break;
					}
				}
				document.getElementById('wait').src = '/images/vide.gif';
				if (!bTrouve) {
					ArcSel(iArc);
				}
			}
		} // readyState.
	} // Fin de fonction.
	request.send(null);
}

function ArcSel(iArc)
{
	var request = GXmlHttp.create();
	var url = "/carto/trail.php?BDD=" + Bdd + "&CMD=ARCJS&DEBUG=0&ARC="+iArc;
	if (ie) {
		url = url + '&RND=' + Math.random(); // probleme de cache avec ie.
	}
	request.open('GET', url, true);
	document.getElementById('wait').src = '/images/maprace/anibull1.gif';

	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var js = request.responseText;
			var P;
			eval(js);
			var Arc = new TArc(iArc);
			//Arc.iArc = iArc;
			P.index = TabArc.length;
			Arc.polyline = P;
			Arc.Longueur = L;
			Arc.index = TabArc.length;
			TabArc.push(Arc);
			MajLongueur();
			var txt = '';
			if (NoPiste > 0)
				txt = '#' + NoPiste;
			if (NomClub != '') {
				if (txt != '')
					txt = txt + ' ';
				txt = txt + NomClub;
			}
			document.getElementById('InfoSentier').innerHTML = txt;

			GEvent.addListener(P, "click", function() {
				map.removeOverlay(TabArc[P.index].polyline);
				TabArcEnleve(P.index);
				MajLongueur();
		  	});
			map.addOverlay(P);
			document.getElementById('wait').src = '/images/vide.gif';
		} // readyState.
	} // Fin de fonction.
	request.send(null);
}

function TabArcEnleve(i)
{
	TabArc[i].polyline = null;
	TabArc[i].iArc = 0; // Comme on ne sait pas enlever facilement un élément d'un tableau...
	TabArc[i].Longueur = 0;
}

function MajLongueur()
{
	var L = 0;
	for (var i = 0; i < TabArc.length; i++) {
		L += TabArc[i].Longueur;
	}
	var txt = L + ' m';
	if (L > 1000) {
		var deci = Math.floor((L / 100) % 10);
		var ent = Math.floor(L / 1000);
		txt = ent + '.' + deci + ' km';
	}
	var d = document.getElementById('Longueur');
	d.innerHTML = txt;
}

function RazSelection()
{
	for (var i = 0; i < TabArc.length; i++) {
		if (TabArc[i].iArc > 0 && TabArc[i].polyline != null) {
			map.removeOverlay(TabArc[i].polyline);
			TabArcEnleve(i);
		}
	}
	MajLongueur();
}


function VueRegion(selObj)
{
	var LLW = selObj.options[selObj.selectedIndex].value;
	selObj.selectedIndex = 0;
	var t = LLW.split(',');
	if (t.length != 3)
		return;
	var Lati = t[0];
	var Longi = t[1];
	var W = t[2];
	var zoomLevel = getZoomLevel(Lati, W*1000);
	map.setCenter(new GLatLng(Lati, Longi), zoomLevel);
}

function getZoomLevel(lati,w)
{
	var longi = -70;
	lati = lati * 1.0;
	if (lati == 0) {
		var centre = map.getCenter();
		lati = centre.lat();
		longi = centre.lng();
	}
	// Calcul d'un rectangle tres aplati (tant pis pour le format réel de l'écran).
	// //Calcul d'un carré (tant pis pour le format réel de l'écran).
	var R = 6400000;
	var dLongi = w / (R * Math.cos(lati * Math.PI / 180));
	dLongi = dLongi * 180 / Math.PI;
	//dLongi = dLongi * 0.8; // pour les arrondis.
	var dLati = w / R;
	dLati = dLati * 180 / Math.PI;
	//dLati = dLati / 10; // Rectangle tres aplati.
	var sw = new GLatLng(lati - dLati, longi - dLongi);
	var ne = new GLatLng(lati + dLati, longi + dLongi);
	var bounds = new GLatLngBounds(sw, ne);
	var l = map.getBoundsZoomLevel(bounds);
	l = l + 1; // Ca parait mieux...
//	map.setZoom(l);
	return l;
}

var markerAddress = null;

function showAddress(address)
{
	var geocoder = new GClientGeocoder();
	if (geocoder) {
		geocoder.setBaseCountryCode('ca');
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					//alert(address + " not found");
				} else {
					if (markerAddress != null)
						map.removeOverlay(markerAddress);
					map.setCenter(point, 13);
					markerAddress = new GMarker(point);
					map.addOverlay(markerAddress);
					//marker.openInfoWindowHtml(address);
				}
			}
		);
	}
}

var firstPass = true;

function firstAddress()
{
	if (firstPass) {
		var a = document.getElementById('ADRESSE');
		if (a.value == 'Centrer sur adresse...')
			a.value = '';
		firstPass =false;
	}
}

