//***********************************************************
// Trail Locator Project
// The Trans Canada Trail
// http://www.tctrail.ca
// 
// Coding by Stephane Simard
// ssoutbox-tctrail@yahoo.com
//************************************************************


// Variable global
var isCompact = false;
var actualProcess = 0;
var compactOverlay = new Array();
var mappedExtendTrails = new Array();


//-------------------------------------------------------------------------------------------
// Remove Compact trail on the  MAP

function resetCompactOverlay()
{
	// Remove all compact trails
	for (var o=0 ; o<compactOverlay.length; o++) 
		map.removeOverlay(compactOverlay[o]);

	compactOverlay.length = 0;
	isCompact = false;
}


//-------------------------------------------------------------------------------------------
// Show Compact trail on MAP

function compactTrail()
{
	// for each trail
	for (var t=0; t<xmlCompact.length; t++)
	{
		var overlayList = new Array(0); 
		var seg = xmlCompact[t].getElementsByTagName("seg");
		
		// Print all segment
		for (var s=0; s<seg.length; s++) 
		{
			// get any state attributes
			var type = xmlCompact[t].getAttribute("type")
			var points = seg[s].getElementsByTagName("pnt");
			var pts = [];
			for (var p=0; p < points.length; p++) 
				pts[p] = new GLatLng(parseFloat(points[p].getAttribute("lat")), parseFloat(points[p].getAttribute("lng")));
						
			var color; // WATER or LAND
			if(type == "w")
				color = "#1946B9";
			else
				color = "#B6211B";
			
			// show polyline on map
			var poly = new GPolyline(pts, color, 3, 0.8);
			// Get Event for this segment
			GEvent.addListener(poly, "click", function(latlng) 
			{
				// If tools calcul distance is enable, put marker on map
				if(document.getElementById("distanceDiv").style.display == "block")
					clickDistanceEvent(null, latlng);
			});
			map.addOverlay(poly);
			compactOverlay.push(poly);
		}
	}
}


//-------------------------------------------------------------------------------------------
// Remove Extend trail on the  MAP

function resetExtendOverlay()
{
	// for each trail
	for(var t=0; t<mappedExtendTrails.length; t++)
	{			
		// remove all segment on map
		for(var s = 0; s<trailsList[mappedExtendTrails[t]].segmentArrayIndex; s++)
			map.removeOverlay(trailsList[mappedExtendTrails[t]].segmentArray[s].overlay);
		
		// remove all segment in memory
		trailsList[mappedExtendTrails[t]].resetOverlay();
	}
	mappedExtendTrails.length = 0;
	resetHighlight(false);	// remove highlighting
}


//-------------------------------------------------------------------------------------------
// Find trail to show  on MAP

function extendTrail()
{	
	// Empeche plusieurs appel en même temps de la fonction
	// Par exemple sur plusiuers drag très rapide 
	if(actualProcess == 1)
		return;				// Un process est deja en cours - return
	else
		actualProcess = 1;	// On commence le process
	
	// Prendre les coordonnees de la map visualise par l'usager et agrandir la zone virtuellement
	var mapBounds = map.getBounds();
	var sw = mapBounds.getSouthWest();
	var ne = mapBounds.getNorthEast();
	var virtualMapBounds = new GLatLngBounds(new GLatLng(sw.y - 0.3, sw.x - 0.3), new GLatLng(ne.y + 0.3, ne.x + 0.3));
			
	// Parcourir les sentiers pour savoir lequel doit etre afficher
	for(var t=0; t<trailListIndex; t++)
	{			
		// Recuperer le bounds de chaque trail
		var strParam = trailsList[t].sw + "," + trailsList[t].ne;
		var param = strParam.split(',');  // split les param
		var trailBounds  = new GLatLngBounds(new GLatLng(param[0],param[1]), new GLatLng(param[2],param[3]));

		// Si le sentier est dans la zone consulté par l'usager on affiche sur la MAP
		if (virtualMapBounds.intersects(trailBounds) && trailsList[t].isMapped == false)
			addTrailOverlay(t);
			
		// Si le sentier n'est pas dans la zone consulté et qu'il est affiché, on doit effacer
		else if(!virtualMapBounds.intersects(trailBounds) && trailsList[t].isMapped == true)
		{
			// Enlever tous les segments d'un numero
			for(var s=0; s<trailsList[t].segmentArrayIndex; s++)
				map.removeOverlay(trailsList[t].segmentArray[s].overlay);
			
			// Effacer overlays en mémoire
			trailsList[t].resetOverlay();
			for (var i=0; i<mappedExtendTrails.length; i++)
			{
				if(t == mappedExtendTrails[i])
					mappedExtendTrails.splice(i,1);
			}
			
			// Enlever le highlight
			if(trailsList[t].isHighlight == true)
				resetHighlight(false);
		}
	}
	
	actualProcess = 0;	// On termine le process
}


