//*******************************************************************************************
//*		Description  : 	Fonctions javascript nécessaire pour le module "gMaps.php"
//*
//*		Programmeurs :	Christian Charest 	[CC]  
//*
//*******************************************************************************************

	//****** AJAX functions
	function gm_setInfos(params){
		setInfos(location.href+"?"+params);
	}

	//Mettre a jour les coordonnées d'un markeur
	function updateMarkerPt(uid, newPt){

		//Trouver le marker dans la liste qui correspond au uid
		for(var i = 0; i < markers.length; i++)
		if (markers[i].uid == uid)
		{
			markers[i].setPoint(newPt);
			break;
		}

		//Si le markeur est selui selectionn�, le mettre a jour
		if (selMarker.uid == uid)
			selMarker.setPoint(newPt);
			
		if (useMarkMan)
			markerMan.refresh();
	}	
	//******

	function selectMarker(overlay){

		if (typeof overlay == "undefined"){overlay = selMarker}

		if (selMarker == null)
		{
			selMarker = addMarker("", overlay.getPoint(), true);
			map.addOverlay(selMarker);
		}
		else
			selMarker.setPoint(overlay.getPoint());

		selMarker.postal  = overlay.postal;
		selMarker.address = overlay.address;
		selMarker.uid     = overlay.uid;
		
		//markerMan.refresh();
	}
			
	function selectMarkerByPt(point){

		var markerPoint	;
		var precision = 0.0000000000001;
		for(var i = 0; i < markers.length; i++)
		{
			markerPoint	= markers[i].getPoint();

			var diffX = Math.abs(markerPoint.lng() - point.lng());
			var diffY = Math.abs(markerPoint.lat() - point.lat());

			if ( diffX <= precision && diffY <= precision )
			{
				selectMarker(markers[i]);
				break;
			}
		}
	}
			
	function selectMarkerById(uid){

		for(var i = 0; i < markers.length; i++)
		if (markers[i].uid == uid)
		{
			selectMarker(markers[i]);
			break;
		}
	}
							
	function addMarker(icon, point, selected){

		if (typeof selected == "undefined"){selected = false}

		
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		
		if (selected && iconSel == false)
			baseIcon.image      = "";
		else if (selected)
			baseIcon.image      = coreRel+"images/gmap-icon-sel.png";
		else if(icon.length > 0)
			baseIcon.image      = icon;
		else
			baseIcon.image      = coreRel+"images/gmap-icon.png";
		baseIcon.iconSize   = new GSize(iconWidth, iconHeight);
		baseIcon.iconAnchor = new GPoint(anchorX, anchorY);
		baseIcon.shadow     = "";
		var markerOptions = { icon:baseIcon };
		var marker = new GMarker(point, markerOptions);

		if (selected === false)
			markers.push(marker);

		return marker;
	}
	
	function addFirstMarkerFromPostalList(callback){

		if("undefined" == typeof callback) {callback = null;}

		info = convPostalInfos.shift();

		geocoder.getLatLng( info[1],
		function(point){
	
			if (!point)
			{
				//nothing
				if (callback != null && convPostalInfos.length == 0)
				{
					callback();

				}
			}
			else
			{
				marker = addMarker(info[4], point);
				marker.myhtml  = info[0];
				marker.postal  = info[1];
				marker.uid     = info[2];
				marker.address = info[3];
				marker.icon	   = info[4];

				//Si c'est le dernier de la liste, executer le callback
				if (callback != null && convPostalInfos.length == 0)
				{
					callback();

				}

				gm_setInfos("gmAction=saveMarker&id="+info[2]+"&lng="+point.lng()+"&lat="+point.lat());
			}
		
		});
	}


	function addFirstMarkerFromAddrList(callback){

		if("undefined" == typeof callback) {callback = null;}

		info = convAddrInfos.shift();

		geocoder.getLatLng( info[3],
		function(point){
						
			if (!point)
			{
				convPostalInfos.push(info);
				gm_setInfos("gmAction=saveMarker&id="+info[2]);

				//Si c'est le dernier de la liste, executer le callback
				if (callback != null && convAddrInfos.length == 0)
					callback();
			}
			else
			{
				marker = addMarker(info[4], point);
				marker.myhtml  = info[0];
				marker.postal  = info[1];
				marker.uid     = info[2];
				marker.address = info[3];
				marker.icon    = info[4];

				//Si c'est le dernier de la liste, executer le callback
				if (callback != null && convAddrInfos.length == 0)
					callback();
				gm_setInfos("gmAction=saveMarker&id="+info[2]+"&lng="+point.lng()+"&lat="+point.lat());
			}
		
		});
	}
		    
	function centerOn(query, zoom, callback ){

		if("undefined" == typeof callback) {callback = null;}
		if("undefined" == typeof zoom) {zoom = defaultZoom;}
		
		geocoder.getLatLng( query,
		function(point){
			
			if (point != null)
			{
				map.setCenter(point, zoom);
				if (callback != null)
					callback(point);
			}
			else
				alert("Impossible de trouver : " + query);
		});
	}
		    
	function centerOnPt(lat, lng, callback){
		if("undefined" == typeof callback) {callback = null;}
		
		map.setCenter(new GLatLng(lat,lng), 16);
		if (callback != null)
			callback();
		
	}
		    
	function showPointerOn(point)
	{
		if (pointer == null)
		{
			var baseIcon      = new GIcon(G_DEFAULT_ICON);

			baseIcon.image      = "images/icon-pointer.png";
								
			baseIcon.iconSize   = new GSize(35, 35);
			baseIcon.iconAnchor = new GPoint(15,30);
			baseIcon.shadow     = "";
			var markerOptions   = { icon:baseIcon, draggable:true, bouncy:true };
			pointer = new GMarker(point, markerOptions);
			map.addOverlay(pointer);
		}
		pointer.setPoint(point);
	}

	function loadMarkersFromXML(xmlMarkers, callback)
	{
		
		if("undefined" == typeof callback) {callback = null;}
		var mLat 	= null;
		var mLng 	= null;
		var mInfoHTML	= null;
		var mPostal	= null;
		var mUid  	= null;
		var mAddress	= null;
		var mGeoFailed	= null;
		var mIcon	= null;
		var toDecode	= null;
		var iCpt	= 0;
		
		var refreshFct = function(){
			

			if (convAddrInfos.length == 0 && convPostalInfos.length == 0 )
			{
				
				if (useMarkMan){
					markerMan.addMarkers(markers, 7, 17);
					markerMan.refresh();
				}
				else{			
							
					for(var i=0; i < markers.length; i++)
						map.addOverlay(markers[i]);
				}
				
				if (typeof $ != "undefined"){
					var markerLoader = $('gmMarkerLoader');
					markerLoader.style.display = "none";
						//markerLoader.morph('.gmInactiveLoader');
				}

				if (callback != null)
					callback();
			}
			else if (convPostalInfos.length > 0)
			{
				//alert(convPostalInfos.length);
				for(var i = 0; i<convPostalInfos.length; i++ )
				{
					var fct = function(){addFirstMarkerFromPostalList()};
					setTimeout(fct, 250*i);
				}

				setTimeout(refreshFct, 250*convPostalInfos.length+1);
			}

		};

		var xml = GXml.parse(xmlMarkers);
		var nodes = xml.documentElement.getElementsByTagName("marker");
		for (var i = 0; i < nodes.length; i++)
		{
			mInfoHTML  = GXml.value(nodes[i]);
			//Si on detect le caractere pour coller les tab alors separer le code html et former les elements GInfoWindowTab
			if (mInfoHTML.indexOf(tabGlue) > -1 ){
				var tabsHTML = new Array();
				tabsHTML = mInfoHTML.split(tabGlue);
				mInfoHTML = new Array();
				
				for(var j=0; j<tabsHTML.length; j=j+2)
					mInfoHTML.push( new GInfoWindowTab(tabsHTML[j], tabsHTML[j+1]) );
				
			}
			
			mLat 	   = nodes[i].getAttribute("lat");
			mLng 	   = nodes[i].getAttribute("lng");
			mPostal    = nodes[i].getAttribute("postal");
			mAddress   = nodes[i].getAttribute("address");
			mUid	   = nodes[i].getAttribute("uid");
			mGeoFailed = nodes[i].getAttribute("geofailed");
			mIcon 	   = nodes[i].getAttribute("icon");

			if (mLat == "" || mLng == "" || (mLng == "0" && mLat == "0"))
			{
				var info = new Array();
				info[0] = mInfoHTML;
				info[1] = mPostal;
				info[2] = mUid;
				info[3] = mAddress;
				info[4] = mIcon;

				if (mGeoFailed == 0)
				{
					convAddrInfos.push(info);
					var fct = function(){addFirstMarkerFromAddrList(refreshFct)};
					setTimeout(fct, 250*iCpt);
					iCpt = iCpt + 1;
				}
				else
					convPostalInfos.push(info);
			}
			else
			{
				var point = new GLatLng(mLat, mLng);
				
				marker		= addMarker(mIcon, point);
				
				marker.myhtml   = mInfoHTML;
				marker.postal 	= mPostal;
				marker.uid 	= mUid;
				marker.address	= mAddress;
				marker.icon = mIcon;
			}
			
		}
		
		if (convAddrInfos.length == 0 )
			refreshFct();
	}

	function addAllMarkers(callback)
	{
		if("undefined" == typeof callback) {callback = null;}

		markers = new Array();
		//if (xmlData == null)
			GDownloadUrl(location.href+"?gmAction=xmlMarkers", function(data){loadMarkersFromXML(data, callback);xmlData=data;});
		//else
		//	loadMarkersFromXML(xmlData, callback);

	}
	
	function reloadMarkersFromArr(markersToReload, callback)
	{
		if("undefined" == typeof callback) {callback = null;}
		
		markers.each(function(marker, index){
			if (markersToReload[0] == marker.uid){
				map.closeInfoWindow();
				map.removeOverlay(marker);
				markers.splice(index,1);
			}
			
		});

		GDownloadUrl(location.href+"?gmAction=xmlMarkers"+"&filters="+markersToReload.join(';'), function(data){loadMarkersFromXML(data, callback);});
		
	}
		
	function askFromPostal(elem)
	{
		//infoDest[0] = selMarker.postal;//toPostal;
		//infoDest[1] = selMarker.address;
		elem.innerHTML = 'Entrez votre code postal : <br><input type="text" style="width:60px" onkeypress="checkEnter(event,function(){getDirections(this.parentNode.childNodes[2].value);})"><input type="button" value="Go" onclick="getDirections(this.parentNode.childNodes[2].value)">';
	}
		
	function getDirections(fromPostal)
	{
		var showDirectionsFCT = function(){
			//afficher la boite de directions et le titre
			var directions = document.getElementById("bmDirections");
			var dirContainer = document.getElementById("bmDirContainer");
			var title = document.getElementById("bmTitle");
			directions.innerHTML = '<div style="padding-left:10px;padding-top:10px"><a href="http://maps.google.ca/maps?f=d&hl='+ langue +'&saddr='+fromPostal+'&daddr='+selMarker.postal+'&z=14&om=1&pw=2" target="_blank"><img src="images/bt-page_03.gif" width="20" height="20" border="0" align="absmiddle">  Version imprimable</a></div>';

			if (parseInt(directions.style.width) != 300)
			{
				//Redimensionner la map
				var mapDiv = document.getElementById("map2");
				mapDiv.style.width  = parseInt(mapDiv.style.width) - 330 + "px";
				mapDiv.style.height  = parseInt(mapDiv.style.height) - 30 + "px";

				directions.style.width  = "300px";
				dirContainer.style.width  = "330px";
				dirContainer.style.display = "";
				dirContainer.style.height = mapDiv.style.height;

				title.style.height  = "30px";
				title.style.overflow = "hidden";
				title.style.display = "";

			}
			title.innerHTML = "<h2>"+selMarker.address+"</h2>";

			if (mapDirections != null)
				mapDirections.clear();
			mapDirections = new GDirections(map, directions);
			mapDirections.load("from:"+fromPostal + " to:" + selMarker.address);

			if (mapDirections.getNumGeocodes() != 2 )
				mapDirections.load("from:"+fromPostal + " to:" + selMarker.postal);

			//map.clearOverlays();
		}

		if (document.getElementById("map2") != null)
		{
			showDirectionsFCT();
			//map.clearOverlays();
		}
		else
			showBigMap(showDirectionsFCT);

	}

	function activateMap(mId)
	{
		map = mapArr[mId][0];
		
		if (useMarkMan){
			markerMan = mapArr[mId][1];
			if("undefined" != typeof markerMan){
				markerMan.refresh();
			}
		}
	}
	
	function openMarkersInfoWin(marker){
		if (typeof marker.myhtml == 'array')
			map.openInfoWindowTabsHtml(marker.getPoint(), marker.myhtml, {maxWidth:215});
		else
			map.openInfoWindowHtml(marker.getPoint(), marker.myhtml);
	}
			
	function loadGMap(callback, mapId)
	{
		if("undefined" == typeof callback || callback == null) {callback = addAllMarkers;}
		if("undefined" == typeof mapId) {mapId = "map";}

		if ( GBrowserIsCompatible() )
		{
			mId = mId+1;
			mapArr[mId] = new Array();
			mapArr[mId][0] = new GMap2( document.getElementById(mapId) );
			map = mapArr[mId][0];
			
			//Map Type
			//if ( [G_SATELLITE_MAP, G_NORMAL_MAP, G_HYBRID_MAP].contains( defaultMapType ) )
				map.setMapType(defaultMapType);
						
			map.addControl( new GLargeMapControl() );
			map.addControl( new GMapTypeControl() );
			//map.addControl( new GOsverviewMapControl() );
			
			map.enableDoubleClickZoom();
			map.enableContinuousZoom();
			map.enableScrollWheelZoom();
			
			centerOn(defaultZone, defaultZoom, function(){
				if (useMarkMan){
					mapArr[mId][1] = new GMarkerManager(map);
					markerMan = mapArr[mId][1];
				}
				
				callback();
			});
			
			GEvent.addListener(map, "click", function(overlay, point) {
				//if (overlay && typeof overlay.myhtml != "undefined"  && overlay.myhtml.length > 3)
				if (typeof overlay.myhtml != 'undefined')
				{			
					openMarkersInfoWin(overlay);
					//overlay.openInfoWindowHtml(overlay.myhtml);
					//if ($type(getExtInfos) == 'function')
					//	getExtInfos(overlay.uid);						
					selectMarker(overlay);
				}

			});
		
		}
	}
	

	function showBigMap(callback)
	{
		if("undefined" == typeof callback){callback = false;}

		width = document.body.clientWidth - 100;
		height = document.body.clientHeight - 100;
		
		
		var topCoord  = ((document.body.clientHeight/2)-(height/2));//+document.body.scrollTop;
		var leftCoord = (document.body.clientWidth/2)-(width/2);
 	
		onTopMap = document.createElement("DIV");
		onTopMap.id = "onTopMap";
		document.body.appendChild(onTopMap);
			
		filler = document.createElement("DIV");					
		filler.style.backgroundColor = "black";
		filler.style.position = "absolute";
		filler.style.top    = "0px";
		filler.style.left   = "0px";
		filler.style.width  = "100%";
		filler.style.height = document.body.scrollHeight;
		filler.style.zIndex  = "999996";
		filler.id = "bigMap";
		changeOpac(60, filler)
		onTopMap.appendChild(filler);
		
		container = document.createElement("DIV");
		container.style.position = "absolute";
		container.style.top    = topCoord+"px";;
		container.style.left   = leftCoord+"px";
		container.style.zIndex  = "999998";
		container.style.color = "white";	
		container.innerHTML = '<table border="0" cellpadding="0" cellspacing="0">' +
						'  <tr>' +
						'    <td width="10" height="15" background="images/forme-popup-big_04.gif"></td>' +
						'    <td height="15" background="images/forme-popup-big_05.gif"><div style="position:relative; float:right; ">' +
						'      <div id="fermer" style="position:absolute; background-image:url(images/forme-popup-big_02.gif); background-repeat: no-repeat; top:-20px; height:21px; width: 70px; left:-70px; cursor:pointer" onclick="hideBigMap();return false;"></div>' +
						'    </div> </td>' +
						'    <td width="11" height="15" background="images/forme-popup-big_06.gif"></td>' +
						'  </tr>' +
						'  <tr>' +
						'    <td width="10" background="images/forme-popup-big_07.gif"></td>' +
						'    <td bgcolor="#f3f1f0" valign="top"><div id="bmTitle" style="width:100%;display:none"></div><div id="bmDirContainer" style="display:none;overflow:auto;vertical-align:top;float:left;"><div id="bmDirections" style="background-color:white;height:100%;"></div></div><div style="height:'+height+'px;width:'+width+'px;float:left;overflow:hidden" id="map2"></div></td>' +
						'    <td width="11" background="images/forme-popup-big_09.gif"></td>' +
						'  </tr>' +
						'  <tr>' +
						'    <td width="10" height="16" background="images/forme-popup-big_10.gif"></td>' +
						'    <td height="16" background="images/forme-popup-big_11.gif"></td>' +
						'    <td width="11" height="16" background="images/forme-popup-big_12.gif"></td>' +
						'  </tr>' +
						'</table>';
		onTopMap.appendChild(container);
							
		frame = document.createElement("iframe");
		frame.style.position = "absolute";
		frame.style.top    = container.style.top;
		frame.style.left   = container.style.left;
		frame.style.width  = parseInt(width+18);
		frame.style.height = parseInt(height+28);
		frame.style.zIndex  = "999997"
		onTopMap.appendChild(frame);	
		
		//center on current map pos
		var curPt = map.getCenter();
		var curZm = map.getZoom();
		var fctToExec;

		fctToExec = function(){	
			if (callback != false)
				callback();
			else
			{
				//addAllMarkers();
				markerMan.addMarkers(markers, 7, 17);
				markerMan.refresh();

				map.addOverlay(selMarker);
				//selectMarker();
				map.setCenter(curPt, curZm);
			}
			map.enableScrollWheelZoom();
		}
		
		loadGMap(fctToExec, "map2");
		document.body.scrollTop  = 0;
		document.body.scrollLeft = 0;
		document.body.style.overflow = "hidden";
		//scrollY = (document.all)?document.body.scrollTop:window.pageYOffset;
	}