

/*******************************************************************************************/
/* DEBUT CONSTANTES																																					 */
/*******************************************************************************************/
var CtrlTable = {
  'GOverviewMapControl': true,
  'GLargeMapControl': true,
  'GSmallMapControl': true,
  'GSmallZoomControl': true,
  'GSmallMapTypeControl': true,
  'GMapTypeControl': true,
  'GMenuMapTypeControl': true,
  'GHierarchicalMapTypeControl': true,
  'GScaleControl': true
};

var MapTypeTable = {
  'G_NORMAL_MAP' : null,
  'G_SATELLITE_MAP' : null,
  'G_HYBRID_MAP' : null,
  'G_PHYSICAL_MAP' : null,
  'G_MAP_TYPE' : 'G_NORMAL_MAP',
  'G_SATELLITE_TYPE' : 'G_SATELLITE_MAP',
  'G_HYBRID_TYPE' : 'G_HYBRID_MAP'
};


var theEZMap;
var startMarker;
var endMarker;
var pointViaArray = [];

var startdate = new Date();

// Polyline enlighted
var enlightedPolyline = -1;
var toptripselected = false;

// configuration -- if you're using your own copy of gmapez.js, you
// may want to modify these:
var overlaysPerStep = 25;

var MiniIcon = new GIcon();
MiniIcon.shadow = "/static/images/maps/mm_20_shadow.png";
MiniIcon.iconSize = new GSize(12, 20);
MiniIcon.shadowSize = new GSize(22, 20);
MiniIcon.iconAnchor = new GPoint(6, 20);
MiniIcon.infoWindowAnchor = new GPoint(5, 1);

G_DEFAULT_ICON.transparent = null;

var baseIcon = new GIcon();
baseIcon.iconSize=new GSize(18,22);
baseIcon.shadowSize=new GSize(20,22);
baseIcon.iconAnchor=new GPoint(6,20);
baseIcon.infoWindowAnchor=new GPoint(5,1);
//var departureIcon = new GIcon(baseIcon, '/static/images/maps/marker-GREEN-START.png', null, '/static/images/maps/mm_20_shadow.png');
//var arrivalIcon = new GIcon(baseIcon, '/static/images/maps/marker-GREEN-END.png', null, '/static/images/maps/mm_20_shadow.png');
var maleIcon = new GIcon(baseIcon, '/static/images/maps/man-icon.png', null, '/static/images/maps/mm_20_shadow.png');
var femaleIcon = new GIcon(baseIcon, '/static/images/maps/woman-icon.png', null, '/static/images/maps/mm_20_shadow.png');


var circleIcon = new GIcon();
circleIcon.iconSize=new GSize(16,16);
circleIcon.iconAnchor=new GPoint(8,8);
circleIcon.infoWindowAnchor=new GPoint(10,0);
var greenIcon = (new GIcon(circleIcon, "/static/images/maps/greenCircle.png", null, ""));
var orangeIcon = (new GIcon(circleIcon, "/static/images/maps/orangeCircle.png", null, ""));
var whiteIcon = (new GIcon(circleIcon, "/static/images/maps/whiteCircle.png", null, ""));


/*******************************************************************************************/
/* FIN CONSTANTES																																					 */
/*******************************************************************************************/

/*******************************************************************************************/
/* LES FONCTIONS	DANS L 'ORDRE D'EXECUTION																																			 */
/*******************************************************************************************/

var laterFuncs = [];
var lastFunc = null;
	
function doNow() {
	if( laterFuncs.length > 0 ) {
		laterFuncs.shift().call();
		setTimeout( doNow, 1 );
	}
	else {
		if( lastFunc ) {
		  lastFunc.call();
		}
	}
}
function doLater( obj, func ) {
	laterFuncs.push( function() { func.call( obj ); } );
}

/*******************************************************************************************/
/* DEBUT FONCTIONS																																					 */
/*******************************************************************************************/

// Tableau de l'ensemble des markers.
var idmarkers = {};

function markerForUrl( url ) {
  var matcha = /#(.*)/.exec( url );

  if( matcha )
	return idmarkers[ matcha[ 1 ] ];
  else
	return null;
}

// generate Id des infomarker
var _lastId = 0;
function newId() {
	return 'ez_' + (++_lastId);
}

function getTotalOffset( elem ) {
  point = new GPoint( 0, 0 );
  while( elem ) {
	point.x += elem.offsetLeft;
	point.y += elem.offsetTop;
	//alert( elem.offsetTop + ' = ' + point.y );
	elem = elem.offsetParent;
  }
  return point;
}

// Debut Fonctions de parsing
function wordMap( str ) {
  var wmap = {};
  var list = str.split(' ');
  for( var j = 0; j < list.length; ++j ) {
	wmap[ list[ j ] ] = true;
  }
  return wmap;
}
function parseParams( str, params ) {
  var matchparam;
  for( var word in wordMap( str ) ) {
	matchparam = /^(\w+):(.*)$/.exec( word );
	if( matchparam && matchparam[1] in params ) {
	  params[ matchparam[1] ] = matchparam[2];
	}
  }
  return params;
}
// Fin Fonctions de parsing
	
	/*******************************************************************************************/
	// For this event handler, "this" is the clicked anchor
	// Gestion des clicks/mouseover sur les trajets de la liste
	// Gestion des clicks sur la carte
	/******************************************************************************************/	
		