//-------------------------------------------------------------------------------------------
// Show Extend trail on MAP

function addTrailOverlay(trailIndex)
{
	var seg = xmlExtend[trailIndex].getElementsByTagName("seg");
	var type = xmlExtend[trailIndex].getAttribute("type");
	trailsList[trailIndex].isMapped = true;
	mappedExtendTrails.push(trailIndex);
		
	// Parcourir les segment du sentier et les afficher 
	for (var s=0; s<seg.length; s++)
	{
		// get any state attributes
		var points = seg[s].getElementsByTagName("pnt");
		var pts = [];
		
		// Prendre chaque points du segment
		for (var p=0; p<points.length; p++)
			pts[p] = new GLatLng(parseFloat(points[p].getAttribute("lat")), parseFloat(points[p].getAttribute("lng")));
		
		var color; // Determine le type du sentier - WATER / LAND
		if(type == "w")
			color = "#1946B9";
		else
			color = "#016838";
		
		// Create overlay on MAP
		var poly = new GPolyline(pts, color, 4, 0.8);
		GEvent.addListener(poly, "click", function(latlng) 
		{
			// Si dans tools calcul distance, ignorer event sur click et mettre un marker de distance
			if(document.getElementById("distanceDiv").style.display == "block")
				clickDistanceEvent(null, latlng);
			else{
				highlightTrail(trailIndex, true);
				createInfoWin(true, latlng, trailsList[trailIndex].province, trailsList[trailIndex].number, trailsList[trailIndex].name);
			}
		});
		map.addOverlay(poly);
				
		// Save in memory
		trailsList[trailIndex].addNewSegment(pts, type, poly);
	}
	
	// Si le sentier est Highlight on affiche la ligne en vert fluo
	if(trailsList[trailIndex].isHighlight == true)
		highlightTrail(trailIndex, false);
}


//-------------------------------------------------------------------------------------------
// Highlight selected trail when you click on a trail
// Param removeInfo = true s'il faut effacer la fenêtre infowin

function highlightTrail(trailIndex, removeInfo)
{
	resetHighlight(removeInfo);
	trailsList[highlight.trailIndex].isHighlight = false;
	trailsList[trailIndex].isHighlight = true;
	highlight.trailIndex = trailIndex;

	// Afficher tous les segments de la trail en vert fluo
	for (var s=0; s<trailsList[trailIndex].segmentArrayIndex; s++)
	{
		var poly = new GPolyline(trailsList[trailIndex].segmentArray[s].points,"#10F035", 4, 0.8);
		highlight.addNewOverlay(poly);
		map.addOverlay(poly);
	}
}


//-------------------------------------------------------------------------------------------
// Reset Highlight and remove fluo green line
// Param removeInfo = true s'il faut effacer la fenêtre infowin

function resetHighlight(removeInfo)
{
	if(removeInfo == true)
		removeInfoWin();	// Remove Info Windows
	
	// Remove all Highlight trail
	for (var o=0; o<highlight.overlayIndex; o++)
	{
		map.removeOverlay(highlight.overlay[o]);
		highlight.overlay[o] = null;
	}
	highlight.overlayIndex = 0;
	highlight.overlay.length = 0;
}


//-------------------------------------------------------------------------------------------
// Highlight selected trail when you select a trail form select list

function highlightOnSelect(trailIndex, trailCenter)
{	
	// Si la trail est déjà sur la MAP on déclenche l'affichage
	if(trailsList[trailIndex].isMapped)
		highlightTrail(trailIndex, true);
		
	// Sinon on paramètre les données et il sera automatiquement 
	// affiché lors de l'appel de fonction addTrailOverlay
	else
	{
		resetHighlight(true);
		trailsList[highlight.trailIndex].isHighlight = false;
		trailsList[trailIndex].isHighlight = true;
	}
	
	// Ouvrir une fenetre d'information sur le sentier
	createInfoWin(false, trailCenter, trailsList[trailIndex].province, trailsList[trailIndex].number, trailsList[trailIndex].name);
}