/*		
function Timer()
{
	// dans le cas d un trip detail, on doit cacher la map a la fin de l initialisation, on place ici le bordel car bug IE
	  if($("#comuto_GMAP").length) 
	  {
		var mydivs = document.getElementsByTagName( 'div' );
	    for( var mi = 0; mi < mydivs.length; ++mi ) {
		  	if (mydivs[ mi ].className == "comuto_GMAP_CONTAINER") 
			{
				mydivs[ mi ].style.display = 'none';
			}
	    }
	  }
}
*/
// Draw the trip polyline
function polylineOut()
{
	this.style.background="#fff";
	this.style.color="#6975c1";
	var markerFROM = markerForUrl( this.id + "FROM");
	if (enlightedPolyline != -1) markerFROM.ezmap.map.removeOverlay(enlightedPolyline);
}
  
  
function polylineOver() 
{	
  this.style.background="#009947";
  this.style.color="#fff";
  
  var markerFROM = markerForUrl( this.id + "FROM");
  var markerTO = markerForUrl( this.id + "TO" );
 
  if( markerFROM && markerTO ) {
  
	  if( /\bZOOM\b/.exec( this.className ) ) {
		var mapType = markerFROM.mapType || markerFROM.ezmap.map.getCurrentMapType();
		var zoomLevel;
		if( markerFROM.span ) {
		  zoomLevel = mapType.getSpanZoomLevel(
			markerFROM.point, markerFROM.span, markerFROM.ezmap.viewsize );
		}
		else {
		  zoomLevel = markerFROM.ezmap.map.getZoom();
		}
		markerFROM.ezmap.map.setCenter( marker.point, zoomLevel, mapType );
	  }
	
	var points = new Array();
  
	points.push(markerTO.point);
	points.push(markerFROM.point);
	
	if (enlightedPolyline != -1) markerFROM.ezmap.map.removeOverlay(enlightedPolyline);
	var params = parseParams( this.name, { color: null, weight: null, opacity: null } );
	enlightedPolyline = new GPolyline(points, params.color, params.weight, params.opacity);

	markerFROM.ezmap.map.addOverlay(enlightedPolyline);
	
// marker.doOpen();
	return false;
	}
	else {
	  return true;
	}

}
	
function toptripClick()
{
	var id=this.id.substring(this.id.lastIndexOf('#')+1);
	
	var fromcity 		= $('#comuto_FROMCITY_'+id).val();
	var fromcity_id 	= $('#comuto_FROMCITYID_'+id).val();
	var tocity 			= $('#comuto_TOCITY_'+id).val();
	var tocity_id 		= $('#comuto_TOCITYID_'+id).val();
	
	document.body.style.cursor = "wait";
	this.style.cursor = "wait";
	
	theEZMap.map.getDragObject().setDraggableCursor("wait");
	
	var anchors = document.getElementsByTagName( 'a' );
	for( var mi = 0; mi < anchors.length; ++mi ) {
		if (anchors[ mi ].className == "comuto_TOPTRIPLINK") 
		{
			anchors[ mi ].style.cursor = "wait";
		}
	}	
	
	
	$.ajax({
		url:  '/api/ajax_mapTrips.php',
		type: 'POST',
		data: {
			"TYPETRIP":5,
			"SEARCH_FROMCITY_ID": fromcity_id,
			"SEARCH_TOCITY_ID": tocity_id,
			"SEARCH_FROMCITY": fromcity,
			"SEARCH_TOCITY": tocity
		},
		timeout: 20000,
		dataType: 'xml',
		error: function(){
				document.body.style.cursor = "default";
				theEZMap.map.getDragObject().setDraggableCursor("default");

				alert('Error loading XML document');
			},
		success: function(xml){
			
			theEZMap.removeOverlays();
			$("#comuto_GMAP").html($(xml).find('contentmap').text());
			$("#comuto_MAPTRIPLISTINSIDE").html($(xml).find('contentright').text());
			$("#comuto_MAPTITLE").html($(xml).find('contentrighttitle').text());
			$("#comuto_pagination_map").html($(xml).find('contentpagination').text());
			
			document.body.style.cursor = "default";
			theEZMap.map.getDragObject().setDraggableCursor("default");

			loadfuncWithMarkers(theEZMap.departureMarker, theEZMap.arrivalMarker);		
		}
	});
	
}	
	
// open the info window
function tripClick() 
{
    var marker = markerForUrl( this.href);
  
    if( marker ) {
      if( /\bZOOM\b/.exec( this.className ) ) {
        var mapType = marker.mapType || marker.ezmap.map.getCurrentMapType();
        var zoomLevel;
        if( marker.span ) {
          zoomLevel = mapType.getSpanZoomLevel(
            marker.point, marker.span, marker.ezmap.viewsize );
        }
        else {
          zoomLevel = marker.ezmap.map.getZoom();
        }
        marker.ezmap.map.setCenter( marker.point, zoomLevel, mapType );
      }
	
	  marker.doOpen();
      return false;
    }
    else {
      return true;
    }
}
	/*******************************************************************************************/
	// GESTION DES PATH ENTRE 2 POINTS
	/******************************************************************************************/	
	
function addDepartureMarker(point, ezmap)
{
	ezmap.departureMarker = new GMarker(point,{icon:greenIcon,draggable:true,bouncy:false});	
}

function addArrivalMarker(point, ezmap)
{
	ezmap.arrivalMarker = new GMarker(point,{icon:orangeIcon,draggable:true,bouncy:false});
}


function addViaMarker(point, ezmap)
{
	ezmap.viaMarker.push(new GMarker(point,{icon:whiteIcon,draggable:true,bouncy:false}));
	
}

function addPathForTripBloc(ezmap)
{
	var addressfromlat 	= $("#comuto_ADDRESSFROMLAT").val();
	var addressfromlon 	= $("#comuto_ADDRESSFROMLON").val();
	var addresstolat 	= $("#comuto_ADDRESSTOLAT").val();
	var addresstolon 	= $("#comuto_ADDRESSTOLON").val();
	
	var pointDepart = new GLatLng(addressfromlat, addressfromlon);
	var pointArrivee = new GLatLng(addresstolat, addresstolon);

	addDepartureMarker(pointDepart, ezmap);
	addArrivalMarker(pointArrivee, ezmap);
	
	
	var nbViacities = parseInt($('#comuto_NBVIACITIES').val()) + 1;
	
	if ($('#comuto_NBVIACITIES').length)
	{
		for(i = 0; i < nbViacities; i++)
		{
			var addressvialat 	= $("#comuto_ADDRESSVIALAT"+i).val();
			var addressvialon 	= $("#comuto_ADDRESSVIALON"+i).val();
			
			var pointVia = new GLatLng(addressvialat, addressvialon);
			pointViaArray.push(pointVia);
			addViaMarker(pointVia, ezmap);
		}
	}

}

function setMapUrl(ezmap)
{
	
	var centerLat = ezmap.map.getCenter().lat();
	var centerLng = ezmap.map.getCenter().lng();
	var zoomLevel = ezmap.map.getZoom();
	
	var urlMap = "http://maps.google.fr/?ie=UTF8&ll="+centerLat+","+centerLng+"&spn="+ezmap.map.getBounds().toSpan().toUrlValue(5)+"&z="+zoomLevel;
	
	if (urlMap != $("#comuto_EXTENT").attr('href'))
	{
		$("#comuto_EXTENT").attr('href', urlMap);
	
		$.ajax({
				url:  '/api/ajax_setMapParameter.php',
				type: 'POST',
				data: {
					"GMAPURL": urlMap
				},
				timeout: 3000,
				error: function(){
					//	alert('Error loading XML document in setMapUrl');
					},
				success: function(){
					}
			});
	}

}


// ici this represente la map
function clickOnMap(overlay, point, ezmap)
{
  if( overlay && overlay.doOpen ) 
  {
    overlay.doOpen();
  }
  else if ( $("#comuto_DIRECTION").val() == 1)
  {
	if( point ) 
	{
	    ezmap.map.closeInfoWindow();
		if (!ezmap.departureMarker) {
			addDepartureMarker(point, ezmap);
			ezmap.map.addOverlay(ezmap.departureMarker);
		}
		else if (!ezmap.arrivalMarker) {
		
			addArrivalMarker(point, ezmap);
			ezmap.map.addOverlay(ezmap.arrivalMarker);
		
			var fromlat = ezmap.departureMarker.getPoint().lat();
			var fromlon = ezmap.departureMarker.getPoint().lng();
				
			var tolat = ezmap.arrivalMarker.getPoint().lat();
			var tolon = ezmap.arrivalMarker.getPoint().lng();
			ezmap.GDir.loadFromWaypoints([ezmap.departureMarker.getPoint(),ezmap.arrivalMarker.getPoint()],{getPolyline:true,preserveViewport :false});

			document.body.style.cursor = "wait";
			ezmap.map.getDragObject().setDraggableCursor("wait");

			// hack debile pour virer les icones A et B
			GEvent.addListener( ezmap.GDir, 'load', function(){
				var markerDepart = ezmap.GDir.getMarker(0);
		        var markerArrivee = ezmap.GDir.getMarker(1);
		        setTimeout(function() {markerDepart.setImage("")},0);
				setTimeout(function() {markerArrivee.setImage("")},0);
			});
				
			$.ajax({
				url:  '/api/ajax_mapTrips.php',
				type: 'POST',
				data: {
					"TYPETRIP":8,
					"TOLAT": tolat,
					"TOLON": tolon,
					"FROMLAT": fromlat,
					"FROMLON": fromlon
				},
				timeout: 20000,
				dataType: 'xml',
				error: function(){
						document.body.style.cursor = "default";
						ezmap.map.getDragObject().setDraggableCursor("default");

						alert('Error loading XML document');
					},
				success: function(xml){
					
					ezmap.removeOverlays();
					$("#comuto_GMAP").html($(xml).find('contentmap').text());
					$("#comuto_MAPTRIPLISTINSIDE").html($(xml).find('contentright').text());
					$("#comuto_MAPTITLE").html($(xml).find('contentrighttitle').text());
					$("#comuto_pagination_map").html($(xml).find('contentpagination').text());
					
					document.body.style.cursor = "default";
					ezmap.map.getDragObject().setDraggableCursor("default");

					loadfuncWithMarkers(ezmap.departureMarker, ezmap.arrivalMarker);		
				}
			});
			
			
		
			  
		} else {
			ezmap.map.removeOverlay(ezmap.departureMarker);
			ezmap.map.removeOverlay(ezmap.arrivalMarker);
			
			ezmap.GDir.clear();
			
			ezmap.departureMarker = null;
			ezmap.arrivalMarker = null;

			ezmap.departureMarker = new GMarker(point,{icon:greenIcon,draggable:true,bouncy:false});	
			ezmap.map.addOverlay(ezmap.departureMarker);

				
		}
	}
  }
  return;	
}


/*******************************************************************************************/
/* FIN FONCTIONS																																					 */
/*******************************************************************************************/

/*******************************************************************************************/
/* LES OBJETS GMAP																																				 */
/*******************************************************************************************/

	/********************************/
	/* 		EZMarker    		*/
	/********************************/
	
    function EZInfoMarker( ezmap ) {
      this.ezmap = ezmap;
      this.icon = G_DEFAULT_ICON;

      this.point = null;
      this.title = null;

      this.blowup = false;
      this.tabs = [];

      this.infoZoomOffset = undefined;
      this.infoZoomLevel = undefined;
      this.infoMapType = null;
    }
	
    EZInfoMarker.prototype = new GMarker( new GLatLng( 0, 0 ) );
    EZInfoMarker.prototype.constructor = EZInfoMarker;

    EZInfoMarker.prototype.initialize = function( map ) {
      GMarker.call(
          this,
          this.point,
          {
            icon: this.icon,
            clickable: ( this.tabs.length > 0 || this.blowup ),
            title: this.title
          });
      GMarker.prototype.initialize.call( this, map );
    };

    EZInfoMarker.prototype.doOpen = function( autoopen ) {
      if( ! autoopen ) {
        var body = document.body || document.getElementsByTagName('body')[0];
        if( 'scrollLeft' in body ) {
          // http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
          var myWidth = 0, myHeight = 0;
          if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
          } else if( document.documentElement &&
              ( document.documentElement.clientWidth ||
              document.documentElement.clientHeight ) )
          {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
          } else if( document.body &&
              ( document.body.clientWidth || document.body.clientHeight ) )
          {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
          }

          var mapdiv = this.ezmap.div;
          var totalOffset = getTotalOffset( mapdiv );
          if( totalOffset.x < body.scrollLeft ||
              totalOffset.x + mapdiv.offsetWidth > body.scrollLeft+myWidth ||
              totalOffset.y < body.scrollTop ||
              totalOffset.y + mapdiv.offsetHeight > body.scrollTop+myHeight)
          {
            //alert( totalOffset.x + ', ' + totalOffset.y );
            scrollTo( totalOffset.x, totalOffset.y );
          }
        }
      }

      var zoom = null;
      if( this.tabs.length > 0 ) {
        var opts = { maxWidth: this.ezmap.div.offsetWidth - 100 };
        if( this.icon ) {
          this.openInfoWindowTabs( this.tabs, opts );
        }
        else {
          // "INVISIBLE" markers are never added as overlays -- GMap2
          // knows nothing about them.
          this.ezmap.map.openInfoWindowTabs( this.point, this.tabs, opts );
        }
        for( var i = 0; i < this.tabs.length; ++i ) {
          this.setupInfoForm( this.tabs[ i ] );
        }
      }
      else if( this.blowup ) {
        if( this.infoZoomOffset != undefined )
          zoom = this.ezmap.map.getZoom() + this.infoZoomOffset;
        else if( this.infoZoomLevel != undefined )
          zoom = this.infoZoomLevel;

        if( zoom >= this.ezmap.map.getCurrentMapType().numZoomLevels )
          zoom = this.ezmap.map.getCurrentMapType().numZoomLevels - 1;
        else if( zoom < 0 )
          zoom = 0;

        this.showMapBlowup( { zoomLevel: zoom, mapType: this.infoMapType } );
      }
      else {
        this.ezmap.map.closeInfoWindow();
      }
    };

    EZInfoMarker.prototype.setupInfoForm = function( tab ) {
      var div, a;
      var tabElem = tab.contentElem;
      var classes = tabElem.className ? wordMap( tabElem.className ) : {};
      if( classes.DirectionsToHere ||
          classes.DirectionsFromHere ||
          classes.SearchNearby )
      {
        if( tab.infoFormId ) {
          div = document.getElementById( tab.infoFormId );
          div.innerHTML = '';
        }
        else {
          div = document.createElement('div');
          div.className = 'ez_infoForm';
          tab.infoFormId = div.id = newId();
          tabElem.appendChild( div );
        }
        var _this = this;
        if( classes.DirectionsToHere || classes.DirectionsFromHere ) {
          div.appendChild( document.createTextNode( 'Get directions: ' ) );
          if( classes.DirectionsToHere ) {
            a = document.createElement('a');
            a.innerHTML = 'To here';
            a.onclick = function() { _this.showForm( tab ); };
            a.href = 'javascript:void(null)';
            div.appendChild( a );
          }
          if( classes.DirectionsToHere && classes.DirectionsFromHere ) {
            div.appendChild( document.createTextNode( ' - ' ) );
          }
          if( classes.DirectionsFromHere ) {
            a = document.createElement('a');
            a.innerHTML = 'From here';
            a.onclick = function() {};
            a.href = 'javascript:void(null)';
            div.appendChild( a );
          }
          div.appendChild( document.createElement('br') );
        }
        if( classes.SearchNearby ) {
          a = document.createElement('a');
          a.innerHTML = 'Search nearby';
          a.onclick = function() {};
          a.href = 'javascript:void(null)';
          div.appendChild( a );
        }
      }
    };

    EZInfoMarker.prototype.showForm = function( tab ) {
      var div = document.getElementById( tab.infoFormId );
      div.innerHTML = '<b>Get directions:</b> To here - ';
      var a = document.createElement('a');
      a.innerHTML = 'From here';
      a.onclick = function() {};
      a.href = 'javascript:void(null)';
      div.appendChild( a );
      var x = document.createElement('div');
      x.innerHTML = 'Start address';
      div.appendChild( x );
      this.ezmap.map.getInfoWindow().reset();
    };


	/********************************/
	/* 		EZLine 			*/
	/********************************/
	
    function EZPolyline( color, weight, opacity ) {
      this.points = [];
      this.initialize = function( map ) {
        GPolyline.call( this, this.points, color, weight, opacity );
        GPolyline.prototype.initialize.call( this, map );
      };
    };
    EZPolyline.prototype = new GPolyline();
    EZPolyline.prototype.constructor = EZPolyline;

	/********************************/
	/* 		EZMap 			*/
	/********************************/
	
    function EZMap( div, classes ) {
      this.div = div;
      this.classes = classes;
	  this.initDone = 0;
      this.divData = null;

      this.map = undefined;
      this.viewsize = null;
      this.extentMarker = null;

      this.overlayList = [];
	  this.polylineList = [];
      
	  this.GDir = null;
	  this.departureMarker = null;
      this.arrivalMarker = null;
	  this.viaMarker = [];
	  
      this.stateDepartureArrival = 0;

      this.loading = null;
      this.bar = null;
      this.maxstep = 0;
      this.step = 0;
      this.oi = 0;
	  
	  
	  this.initFrame();
	  
	  
    }

    EZMap.prototype.logWarning = function( str ) {
      if( ! this.warningNode ) {
        this.warningVis = false;
        this.warningNode = document.createElement('ul');
        this.warningNode.className = 'warnings';
        this.div.appendChild( this.warningNode );

        var warnBtn = document.createElement('button');
        warnBtn.className = 'warnings';
        warnBtn.innerHTML = 'Warnings...';
        this.div.appendChild( warnBtn );
        var ezmap = this;
        warnBtn.onclick = function() { ezmap.toggleWarnings(); };
      }
      var li = document.createElement('li');
      li.innerHTML = str;
      this.warningNode.appendChild( li );
    };

    EZMap.prototype.toggleWarnings = function() {
      this.warningVis = ! this.warningVis;
      this.warningNode.style.display = this.warningVis ? 'block' : 'none';
    };

    EZMap.prototype.processMarkers = function( parentNode, polyline ) {
      var customIcon = new GIcon(baseIcon, $("#comuto_MAPICON").val(), null, '/static/images/maps/mm_20_shadow.png');

	  var lastOverlay, marker, textContent, imgs;
      var matchll, matchspn, matchtype;
      for( var node = parentNode.firstChild; node; node = node.nextSibling){
        lastOverlay = this.overlayList[ this.overlayList.length - 1 ];
        switch( node.nodeName ) {
		case 'INPUT':
			if (node.id == "comuto_detailMap")
			{
				addPathForTripBloc(this);
			}
		break;
        case 'A':
          matchll = /\Wll=([-.\d]*),([-.\d]*)/.exec( node.href );
          if( matchll ) {
		  
			var _lat = parseFloat(matchll[1]);
			var _lon = parseFloat(matchll[2]);

	        textContent = node.innerHTML.replace( /<[^>]*>/g, '' );
			
			if( /\bDEPART\b/.exec( textContent )) {
				var pointDepart = new GLatLng(_lat, _lon);
				addDepartureMarker(pointDepart, this);	
			}
			else if (/\bARRIVEE\b/.exec( textContent ))
			{
				var pointArrivee = new GLatLng(_lat, _lon);
				addArrivalMarker(pointArrivee, this);
			}
			else
			{
	            marker = new EZInfoMarker( this );
	            marker.title = node.getAttribute('title');
	            this.overlayList.push( marker );

	            if( node.id || node.name )	idmarkers[ node.id || node.name ] = marker;

	            if( /\bINVISIBLE\b/.exec( textContent ) ) {
	              marker.icon = null;
	            }

				if( /\bCUSTOM\b/.exec( textContent ) ) {
					
					//Récupération d'un éventuel picto spécifique
					for( var nodeimg = node.firstChild; nodeimg; nodeimg = nodeimg.nextSibling){
						if(nodeimg.nodeName=='IMG' && nodeimg.src){
							customIcon = new GIcon(baseIcon, nodeimg.src, null, null);
							break;
						}
					}
					marker.icon = customIcon;
	            }
				
				if( /\bMAN\b/.exec( textContent ) ) {
	              marker.icon = maleIcon;
	            }
				if( /\bFEMALE\b/.exec( textContent ) ) {
	              marker.icon = femaleIcon;
	            }
	            marker.point = new GLatLng(_lat, _lon);

	            if( polyline ) {
	              marker.icon = null;
	              polyline.points.push( marker.point );
	            }
			}

          }
          else {
            this.logWarning( "No ll param for marker [" + node.innerHTML +
              ":" + (node.id || node.name) + "]" );
          }
          break;

        case 'DIV':
          if( ! lastOverlay ) {
            this.logWarning( "div block given before any markers" );
            continue;
          }
          else {
            var infoClasses = wordMap( node.className );
            if( 'GMapEZ' in infoClasses ) {
              // infoWindow blowup
              // XXX replace this with a nested map to allow for use
              // in tabs?
              lastOverlay.blowup = true;
              var matchzoom = /ZOOMLEVEL([-+=]?)(\d+)/.exec( node.innerHTML );
              if( matchzoom ) {
                var num = parseInt( matchzoom[ 2 ] );
                if( matchzoom[ 1 ] == '-' )
                  lastOverlay.infoZoomOffset = num;
                else if( matchzoom[ 1 ] == '+' )
                  lastOverlay.infoZoomOffset = - num;
                else
                  lastOverlay.infoZoomLevel = num;
              }

              for( typeName in MapTypeTable ) {
                if( typeName in infoClasses ) {
                  if( MapTypeTable[ typeName ] ) {
                    lastOverlay.infoMapType = window[ MapTypeTable[ typeName ] ];
                  }
                  else {
                    lastOverlay.infoMapType = window[ typeName ];
                  }
                  break;
                }
              }
            }
            else {
              // XXX remove title attribute from div node?
              lastOverlay.tabs.push(
                  new GInfoWindowTab( node.getAttribute('title'), node ));
            }
          }
          break;

        case 'LI':
          this.processMarkers( node, polyline );
          break;

        case 'OL':
          var params = parseParams( node.className,
              { color: null, weight: null, opacity: null } );
          if( params.color && ! /^#[0-9a-zA-Z]{6}$/.exec( params.color ) )
            this.logWarning( 'Polyline color should be a 6-digit' +
                ' hex color like "#123abc", not "' + params.color + '"' );
          if( params.weight != null ) {
            var w = parseInt( params.weight );
            if( w < 1 || isNaN( w ) )
              this.logWarning( 'Polyline weight should be an' +
                  ' interger above 0, not "' + params.weight + '"' );
            params.weight = w;
          }
          if( params.opacity ) {
            var o = parseFloat( params.opacity );
            if( o < 0 || o > 1 || isNaN( o ) )
              this.logWarning( 'Polyline opacity should be ' +
                  ' between 0 and 1, not "' + params.opacity + '"' );
            params.opacity = o;
          }
          var newline = new EZPolyline(
              params.color,
              params.weight,
              params.opacity );
          this.overlayList.push( newline );
	//	  this.polylineList.push( newline );
          this.processMarkers( node, newline );
          break;

        case '#text':
        case '#comment':
          // ignore text and comments
          break;

        default:
          this.logWarning( "Unknown or misplaced node " + node.nodeName );
          break;
        }
      }
    };

	/* les points verts et oranges */
    EZMap.prototype.onClick = function( overlay, point ) 
    {
        clickOnMap(overlay, point, this);
    };
	EZMap.prototype.onMove = function() 
    {
		setMapUrl(this);
	};
	EZMap.prototype.onZoom = function() 
    {
		setMapUrl(this);
		
		if (this.initDone == 1 && ($("#comuto_CURRENTTYPETRIP").val() == 2  || $("#comuto_CURRENTTYPETRIP").val() == 1))
		{
			var bounds = this.map.getBounds();
			var bound_sw = bounds.getSouthWest();
			var bound_ne = bounds.getNorthEast();
			
			var latmin = bound_sw.lat();
			var lonmin = bound_sw.lng();
			var latmax = bound_ne.lat();
			var lonmax = bound_ne.lng();

			document.body.style.cursor = "wait";
			theEZMap.map.getDragObject().setDraggableCursor("wait");
	
			$.ajax({
				url:  '/api/ajax_mapTrips.php',
				type: 'POST',
				data: {
					"TYPETRIP": $("#comuto_CURRENTTYPETRIP").val(),
					"latmin": latmin,
					"lonmin": lonmin,
					"latmax": latmax,
					"lonmax": lonmax
				},
				timeout: 20000,
				dataType: 'xml',
				error: function(){
						alert('Error loading XML document');
					},
				success: function(xml){	
					theEZMap.removeOverlays();
					$("#comuto_GMAP").html($(xml).find('contentmap').text());
					$("#comuto_MAPTRIPLISTINSIDE").html($(xml).find('contentright').text());
					$("#comuto_MAPTITLE").html($(xml).find('contentrighttitle').text());
					$("#comuto_pagination_map").html($(xml).find('contentpagination').text());
		
					document.body.style.cursor = "default";
					theEZMap.map.getDragObject().setDraggableCursor("default");

					loadfunc();	
					
				}
			});
		}
		this.initDone = 1;
		
    };
    
	
	EZMap.prototype.nextStep = function( func ) {
      if( this.maxstep > 0 ) {
        this.bar.style.width = Math.round( this.step / this.maxstep * 100 ) + '%';
      }
      this.step += 1;
      doLater( this, func );
    };

    EZMap.prototype.initFrame = function() {
      this.divData = this.div;
      this.div = this.div.cloneNode( false );
      this.divData.parentNode.insertBefore( this.div, this.divData );
      this.divData.parentNode.removeChild( this.divData );
      this.div.style.visibility = 'visible';

	 
	  this.initLoadingProgress();
	  

      this.nextStep( this.initParse );
    };

	EZMap.prototype.initLoadingProgress = function() {
		this.loading = document.createElement('div');
	    this.loading.className = 'loadprogress';
	    this.loading.style.marginTop = ( this.div.offsetHeight / 3 ) + 'px';
	    this.loading.innerHTML = '<div class="box"><div class="logo"></div><div class="trough"><div class="bar"></div></div></div>';
	    this.bar = this.loading.getElementsByTagName('div')[3];
	    this.div.appendChild( this.loading );
	}
	EZMap.prototype.removeLoadingProgress = function() {
		if (this.loading && this.loading.parentNode)
		{
			this.loading.parentNode.removeChild( this.loading );
			this.loading = null;
		}
	}
	/* FONCTIONS D'INITIALISATION */

   EZMap.prototype.initParse = function() {
    
      this.processMarkers( this.divData );
	  
      this.divData = null;

      this.map = new GMap2( this.div );
      this.map.getContainer().appendChild( this.loading );
 
	  // On  ajoute  la direction
	  this.GDir = new GDirections(this.map);

	  GEvent.bind( this.map,'zoomend', this, this.onZoom );
	  GEvent.bind( this.map, 'moveend', this, this.onMove );
	  GEvent.bind( this.map, 'click', this, this.onClick );
	  
	  if ($("#comuto_EXTENT").length)
	  {
		var marker = new EZInfoMarker( this );
		_href = $("#comuto_EXTENT").attr('href');
		matchll = /\Wll=([-.\d]*),([-.\d]*)/.exec(_href);
	
		if( matchll ) {
			marker.point = new GLatLng(parseFloat( matchll[1] ), parseFloat( matchll[2] ) ); 
			marker.icon = null;
		}
		
		matchspn = /\Wspn=([-.\d]*),([-.\d]*)/.exec(_href);
		if( matchspn ) {
		  marker.span = new GLatLng(
			  parseFloat( matchspn[1] ),
			  parseFloat( matchspn[2] ) );
		}

		matchtype = /\Wt=(.)/.exec(_href);
		if( matchtype ) {
		  switch( matchtype[1] ) {
			case 'k': marker.mapType = G_SATELLITE_MAP; break;
			case 'h': marker.mapType = G_HYBRID_MAP; break;
			// XXX need a G_MAP_TYPE letter for use by ZOOM links
		  }
		}
		 
        this.extentMarker = marker;
	  }


	
  
      // map type
      var mapType = G_NORMAL_MAP;
      if( this.extentMarker && this.extentMarker.mapType ) {
        mapType = this.extentMarker.mapType;
      }
      for( typeName in MapTypeTable ) {
        if( typeName in this.classes ) {
          if( MapTypeTable[ typeName ] ) {
            mapType = window[ MapTypeTable[ typeName ] ];
          }
          else {
            mapType = window[ typeName ];
          }
          break;
        }
      }

      // center and zoom
      this.viewsize = new GSize( this.div.offsetWidth, this.div.offsetHeight );
      var center, zoomLevel;
      if( this.extentMarker ) {
        center = this.extentMarker.point;
        if( this.extentMarker.span ) {
          zoomLevel = mapType.getSpanZoomLevel(
              center, this.extentMarker.span, this.viewsize );
        }
        else {
          zoomLevel = 10;
        }
      }
      else {
        center = new GLatLng( 41.075210, -85.130310 );
        zoomLevel = 10;
      }
      // apply center, zoom, and map type
      this.map.setCenter( center, zoomLevel, mapType );
	  
      this.maxstep = Math.floor( this.overlayList.length / overlaysPerStep ) + 2;
      this.initOverlays();
    };

    EZMap.prototype.initOverlays = function() {
      var overlay;
      var steplimit = Math.min(this.overlayList.length, this.oi+overlaysPerStep);
      for( ; this.oi < steplimit; ++this.oi ) {
        overlay = this.overlayList[ this.oi ];
        if( overlay.points || overlay.icon )
          this.map.addOverlay( overlay );
        this.overlayList[ this.oi ] = null;
      }
	  
	  if (this.viaMarker.length > 0)
	  {
		for( i=0; i < this.viaMarker.length; i++ ) 
		{
			this.map.addOverlay(this.viaMarker[i]);
		}
	  }
      
	  if (this.departureMarker && this.arrivalMarker)
	  {
		
		 this.map.addOverlay(this.departureMarker);
		 this.map.addOverlay(this.arrivalMarker);
		 
		 if (this.viaMarker.length == 0) this.GDir.loadFromWaypoints([this.departureMarker.getPoint(),this.arrivalMarker.getPoint()], {getPolyline:true,preserveViewport :false});
	  
		 
		 // hack debile pour virer les icones A et B
		 /*
			GEvent.addListener( this.GDir, 'load', function(){
				var markerDepart = this.GDir.getMarker(0);
		        var markerArrivee = this.GDir.getMarker(1);
		        setTimeout(function() {markerDepart.setImage("")},0);
				setTimeout(function() {markerArrivee.setImage("")},0);
			});
			*/
	  }
	  
	  if (this.viaMarker.length > 0)  this.GDir.loadFromWaypoints(pointViaArray, {getPolyline:true,preserveViewport :false});
		
      GEvent.addListener(this.GDir,"load", function(){
        setTimeout(function() {
          for (var i=0; i <  theEZMap.GDir.getNumRoutes()+1; i++) {
             var marker =  theEZMap.GDir.getMarker(i);
	         theEZMap.map.removeOverlay(marker);
          }
        },0);
      });
	
		


	if( this.oi < this.overlayList.length )
        this.nextStep( this.initOverlays );
      else
        this.nextStep( this.initControls );
    };

	EZMap.prototype.removeOverlays = function() {
	 // this.departureMarker = null;
	 // this.arrivalMarker = null;
	  idmarkers = {};
	  enlightedPolyline = -1;
	  this.map.clearOverlays();
    };
	
	
    EZMap.prototype.initControls = function() {
      for( var ctrl in CtrlTable ) {
        if( ctrl in this.classes ) {
          this.map.addControl( new window[ ctrl ]() );
        }
      }
	  
	  this.map.disableScrollWheelZoom();
	  
      this.nextStep( this.initLoading );
    };

    EZMap.prototype.initLoading = function() {
      this.removeLoadingProgress();
	//  setTimeout("Timer()",500);
	};




/*******************************************************************************************/
/* FIN DES OBJETS  GMAP															    */
/*******************************************************************************************/

function loadfuncWithMarkers(departureMarker, arrivalMarker)
{
	// Find all anchor tags linking to GMapEZ markers
	// et on link les event selon la classe
	var anchors = document.getElementsByTagName( 'a' );
	for( var mi = 0; mi < anchors.length; ++mi ) {
	  if( ! anchors[ mi ].onclick ) {
		// les liens trips sur le cote
		if (anchors[ mi ].className == "comuto_TRIPLINK") 
		{
			anchors[ mi ].onmouseover = polylineOver;
			anchors[ mi ].onmouseout = polylineOut;
			anchors[ mi ].onclick = tripClick;
		}
	  }
	}

	// On cree les GMAPEZ
	var divs = document.getElementsByTagName( 'div' );
	for( var i = 0; i < divs.length; ++i ) {
	  var div = divs[ i ];
	  var classes = wordMap( div.className );
	  if( 'GMapEZ' in classes ) {
		// on initialize le tout
		theEZMap = new EZMap( div, classes );
	
		if (departureMarker) theEZMap.departureMarker = departureMarker;
		else theEZMap.departureMarker = null;
		if (arrivalMarker) theEZMap.arrivalMarker = arrivalMarker;
		else theEZMap.arrivalMarker = null;
	  }
	}

	doNow();
}

function loadfunc() 
{
	// Find all anchor tags linking to GMapEZ markers
	// et on link les event selon la classe
	var anchors = document.getElementsByTagName( 'a' );
	for( var mi = 0; mi < anchors.length; ++mi ) {
	  if( ! anchors[ mi ].onclick ) {
		// les liens trips sur le cote
		if (anchors[ mi ].className == "comuto_TRIPLINK") 
		{
			anchors[ mi ].onmouseover = polylineOver;
			anchors[ mi ].onmouseout = polylineOut;
			anchors[ mi ].onclick = tripClick;
		}
		if (anchors[ mi ].className == "comuto_TOPTRIPLINK") 
		{
			anchors[ mi ].onmouseover = polylineOver;
			anchors[ mi ].onmouseout = polylineOut;
			anchors[ mi ].onclick = toptripClick;
		}
	  }
	}

	// On cree les GMAPEZ
	var divs = document.getElementsByTagName( 'div' );
	for( var i = 0; i < divs.length; ++i ) {
	  var div = divs[ i ];
	  var classes = wordMap( div.className );
	  if( 'GMapEZ' in classes ) {
		// on initialize le tout
		theEZMap = new EZMap( div, classes );
	
	  }
	}

	doNow();
}



(function(){
	
  if( window.ez_preload ) {
    // we're already loaded
    return;
  }

  
  
  
  function chainWindowFunc( funcname, newfunc ) {
    var oldfunc = window[ funcname ];
    if( oldfunc ) {
      window[ funcname ] = function() { oldfunc(); newfunc(); };
    }
    else {
      window[ funcname ] = newfunc;
    }
  }

  window.addOnLoad   = function( func ) { chainWindowFunc( "onload",   func );};
  window.addOnUnload = function( func ) { chainWindowFunc( "onunload", func );};

  // Preload: On verifie que la cle fonctionne et on load
  window.ez_preload = function() {
    addOnLoad( loadfunc );
    addOnUnload( GUnload );
  }

  //  on preload la carte
  document.write( [
    '<script type="text/javascript">',
    '  ez_preload();',
    '</script>',
  ].join('\n'));
})();

