 var map;
 var geoCodeur;


/*   // GOOGLE MAP V2   */
  function initialize() 
  {

	
		if(GBrowserIsCompatible()) 
		{
		
			map = new GMap2(document.getElementById('myMap'));
			
			map.addControl(new GMapTypeControl( false ));
			
			/* On supprime les types de base */
			map.removeMapType(G_NORMAL_MAP);
			map.removeMapType(G_SATELLITE_MAP);
			map.removeMapType(G_HYBRID_MAP);
			
			
			
			/*Front*/
			// if ( isFront )
				// createMapParameters(); 
			// else
			
			 // {/*Back*/
					
					/* On definit le type initial de la map */
					map.setMapType(  initTypeMap );
					map.setCenter(new google.maps.LatLng(  initLat,  initLng ), initZoom);
					
					
					/* On definit le centre et l'inclinaison si on est dans gearth */
					if ( initTypeMap == G_SATELLITE_3D_MAP )
					{
						
						map.getEarthInstance( function(ge) 
						{
							ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS , true);
							ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS , true);	
							var lookAt = ge.createLookAt('');
							
							lookAt.set( initLat,initLng, 10, ge.ALTITUDE_RELATIVE_TO_GROUND, 20, earthAngle,  (initZoom*500));
							ge.getView().setAbstractView(lookAt);  

						});
		
					}
				
						
					
					/* On ajoute les differents types de map */
					for  ( var i=0; i< allTypes.length; i++ )
					{
						map.addMapType( getMapType ( allTypes[i] ) );
					}
					
					/*On definit la position du zoom */
					switch ( zoomPosition ) 
					{
						case "Righ" : 
							if ( initTypeMap == G_SATELLITE_3D_MAP )
							{
								map.getEarthInstance( function(ge) 
								{
									ge.getNavigationControl().getScreenXY().setXUnits(ge.UNITS_INSET_PIXELS);
									ge.getNavigationControl().getScreenXY().setYUnits(ge.UNITS_INSET_PIXELS);
								});
							}
							else
								map.addControl(new GLargeMapControl(),  new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20,40)) );
						break;
						
						default :
							map.addControl(new GLargeMapControl());
						break;
					}
					
					


			// }
			
		
			
			geoCodeur = new GClientGeocoder();
			map.enableScrollWheelZoom();
			map.enableContinuousZoom(); 

			

		}

  }
  
  
function getMapType ( mapType )
{
	switch ( mapType  )
	{	
	
		case "G_NORMAL_MAP" :
			return G_NORMAL_MAP;
		break;
		
		case "G_SATELLITE_MAP" :
			 return G_SATELLITE_MAP ;
		break;
		
		case "G_AERIAL_MAP" :
			 return G_AERIAL_MAP ;
		break;
		
		case "G_HYBRID_MAP" :
			 return G_HYBRID_MAP ;
		break;
		
		case "G_AERIAL_HYBRID_MAP" :
			 return G_AERIAL_HYBRID_MAP ;
		break;
		
		case "G_PHYSICAL_MAP" :
			 return G_PHYSICAL_MAP ;
		break;
		
		case "G_MAPMAKER_NORMAL_MAP" :
			 return G_MAPMAKER_NORMAL_MAP;
		break;
		
		case "G_MAPMAKER_HYBRID_MAP" :
			 return G_MAPMAKER_HYBRID_MAP;
		break;
		
		case "G_MOON_ELEVATION_MAP" :
			 return G_MOON_ELEVATION_MAP ;
		break;
		
		case "G_MOON_VISIBLE_MAP" :
			 return G_MOON_VISIBLE_MAP ;
		break;
		
		case "G_MARS_ELEVATION_MAP" :
			 return G_MARS_ELEVATION_MAP ;
		break;
		
		case "G_MARS_VISIBLE_MAP" :
			 return G_MARS_VISIBLE_MAP ;
		break;
		
		case "G_MARS_INFRARED_MAP" :
			 return G_MARS_INFRARED_MAP ;
		break;
		
		case "G_SKY_VISIBLE_MAP" :
			 return G_SKY_VISIBLE_MAP ;
		break;
		
		case "G_SATELLITE_3D_MAP" :
			 return G_SATELLITE_3D_MAP ;
		break;
		
	/* 	case "G_DEFAULT_MAP_TYPES" :
			 return G_DEFAULT_MAP_TYPES;
		break;
		
		case "G_MAPMAKER_MAP_TYPES" :
			 return G_MAPMAKER_MAP_TYPES;
		break;
		
		case "G_MOON_MAP_TYPES" :
			 return G_MOON_MAP_TYPES ;
		break;
		
		case "G_MARS_MAP_TYPES" :
			 return G_MARS_MAP_TYPES;
		break;	
		
		case "G_SKY_MAP_TYPES" :
			 return G_SKY_MAP_TYPES ;
		break; */
		
		/******************************************************************************************
		
		
								RAJOUTER TOUS LES TYPES
		
		
		
		******************************************************************************************/
	}

} 

function getMapTypeString ( mapType )
{
	switch ( mapType  )
	{	
	
		case G_NORMAL_MAP :
			return "G_NORMAL_MAP";
		break;
		
		case G_SATELLITE_MAP :
			 return "G_SATELLITE_MAP" ;
		break;
		
		case G_AERIAL_MAP :
			 return "G_AERIAL_MAP" ;
		break;
		
		case G_HYBRID_MAP :
			 return "G_HYBRID_MAP" ;
		break;
		
		case G_AERIAL_HYBRID_MAP :
			 return "G_AERIAL_HYBRID_MAP" ;
		break;
		
		case G_PHYSICAL_MAP :
			 return "G_PHYSICAL_MAP" ;
		break;
		
		case G_MAPMAKER_NORMAL_MAP :
			 return "G_MAPMAKER_NORMAL_MAP";
		break;
		
		case G_MAPMAKER_HYBRID_MAP :
			 return "G_MAPMAKER_HYBRID_MAP";
		break;
		
		case G_MOON_ELEVATION_MAP :
			 return "G_MOON_ELEVATION_MAP" ;
		break;
		
		case G_MOON_VISIBLE_MAP :
			 return "G_MOON_VISIBLE_MAP" ;
		break;
		
		case G_MARS_ELEVATION_MAP :
			 return "G_MARS_ELEVATION_MAP" ;
		break;
		
		case G_MARS_VISIBLE_MAP :
			 return "G_MARS_VISIBLE_MAP" ;
		break;
		
		case G_MARS_INFRARED_MAP :
			 return "G_MARS_INFRARED_MAP" ;
		break;
		
		case G_SKY_VISIBLE_MAP :
			 return "G_SKY_VISIBLE_MAP" ;
		break;
		
		case G_SATELLITE_3D_MAP :
			 return "G_SATELLITE_3D_MAP" ;
		break;
		
	
	}

}  
  
// window.onload = initialize;
// if ( this.idMap != 12 )
	// document.write("<script type=\"text/javascript\">initialize();</script>");
// else
	FuncOL[1] = initialize;	


 /*
* ExtInfoWindow Class, v1.0 
*  Copyright (c) 2007, Joe Monahan (http://www.seejoecode.com)
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This class lets you add an info window to the map which mimics GInfoWindow
* and allows for users to skin it via CSS.  Additionally it has options to
* pull in HTML content from an ajax request, triggered when a user clicks on
* the associated marker.
*/


/**
 * Creates a new ExtInfoWindow that will initialize by reading styles from css
 *
 * @constructor
 * @param {GMarker} marker The marker associated with the info window
 * @param {String} windowId The DOM Id we will use to reference the info window
 * @param {String} html The HTML contents
 * @param {Object} opt_opts A contianer for optional arguments:
 *    {String} ajaxUrl The Url to hit on the server to request some contents 
 *    {Number} paddingX The padding size in pixels that the info window will leave on 
 *                    the left and right sides of the map when panning is involved.
 *    {Number} paddingY The padding size in pixels that the info window will leave on 
 *                    the top and bottom sides of the map when panning is involved.
 *    {Number} beakOffset The repositioning offset for when aligning the beak element. 
 *                    This is used to make sure the beak lines up correcting if the 
 *                    info window styling containers a border.
 */
function ExtInfoWindow(marker, windowId, html, opt_opts) {
  this.html_ = html;
  this.marker_ = marker;
  this.infoWindowId_ = windowId;

  this.options_ = opt_opts == null ? {} : opt_opts;
  this.ajaxUrl_ = this.options_.ajaxUrl == null ? null : this.options_.ajaxUrl;
  this.callback_ = this.options_.ajaxCallback == null ? null : this.options_.ajaxCallback;

  this.borderSize_ = this.options_.beakOffset == null ? 0 : this.options_.beakOffset;
  this.paddingX_ = this.options_.paddingX == null ? 0 + this.borderSize_ : this.options_.paddingX + this.borderSize_;
  this.paddingY_ = this.options_.paddingY == null ? 0 + this.borderSize_ : this.options_.paddingY + this.borderSize_;

  this.map_ = null;

  this.container_ = document.createElement('div');
  this.container_.style.position = 'relative';
  this.container_.style.display = 'none';

  this.contentDiv_ = document.createElement('div');
  this.contentDiv_.id = this.infoWindowId_ + '_contents';
  this.contentDiv_.innerHTML = this.html_;
  this.contentDiv_.style.display = 'block';
  this.contentDiv_.style.visibility = 'hidden';

  this.wrapperDiv_ = document.createElement('div');
};

/* //use the GOverlay class */
ExtInfoWindow.prototype = new GOverlay();

/**
 * Called by GMap2's addOverlay method.  Creates the wrapping div for our info window and adds
 * it to the relevant map pane.  Also binds mousedown event to a private function so that they
 * are not passed to the underlying map.  Finally, performs ajax request if set up to use ajax
 * in the constructor.
 * @param {GMap2} map The map that has had this extInfoWindow is added to it.
 */
ExtInfoWindow.prototype.initialize = function(map) {
  this.map_ = map;

  this.defaultStyles = {
    containerWidth: this.map_.getSize().width / 2,
    borderSize: 1
  };

  this.wrapperParts = {
    tl:{t:0, l:0, w:0, h:0, domElement: null},
    t:{t:0, l:0, w:0, h:0, domElement: null},
    tr:{t:0, l:0, w:0, h:0, domElement: null},
    l:{t:0, l:0, w:0, h:0, domElement: null},
    r:{t:0, l:0, w:0, h:0, domElement: null},
    bl:{t:0, l:0, w:0, h:0, domElement: null},
    b:{t:0, l:0, w:0, h:0, domElement: null},
    br:{t:0, l:0, w:0, h:0, domElement: null},
    beak:{t:0, l:0, w:0, h:0, domElement: null},
    close:{t:0, l:0, w:0, h:0, domElement: null}
  };

  for (var i in this.wrapperParts ) {
    var tempElement = document.createElement('div');
    tempElement.id = this.infoWindowId_ + '_' + i;
    tempElement.style.visibility = 'hidden';
    document.body.appendChild(tempElement);
    tempElement = document.getElementById(this.infoWindowId_ + '_' + i);
    var tempWrapperPart = eval('this.wrapperParts.' + i);    
    tempWrapperPart.w = parseInt(this.getStyle_(tempElement, 'width'));
    tempWrapperPart.h = parseInt(this.getStyle_(tempElement, 'height'));
    document.body.removeChild(tempElement);
  }
  for (var i in this.wrapperParts) {
    if (i == 'close' ) {
     /*  //first append the content so the close button is layered above it */
      this.wrapperDiv_.appendChild(this.contentDiv_);
    }
    var wrapperPartsDiv = null;
    if (this.wrapperParts[i].domElement == null) {
      wrapperPartsDiv = document.createElement('div');
      this.wrapperDiv_.appendChild(wrapperPartsDiv);
    } else {
      wrapperPartsDiv = this.wrapperParts[i].domElement;
    }
    wrapperPartsDiv.id = this.infoWindowId_ + '_' + i;
    wrapperPartsDiv.style.position = 'absolute';
    wrapperPartsDiv.style.width = this.wrapperParts[i].w + 'px';
    wrapperPartsDiv.style.height = this.wrapperParts[i].h + 'px';
    wrapperPartsDiv.style.top = this.wrapperParts[i].t + 'px';
    wrapperPartsDiv.style.left = this.wrapperParts[i].l + 'px';
    this.wrapperParts[i].domElement = wrapperPartsDiv;
  }
  
  this.map_.getPane(G_MAP_FLOAT_PANE).appendChild(this.container_);
  this.container_.id = this.infoWindowId_;
  var containerWidth  = this.getStyle_(document.getElementById(this.infoWindowId_), 'width');
  this.container_.style.width = (containerWidth == null ? this.defaultStyles.containerWidth : containerWidth);

  this.map_.getContainer().appendChild(this.contentDiv_);
  this.contentWidth = this.getDimensions_(this.container_).width;
  this.contentDiv_.style.width = this.contentWidth + 'px';
  this.contentDiv_.style.position = 'absolute';

  this.container_.appendChild(this.wrapperDiv_);

  GEvent.bindDom(this.container_, 'mousedown', this,this.onClick_);
  GEvent.bindDom(this.container_, 'dblclick', this,this.onClick_);
  GEvent.bindDom(this.container_, 'DOMMouseScroll', this, this.onClick_);
  

  GEvent.trigger(this.map_, 'extinfowindowopen');
  if (this.ajaxUrl_ != null ) {
    this.ajaxRequest_(this.ajaxUrl_);
  }
};

/**
 * Private function to steal mouse click events to prevent it from returning to the map.
 * Without this links in the ExtInfoWindow would not work, and you could click to zoom or drag 
 * the map behind it.
 * @private
 * @param {MouseEvent} e The mouse event caught by this function
 */
ExtInfoWindow.prototype.onClick_ = function(e) {
  if(navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  } else {
   /*  //e.preventDefault(); */
    e.stopPropagation();
  }
};

/**
 * Remove the extInfoWindow container from the map pane. 
 */
ExtInfoWindow.prototype.remove = function() {
  if (this.map_.getExtInfoWindow() != null) {
    GEvent.trigger(this.map_, 'extinfowindowbeforeclose');
    
    GEvent.clearInstanceListeners(this.container_);
    if (this.container_.outerHTML) {
      this.container_.outerHTML = ''; /* //prevent pseudo-leak in IE */
    }
    if (this.container_.parentNode) {
      this.container_.parentNode.removeChild(this.container_);
    }
    this.container_ = null;
    GEvent.trigger(this.map_, 'extinfowindowclose');
    this.map_.setExtInfoWindow_(null);
  }
};

/**
 * Return a copy of this overlay, for the parent Map to duplicate itself in full. This
 * is part of the Overlay interface and is used, for example, to copy everything in the 
 * main view into the mini-map.
 * @return {GOverlay}
 */
ExtInfoWindow.prototype.copy = function() {
  return new ExtInfoWindow(this.marker_, this.infoWindowId_, this.html_, this.options_);
};

/**
 * Draw extInfoWindow and wrapping decorators onto the map.  Resize and reposition
 * the map as necessary. 
 * @param {Boolean} force Will be true when pixel coordinates need to be recomputed.
 */
ExtInfoWindow.prototype.redraw = function(force) {
  if (!force || this.container_ == null) return;

/*   //set the content section's height, needed so  browser font resizing does not affect the window's dimensions */
  var contentHeight = this.contentDiv_.offsetHeight;
  this.contentDiv_.style.height = contentHeight + 'px';

 /*  //reposition contents depending on wrapper parts.
  //this is necessary for content that is pulled in via ajax */
  this.contentDiv_.style.left = this.wrapperParts.l.w + 'px';
  this.contentDiv_.style.top = this.wrapperParts.tl.h + 'px';
  this.contentDiv_.style.visibility = 'visible';

/*   //Finish configuring wrapper parts that were not set in initialization */
  this.wrapperParts.tl.t = 0;
  this.wrapperParts.tl.l = 0;
  this.wrapperParts.t.l = this.wrapperParts.tl.w;
  this.wrapperParts.t.w = (this.wrapperParts.l.w + this.contentWidth + this.wrapperParts.r.w) - this.wrapperParts.tl.w - this.wrapperParts.tr.w;
  this.wrapperParts.t.h = this.wrapperParts.tl.h;
  this.wrapperParts.tr.l = this.wrapperParts.t.w + this.wrapperParts.tl.w;
  this.wrapperParts.l.t = this.wrapperParts.tl.h;
  this.wrapperParts.l.h = contentHeight;
  this.wrapperParts.r.l = this.contentWidth + this.wrapperParts.l.w;
  this.wrapperParts.r.t = this.wrapperParts.tr.h;
  this.wrapperParts.r.h = contentHeight;
  this.wrapperParts.bl.t = contentHeight + this.wrapperParts.tl.h;
  this.wrapperParts.b.l = this.wrapperParts.bl.w;
  this.wrapperParts.b.t = contentHeight + this.wrapperParts.tl.h;
  this.wrapperParts.b.w = (this.wrapperParts.l.w + this.contentWidth + this.wrapperParts.r.w) - this.wrapperParts.bl.w - this.wrapperParts.br.w;
  this.wrapperParts.b.h = this.wrapperParts.bl.h;
  this.wrapperParts.br.l = this.wrapperParts.b.w + this.wrapperParts.bl.w;
  this.wrapperParts.br.t = contentHeight + this.wrapperParts.tr.h;
  this.wrapperParts.close.l = this.wrapperParts.tr.l +this.wrapperParts.tr.w - this.wrapperParts.close.w - this.borderSize_;
  this.wrapperParts.close.t = this.borderSize_;
  this.wrapperParts.beak.l = this.borderSize_ + (this.contentWidth / 2) - (this.wrapperParts.beak.w / 2);
  this.wrapperParts.beak.t = this.wrapperParts.bl.t + this.wrapperParts.bl.h - this.borderSize_;

 /*  //create the decoration wrapper DOM objects
  //append the styled info window to the container */
  for (var i in this.wrapperParts) {
    if (i == 'close' ) {
     /*  //first append the content so the close button is layered above it */
      this.wrapperDiv_.insertBefore(this.contentDiv_, this.wrapperParts[i].domElement);
    }
    var wrapperPartsDiv = null;
    if (this.wrapperParts[i].domElement == null) {
      wrapperPartsDiv = document.createElement('div');
      this.wrapperDiv_.appendChild(wrapperPartsDiv);
    } else {
      wrapperPartsDiv = this.wrapperParts[i].domElement;
    }
    wrapperPartsDiv.id = this.infoWindowId_ + '_' + i;
    wrapperPartsDiv.style.position='absolute';
    wrapperPartsDiv.style.width = this.wrapperParts[i].w + 'px';
    wrapperPartsDiv.style.height = this.wrapperParts[i].h + 'px';
    wrapperPartsDiv.style.top = this.wrapperParts[i].t + 'px';
    wrapperPartsDiv.style.left = this.wrapperParts[i].l + 'px';
    this.wrapperParts[i].domElement = wrapperPartsDiv;
  }

/*   //add event handler for the close box */ 
 var currentMarker = this.marker_;
  var thisMap = this.map_;
  GEvent.addDomListener(this.wrapperParts.close.domElement, 'click', 
    function() {
      thisMap.closeExtInfoWindow();

    }
  );

/*   //position the container on the map, over the marker */
  var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
  this.container_.style.position = 'absolute';
  var markerIcon = this.marker_.getIcon();
  this.container_.style.left = (pixelLocation.x 
    - (this.contentWidth / 2) 
    - markerIcon.iconAnchor.x 
    + markerIcon.infoWindowAnchor.x
  ) + 'px';

  this.container_.style.top = (pixelLocation.y
    - this.wrapperParts.bl.h
    - contentHeight
    - this.wrapperParts.tl.h
    - this.wrapperParts.beak.h
    - markerIcon.iconAnchor.y
    + markerIcon.infoWindowAnchor.y
    + this.borderSize_
  ) + 'px';

  this.container_.style.display = 'block';

  if(this.map_.getExtInfoWindow() != null) {
    this.repositionMap_();
  }
};

/**
 * Determine the dimensions of the contents to recalculate and reposition the 
 * wrapping decorator elements accordingly.
 */
ExtInfoWindow.prototype.resize = function(){
  
 /*  //Create temporary DOM node for new contents to get new height
  //This is done because if you manipulate this.contentDiv_ directly it causes visual errors in IE6 */
  var tempElement = this.contentDiv_.cloneNode(true);
  tempElement.id = this.infoWindowId_ + '_tempContents';
  tempElement.style.visibility = 'hidden';	
  tempElement.style.height = 'auto';
  document.body.appendChild(tempElement);
  tempElement = document.getElementById(this.infoWindowId_ + '_tempContents');
  var contentHeight = tempElement.offsetHeight;
  document.body.removeChild(tempElement);

/*   //Set the new height to eliminate visual defects that can be caused by font resizing in browser */
  this.contentDiv_.style.height = contentHeight + 'px';

  var contentWidth = this.contentDiv_.offsetWidth;
  var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());

  var oldWindowHeight = this.wrapperParts.t.domElement.offsetHeight + this.wrapperParts.l.domElement.offsetHeight + this.wrapperParts.b.domElement.offsetHeight;	
  var oldWindowPosTop = this.wrapperParts.t.domElement.offsetTop;

/*   //resize info window to look correct for new height */
  this.wrapperParts.l.domElement.style.height = contentHeight + 'px';
  this.wrapperParts.r.domElement.style.height = contentHeight + 'px';
  var newPosTop = this.wrapperParts.b.domElement.offsetTop - contentHeight;
  this.wrapperParts.l.domElement.style.top = newPosTop + 'px';
  this.wrapperParts.r.domElement.style.top = newPosTop + 'px';
  this.contentDiv_.style.top = newPosTop + 'px';
  windowTHeight = parseInt(this.wrapperParts.t.domElement.style.height);
  newPosTop -= windowTHeight;
  this.wrapperParts.close.domElement.style.top = newPosTop + this.borderSize_ + 'px';
  this.wrapperParts.tl.domElement.style.top = newPosTop + 'px';
  this.wrapperParts.t.domElement.style.top = newPosTop + 'px';
  this.wrapperParts.tr.domElement.style.top = newPosTop + 'px';

  this.repositionMap_();
};

/**
 * Check to see if the displayed extInfoWindow is positioned off the viewable 
 * map region and by how much.  Use that information to pan the map so that 
 * the extInfoWindow is completely displayed.
 * @private
 */
ExtInfoWindow.prototype.repositionMap_ = function(){
 /*  //pan if necessary so it shows on the screen */
  var mapNE = this.map_.fromLatLngToDivPixel(
    this.map_.getBounds().getNorthEast()
  );
  var mapSW = this.map_.fromLatLngToDivPixel(
    this.map_.getBounds().getSouthWest()
  );
  var markerPosition = this.map_.fromLatLngToDivPixel(
    this.marker_.getPoint()
  );

  var panX = 0;
  var panY = 0;
  var paddingX = this.paddingX_;
  var paddingY = this.paddingY_;
  var infoWindowAnchor = this.marker_.getIcon().infoWindowAnchor;
  var iconAnchor = this.marker_.getIcon().iconAnchor;

/*   //test top of screen	 */
  var windowT = this.wrapperParts.t.domElement;
  var windowL = this.wrapperParts.l.domElement;
  var windowB = this.wrapperParts.b.domElement;
  var windowR = this.wrapperParts.r.domElement;
  var windowBeak = this.wrapperParts.beak.domElement;

  var offsetTop = markerPosition.y - ( -infoWindowAnchor.y + iconAnchor.y +  this.getDimensions_(windowBeak).height + this.getDimensions_(windowB).height + this.getDimensions_(windowL).height + this.getDimensions_(windowT).height + this.paddingY_);
  if (offsetTop < mapNE.y) {
    panY = mapNE.y - offsetTop;
  } else {
   /*  //test bottom of screen */
    var offsetBottom = markerPosition.y + this.paddingY_;
    if (offsetBottom >= mapSW.y) {
      panY = -(offsetBottom - mapSW.y);
    }
  }

/*   //test right of screen */
  var offsetRight = Math.round(markerPosition.x + this.getDimensions_(this.container_).width/2 + this.getDimensions_(windowR).width + this.paddingX_ + infoWindowAnchor.x - iconAnchor.x);
  if (offsetRight > mapNE.x) {
    panX = -( offsetRight - mapNE.x);
  } else {
   /*  //test left of screen */
    var offsetLeft = - (Math.round( (this.getDimensions_(this.container_).width/2 - this.marker_.getIcon().iconSize.width/2) + this.getDimensions_(windowL).width + this.borderSize_ + this.paddingX_) - markerPosition.x - infoWindowAnchor.x + iconAnchor.x);
    if( offsetLeft < mapSW.x) {
      panX = mapSW.x - offsetLeft;
    }
  }

  if (panX != 0 || panY != 0 && this.map_.getExtInfoWindow() != null ) {
    this.map_.panBy(new GSize(panX,panY));
  }
};

/**
 * Private function that handles performing an ajax request to the server.  The response
 * information is assumed to be HTML and is placed inside this extInfoWindow's contents region.
 * Last, check to see if the height has changed, and resize the extInfoWindow accordingly.
 * @private
 * @param {String} url The Url of where to make the ajax request on the server
 */
ExtInfoWindow.prototype.ajaxRequest_ = function(url){
  var thisMap = this.map_;
  var thisCallback = this.callback_;
  GDownloadUrl(url, function(response, status){
    var infoWindow = document.getElementById(thisMap.getExtInfoWindow().infoWindowId_ + '_contents');
    if (response == null || status == -1 ) {
      infoWindow.innerHTML = '<span class="error">ERROR: The Ajax request failed to get HTML content from "' + url + '"</span>';
    } else {
      infoWindow.innerHTML = response;
    }
    if (thisCallback != null ) {
      thisCallback();
    }
    thisMap.getExtInfoWindow().resize();
    GEvent.trigger(thisMap, 'extinfowindowupdate');
  });
};

/**
 * Private function derived from Prototype.js to get a given element's
 * height and width
 * @private
 * @param {Object} element The DOM element that will have height and 
 *                    width will be calculated for it.
 * @return {Object} Object with keys: width, height
 */
ExtInfoWindow.prototype.getDimensions_ = function(element) {
  var display = this.getStyle_(element, 'display');
  if (display != 'none' && display != null) { /* // Safari bug */
    return {width: element.offsetWidth, height: element.offsetHeight};
  }

/*   // All *Width and *Height properties give 0 on elements with display none,
  // so enable the element temporarily */
  var els = element.style;
  var originalVisibility = els.visibility;
  var originalPosition = els.position;
  var originalDisplay = els.display;
  els.visibility = 'hidden';
  els.position = 'absolute';
  els.display = 'block';
  var originalWidth = element.clientWidth;
  var originalHeight = element.clientHeight;
  els.display = originalDisplay;
  els.position = originalPosition;
  els.visibility = originalVisibility;
  return {width: originalWidth, height: originalHeight};
};

/**
 * Private function derived from Prototype.js to get a given element's
 * value that is associated with the passed style
 * @private
 * @param {Object} element The DOM element that will be checked.
 * @param {String} style The style name that will be have it's value returned.
 * @return {Object}
 */
ExtInfoWindow.prototype.getStyle_ = function(element, style) {
  var found = false;
  style = this.camelize_(style);
  var value = element.style[style];
  if (!value) {
    if (document.defaultView && document.defaultView.getComputedStyle) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    } else if (element.currentStyle) {
      value = element.currentStyle[style];
    }
  }
  if((value == 'auto') && (style == 'width' || style == 'height') && (this.getStyle_(element, 'display') != 'none')) {
    if( style == 'width' ) {
      value = element.offsetWidth;
    }else {
      value = element.offsetHeight;
    }
  }
  return (value == 'auto') ? null : value;
};

/**
 * Private function pulled from Prototype.js that will change a hyphened
 * style name into camel case.
 * @private
 * @param {String} element The string that will be parsed and made into camel case
 * @return {String}
 */
ExtInfoWindow.prototype.camelize_ = function(element) {
  var parts = element.split('-'), len = parts.length;
  if (len == 1) return parts[0];
  var camelized = element.charAt(0) == '-'
    ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
    : parts[0];

  for (var i = 1; i < len; i++) {
    camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  }
  return camelized;
};

GMap.prototype.ExtInfoWindowInstance_ = null;
GMap.prototype.ClickListener_ = null;
GMap.prototype.InfoWindowListener_ = null;

/**
 * Creates a new instance of ExtInfoWindow for the GMarker.  Register the newly created 
 * instance with the map, ensuring only one window is open at a time. If this is the first
 * ExtInfoWindow ever opened, add event listeners to the map to close the ExtInfoWindow on 
 * zoom and click, to mimic the default GInfoWindow behavior.
 *
 * @param {GMap} map The GMap2 object where the ExtInfoWindow will open
 * @param {String} cssId The id we will use to reference the info window
 * @param {String} html The HTML contents
 * @param {Object} opt_opts A contianer for optional arguments:
 *    {String} ajaxUrl The Url to hit on the server to request some contents 
 *    {Number} paddingX The padding size in pixels that the info window will leave on 
 *                    the left and right sides of the map when panning is involved.
 *    {Number} paddingX The padding size in pixels that the info window will leave on 
 *                    the top and bottom sides of the map when panning is involved.
 *    {Number} beakOffset The repositioning offset for when aligning the beak element. 
 *                    This is used to make sure the beak lines up correcting if the 
 *                    info window styling containers a border.
 */
GMarker.prototype.openExtInfoWindow = function(map, cssId, html, opt_opts) {
  if (map == null) {
    throw 'Error in GMarker.openExtInfoWindow: map cannot be null';
    return false;
  }
  if (cssId == null || cssId == '') {
    throw 'Error in GMarker.openExtInfoWindow: must specify a cssId';
    return false;
  }
  
  map.closeInfoWindow();
  if (map.getExtInfoWindow() != null) {
    map.closeExtInfoWindow();
  }
  if (map.getExtInfoWindow() == null) {
    map.setExtInfoWindow_( new ExtInfoWindow(
      this,
      cssId,
      html,
      opt_opts
    ) );
    if (map.ClickListener_ == null) {
     /*  //listen for map click, close ExtInfoWindow if open */
      map.ClickListener_ = GEvent.addListener(map, 'click',
      function(event) {
          if( !event && map.getExtInfoWindow() != null ){
          
			
			
	/* ************************************************************************************************
	*																								  *
	*					Ajout des methodes a utiliser lors de la fermeture de l'infobulle		      *
	*																								  *
	***************************************************************************************************/
	 lastIdFooterIconsMarkers = "footerIconMarkerNum_1";
	 setDataIWMemory();
	

	
	/* ************************************************************************************************
	*																								  *
	*		Fin Ajout des methodes a utiliser lors de la fermeture de l'infobulle				      *
	*																								  *
	***************************************************************************************************/
			  map.closeExtInfoWindow();
          }
        }
      );
    }
    if (map.InfoWindowListener_ == null) {
    /*   //listen for default info window open, close ExtInfoWindow if open */
      map.InfoWindowListener_ = GEvent.addListener(map, 'infowindowopen', 
      function(event) {
          if (map.getExtInfoWindow() != null) {
            map.closeExtInfoWindow();
          }
        }
      );
    }
    map.addOverlay(map.getExtInfoWindow());
  }
};

/**
 * Remove the ExtInfoWindow instance
 * @param {GMap2} map The map where the GMarker and ExtInfoWindow exist
 */
GMarker.prototype.closeExtInfoWindow = function(map) {
  if( map.getExtInfWindow() != null ){
    map.closeExtInfoWindow();
  }
};

/**
 * Get the ExtInfoWindow instance from the map
 */
GMap2.prototype.getExtInfoWindow = function(){
  return this.ExtInfoWindowInstance_;
};
/**
 * Set the ExtInfoWindow instance for the map
 * @private
 */
GMap2.prototype.setExtInfoWindow_ = function( extInfoWindow ){
  this.ExtInfoWindowInstance_ = extInfoWindow;
}
/**
 * Remove the ExtInfoWindow from the map
 */
GMap2.prototype.closeExtInfoWindow = function(){
  if( this.getExtInfoWindow() != null ){
    this.ExtInfoWindowInstance_.remove();
  }
};
/*********************************************************************\
*                                                                     *
* egeoxml.js                                         by Mike Williams *
*                                                                     *
* A Google Maps API Extension                                         *
*                                                                     *
* Renders the contents of a My Maps (or similar) KML file             *
*                                                                     *
* Documentation: http://econym.org.uk/gmap/egeoxml.htm                * 
*                                                                     *
***********************************************************************
*                                                                     *
*   This Javascript is provided by Mike Williams                      *
*   Community Church Javascript Team                                  *
*   http://www.bisphamchurch.org.uk/                                  *
*   http://econym.org.uk/gmap/                                        *
*                                                                     *
*   This work is licenced under a Creative Commons Licence            *
*   http://creativecommons.org/licenses/by/2.0/uk/                    *
*                                                                     *
\*********************************************************************/


// Version 0.0   17 Apr 2007 - Initial testing, just markers
// Version 0.1   17 Apr 2007 - Sensible shadows, and a few general improvements
// Version 0.2   18 Apr 2007 - Polylines (non-clickable, no sidebar)
// Version 0.3   18 Apr 2007 - Polygons (non-clickable, no sidebar)
// Version 0.4   18 Apr 2007 - Sidebar entries for polygons
// Version 0.5   19 Apr 2007 - Accept an array of XML filenames, and add the {sortbyname} option
// Version 0.6   19 Apr 2007 - Sidebar entries for polylines, get directions and search nearby
// Version 0.7   20 Apr 2007 - Info Window Styles
// Version 0.8   21 Apr 2007 - baseicon
// Version 0.9   21 Apr 2007 - iwoptions and markeroptions
// Version 1.0   21 Apr 2007 - Launched
// Version 1.1   25 Apr 2007 - Bugfix - would crash if no options were specified
// Version 1.2   25 Apr 2007 - If the description begins with "http://" make it into a link.
// Version 1.3   30 Apr 2007 - printgif, dropbox
// Version 1.4   14 May 2007 - Elabels
// Version 1.5   17 May 2007 - Default values for width, fill and outline
// Version 1.6   21 May 2007 - GGroundOverlay (needs API V2.79+)
// Version 1.7   22 May 2007 - Better icon positioning for MyMaps icons
// Version 1.8   31 May 2007 - polyline bugfix
// Version 1.9   23 Jun 2007 - add .parseString() method
// Version 2.0   23 Jun 2007 - .parseString() handles an array of strings
// Version 2.1   25 Jul 2007 - imagescan
// Version 2.2   10 Aug 2007 - Support new My Maps icons
// Version 2.3   25 Nov 2007 - Clear variables used by .parse() so that it can be rerun
// Version 2.4   08 Dec 2007 - polylineoptions and polygonoptions
// Version 2.5   11 Dec 2007 - EGeoXml.value() trims leading and trailing whitespace 
// Version 2.6   08 Feb 2008 - Trailing whitespace wasn't removed in the previous change
// Version 2.7   14 Oct 2008 - If there's no <description> try looking for <text> instead
// Version 2.8   12 Jan 2009 - Bugfix - last point of poly was omitted
// Version 2.9   05 Feb 2009 - add .hide() .show()

// Constructor

function EGeoXml(myvar, map, url, opts) {
  // store the parameters
  this.myvar = myvar;
  this.map = map;
  this.url = url;
  if (typeof url == "string") {
    this.urls = [url];
  } else {
    this.urls = url;
  }
  this.opts = opts || {};
  
  // infowindow styles
  // this.titlestyle = this.opts.titlestyle || 'style = "font-family: arial, sans-serif;font-size: medium;font-weight:bold;font-size: 100%;"';
  // this.descstyle = this.opts.descstyle || 'style = "font-family: arial, sans-serif;font-size: small;padding-bottom:.7em;"';
  
  this.directionstyle = this.opts.directionstyle || 'style="font-family: arial, sans-serif;font-size: small;padding-left: 1px;padding-top: 1px;padding-right: 4px;"';
  // sidebar/dropbox functions
  this.sidebarfn = this.opts.sidebarfn || EGeoXml.addSidebar;
  this.dropboxfn = this.opts.dropboxfn || EGeoXml.addDropdown;
  // elabel options 
  this.elabelopacity = this.opts.elabelopacity || 100;
  // other useful "global" stuff
  this.bounds = new GLatLngBounds();
  this.gmarkers = [];
  this.gpolylines = [];
  this.gpolygons = [];
  this.groundoverlays = [];
  this.side_bar_html = "";
  this.side_bar_list = [];
  this.styles = []; // associative array
  this.iwwidth = this.opts.iwwidth || 250;
  this.progress = 0;
  this.lastmarker = {};   
  this.myimages = [];
  this.imageNum =0;
}
               
// uses GXml.value, then removes leading and trailing whitespace
EGeoXml.value = function(e) {
  a = GXml.value(e);
  a = a.replace(/^\s*/,"");
  a = a.replace(/\s*$/,"");
  return a;
}

// Create Marker

EGeoXml.prototype.createMarker = function( point,name,desc, style, idCategorie, icon, idMarker) {




  // var icon = G_DEFAULT_ICON;
  // var myvar=this.myvar;
  // var iwoptions = this.opts.iwoptions || {};
  var markeroptions = this.opts.markeroptions || {};
  
  /*On passe Name en titre */
  markeroptions["title"] = name;
  markeroptions["iconUrl"]= icon;
  
  // var icontype = this.opts.icontype || "style";
  // if (icontype == "style") {
    // if (!!this.styles[style]) {
      // icon = this.styles[style];
    // }
  // }
  // if (!markeroptions.icon) {
    // markeroptions.icon = icon;
  // }

  // for ( var i in  desc[0].contentElem)
	// alert ( i );
// alert ( "ok" );
	// Attempt to preload images
  if (this.opts.preloadimages) 
  {
    var text =  desc[0].contentElem.innerHTML;
    var pattern = /<\s*img/ig;
    var result;
    var pattern2 = /src\s*=\s*[\'\"]/;
    var pattern3 = /[\'\"]/;

    while ((result = pattern.exec(text)) != null)
	{
      var stuff = text.substr(result.index);
      var result2 = pattern2.exec(stuff);
      if (result2 != null) {
        stuff = stuff.substr(result2.index+result2[0].length);
        var result3 = pattern3.exec(stuff);
        if (result3 != null) {
          var imageUrl = stuff.substr(0,result3.index);
          this.myimages[this.imageNum] = new Image();
          this.myimages[this.imageNum].src = imageUrl;
          this.imageNum++;
		  
        }
      }
	
    }

  }



  if (this.opts.elabelclass) {
    var l = new ELabel(point, name, this.opts.elabelclass, this.opts.elabeloffset, this.elabelopacity, true);
    this.map.addOverlay(l);
  }

 



	// var html = "<div style = 'width:"+this.iwwidth+"px'>"
               // +"<div>"+desc+"</div>"
               // +"<div>ID Categorie : "+idCategorie+"</div>";

  // if (this.opts.directions) {
    // var html1 = html + '<div '+this.directionstyle+'>'
                     // + 'Get Directions: <a href="javascript:GEvent.trigger(' + this.myvar +'.lastmarker,\'click2\')">To Here</a> - ' 
                     // + '<a href="javascript:GEvent.trigger(' + this.myvar +'.lastmarker,\'click3\')">From Here</a><br>'
                     // + '<a href="javascript:GEvent.trigger(' + this.myvar +'.lastmarker,\'click4\')">Search nearby</a></div>';
    // var html2 = html + '<div '+this.directionstyle+'>'
                     // + 'Get Directions: To here - '
                     // + '<a href="javascript:GEvent.trigger(' + this.myvar +'.lastmarker,\'click3\')">From Here</a><br>'
                     // + 'Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">'
                     // + '<input type="text" SIZE=35 MAXLENGTH=80 name="saddr" id="saddr" value="" />'
                     // + '<INPUT value="Go" TYPE="SUBMIT">'
                     // + '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + "(" + name + ")" + '"/>'
                     // + '<br><a href="javascript:GEvent.trigger(' + this.myvar +'.lastmarker,\'click\')">&#171; Back</a></div>';
    // var html3 = html + '<div '+this.directionstyle+'>'
                     // + 'Get Directions: <a href="javascript:GEvent.trigger(' + this.myvar +'.lastmarker,\'click2\')">To Here</a> - ' 
                     // + 'From Here<br>'
                     // + 'End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">'
                     // + '<input type="text" SIZE=35 MAXLENGTH=80 name="daddr" id="daddr" value="" />'
                     // + '<INPUT value="Go" TYPE="SUBMIT">'
                     // + '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +  "(" + name + ")" + '"/>'
                     // + '<br><a href="javascript:GEvent.trigger(' + this.myvar +'.lastmarker,\'click\')">&#171; Back</a></div>';
    // var html4 = html + '<div '+this.directionstyle+'>'
                     // + 'Search nearby: e.g. "pizza"<br>'
                     // + '<form action="http://maps.google.com/maps" method="get"" target="_blank">'
                     // + '<input type="text" SIZE=35 MAXLENGTH=80 name="q" id="q" value="" />'
                     // + '<INPUT value="Go" TYPE="SUBMIT">'
                     // + '<input type="hidden" name="near" value="' + name + ' @' + point.lat() + ',' + point.lng() + '"/>'
                    // + '<input type="hidden" name="near" value="' +  point.lat() + ',' + point.lng() +  "(" + name + ")" + '"/>';
                     // + '<br><a href="javascript:GEvent.trigger(' + this.myvar +'.lastmarker,\'click\')">&#171; Back</a></div>';
    // GEvent.addListener(m, "click2", function() {
      // m.openInfoWindowHtml(html2 + "</div>",iwoptions);
    // });
    // GEvent.addListener(m, "click3", function() {
      // m.openInfoWindowHtml(html3 + "</div>",iwoptions);
    // });
    // GEvent.addListener(m, "click4", function() {
      // m.openInfoWindowHtml(html4 + "</div>",iwoptions);
    // });
  // } else {
    // var html1 = html;
  // }

  
  
   // var m = new GMarker(, markeroptions);
   
   
	var optionsInfoWindows =
	{
		"click":true,
		"type":"multiTab", 
		"content": desc
	}
		
		
  
   
   var m = createMarker ( point.lat(), point.lng() , markeroptions, optionsInfoWindows )
  
  
  // GEvent.addListener(m, "click", function() {
    // eval(myvar+".lastmarker = m");
    // m.openInfoWindowHtml(html + "</div>",iwoptions);
  // });
  
  
  
  
  
  if (!!this.opts.addmarker) {
    this.opts.addmarker( m,name,desc,icon.image, idMarker, idCategorie )
  } else {
    this.map.addOverlay(m);
  }
  
  this.gmarkers.push(m);
  // if (this.opts.sidebarid || this.opts.dropboxid) {
    // var n = this.gmarkers.length-1;
    // this.side_bar_list.push (name + "$$$marker$$$" + n +"$$$" );
  // }
}

// Create Polyline

EGeoXml.prototype.createPolyline = function(points,color,width,opacity,pbounds,name,desc) {
  var thismap = this.map;
  var iwoptions = this.opts.iwoptions || {};
  var polylineoptions = this.opts.polylineoptions || {};
  var p = new GPolyline(points,color,width,opacity,polylineoptions);
  this.map.addOverlay(p);
  this.gpolylines.push(p);
  var html = "<div style='font-weight: bold; font-size: medium; margin-bottom: 0em;'>"+name+"</div>"
             +"<div style='font-family: Arial, sans-serif;font-size: small;width:"+this.iwwidth+"px'>"+desc+"</div>";
  GEvent.addListener(p,"click", function() {
    thismap.openInfoWindowHtml(p.getVertex(Math.floor(p.getVertexCount()/2)),html,iwoptions);
  } );
  if (this.opts.sidebarid) {
    var n = this.gpolylines.length-1;
    var blob = '&nbsp;&nbsp;<span style=";border-left:'+width+'px solid '+color+';">&nbsp;</span> ';
    this.side_bar_list.push (name + "$$$polyline$$$" + n +"$$$" + blob );
  }
}

// Create Polygon

EGeoXml.prototype.createPolygon = function(points,color,width,opacity,fillcolor,fillopacity,pbounds, name, desc) {
  var thismap = this.map;
  var iwoptions = this.opts.iwoptions || {};
  var polygonoptions = this.opts.polygonoptions || {};
  var p = new GPolygon(points,color,width,opacity,fillcolor,fillopacity,polygonoptions)
  this.map.addOverlay(p);
  this.gpolygons.push(p);
  var html = "<div style='font-weight: bold; font-size: medium; margin-bottom: 0em;'>"+name+"</div>"
             +"<div style='font-family: Arial, sans-serif;font-size: small;width:"+this.iwwidth+"px'>"+desc+"</div>";
  GEvent.addListener(p,"click", function() {
    thismap.openInfoWindowHtml(pbounds.getCenter(),html,iwoptions);
  } );
  if (this.opts.sidebarid) {
    var n = this.gpolygons.length-1;
    var blob = '<span style="background-color:' +fillcolor + ';border:2px solid '+color+';">&nbsp;&nbsp;&nbsp;&nbsp;</span> ';
    this.side_bar_list.push (name + "$$$polygon$$$" + n +"$$$" + blob );
  }
}


// Sidebar factory method One - adds an entry to the sidebar
EGeoXml.addSidebar = function(myvar,name,type,i,graphic) {
  if (type == "marker") {
    return '<a href="javascript:GEvent.trigger(' + myvar+ '.gmarkers['+i+'],\'click\')">' + name + '</a><br>';
  }
  if (type == "polyline") {
    return '<div style="margin-top:6px;"><a href="javascript:GEvent.trigger(' + myvar+ '.gpolylines['+i+'],\'click\')">' + graphic + name + '</a></div>';
  }
  if (type == "polygon") {
    return '<div style="margin-top:6px;"><a href="javascript:GEvent.trigger(' + myvar+ '.gpolygons['+i+'],\'click\')">' + graphic + name + '</a></div>';
  }
}

// Dropdown factory method
EGeoXml.addDropdown = function(myvar,name,type,i,graphic) {
    return '<option value="' + i + '">' + name +'</option>';
}

  
// Request to Parse an XML file

EGeoXml.prototype.parse = function() {
  // clear some variables
  this.gmarkers = [];
  this.gpolylines = [];
  this.gpolygons = [];
  this.groundoverlays = [];
  this.side_bar_html = "";
  this.side_bar_list = [];
  this.styles = []; // associative array
  this.lastmarker = {};   
  this.myimages = [];
  this.imageNum =0;
  var that = this;
  this.progress = this.urls.length;
  for (u=0; u<this.urls.length; u++) {
    GDownloadUrl(this.urls[u], function(doc) {that.processing(doc)});
  }
}

EGeoXml.prototype.parseString = function(doc) {
  // clear some variables
  this.gmarkers = [];
  this.gpolylines = [];
  this.gpolygons = [];
  this.groundoverlays = [];
  this.side_bar_html = "";
  this.side_bar_list = [];
  this.styles = []; // associative array
  this.lastmarker = {};   
  this.myimages = [];
  this.imageNum =0;
  if (typeof doc == "string") {
    this.docs = [doc];
  } else {
    this.docs = doc;
  }
  this.progress = this.docs.length;
  for (u=0; u<this.docs.length; u++) {
    this.processing(this.docs[u]);
  }
}


EGeoXml.prototype.processing = function(doc) {
    var that = this;
    var xmlDoc = GXml.parse(doc)
    // Read through the Styles
   /*  var styles = xmlDoc.documentElement.getElementsByTagName("Style");
    for (var i = 0; i <styles.length; i++) {
      var styleID = styles[i].getAttribute("id");
      var icons=styles[i].getElementsByTagName("Icon");
      // This might not be am icon style
      if (icons.length > 0) {
        var href=EGeoXml.value(icons[0].getElementsByTagName("href")[0]);
        if (!!href) {
          if (!!that.opts.baseicon) {
            that.styles["#"+styleID] = new GIcon(that.opts.baseicon,href);
          } else {
            that.styles["#"+styleID] = new GIcon(G_DEFAULT_ICON,href);
            that.styles["#"+styleID].iconSize = new GSize(32,32);
            that.styles["#"+styleID].shadowSize = new GSize(59,32);
            that.styles["#"+styleID].dragCrossAnchor = new GPoint(2,8);
            that.styles["#"+styleID].iconAnchor = new GPoint(16,32);
            if (that.opts.printgif) {
              var bits = href.split("/");
              var gif = bits[bits.length-1];
              gif = that.opts.printgifpath + gif.replace(/.png/i,".gif");
              that.styles["#"+styleID].printImage = gif;
              that.styles["#"+styleID].mozPrintImage = gif;
            }
            if (!!that.opts.noshadow) {
              that.styles["#"+styleID].shadow="";
            } else {
              // Try to guess the shadow image
              if (href.indexOf("/red.png")>-1 
               || href.indexOf("/blue.png")>-1 
               || href.indexOf("/green.png")>-1 
               || href.indexOf("/yellow.png")>-1 
               || href.indexOf("/lightblue.png")>-1 
               || href.indexOf("/purple.png")>-1 
               || href.indexOf("/pink.png")>-1 
               || href.indexOf("/orange.png")>-1 
               || href.indexOf("-dot.png")>-1 ) {
                  that.styles["#"+styleID].shadow="http://maps.google.com/mapfiles/ms/micons/msmarker.shadow.png";
              }
              else if (href.indexOf("-pushpin.png")>-1) {
                  that.styles["#"+styleID].shadow="http://maps.google.com/mapfiles/ms/micons/pushpin_shadow.png";
              }
              else {
                var shadow = href.replace(".png",".shadow.png");
                that.styles["#"+styleID].shadow=shadow;
              }
            }
          }
        }
      }
      // is it a LineStyle ?
      var linestyles=styles[i].getElementsByTagName("LineStyle");
      if (linestyles.length > 0) {
        var width = parseInt(GXml.value(linestyles[0].getElementsByTagName("width")[0]));
        if (width < 1) {width = 5;}
        var color = EGeoXml.value(linestyles[0].getElementsByTagName("color")[0]);
        var aa = color.substr(0,2);
        var bb = color.substr(2,2);
        var gg = color.substr(4,2);
        var rr = color.substr(6,2);
        color = "#" + rr + gg + bb;
        var opacity = parseInt(aa,16)/256;
        if (!that.styles["#"+styleID]) {
          that.styles["#"+styleID] = {};
        }
        that.styles["#"+styleID].color=color;
        that.styles["#"+styleID].width=width;
        that.styles["#"+styleID].opacity=opacity;
      }
      // is it a PolyStyle ?
      var polystyles=styles[i].getElementsByTagName("PolyStyle");
      if (polystyles.length > 0) {
        var fill = parseInt(GXml.value(polystyles[0].getElementsByTagName("fill")[0]));
        var outline = parseInt(GXml.value(polystyles[0].getElementsByTagName("outline")[0]));
        var color = EGeoXml.value(polystyles[0].getElementsByTagName("color")[0]);

        if (polystyles[0].getElementsByTagName("fill").length == 0) {fill = 1;}
        if (polystyles[0].getElementsByTagName("outline").length == 0) {outline = 1;}
        var aa = color.substr(0,2);
        var bb = color.substr(2,2);
        var gg = color.substr(4,2);
        var rr = color.substr(6,2);
        color = "#" + rr + gg + bb;

        var opacity = parseInt(aa,16)/256;
        if (!that.styles["#"+styleID]) {
          that.styles["#"+styleID] = {};
        }
        that.styles["#"+styleID].fillcolor=color;
        that.styles["#"+styleID].fillopacity=opacity;
        if (!fill) that.styles["#"+styleID].fillopacity = 0; 
        if (!outline) that.styles["#"+styleID].opacity = 0; 
      }
    } */

    // Read through the Placemarks
    var placemarks = xmlDoc.documentElement.getElementsByTagName("Placemark");
    for (var i = 0; i < placemarks.length; i++) {
	
      var name=EGeoXml.value(placemarks[i].getElementsByTagName("name")[0]);
      var desc=EGeoXml.value(placemarks[i].getElementsByTagName("description")[0]);
	  var idCategorie=EGeoXml.value(placemarks[i].getElementsByTagName("idCategorie")[0]);
	  var idMarker=EGeoXml.value(placemarks[i].getElementsByTagName("idMarker")[0]);
	  var icon=	EGeoXml.value( placemarks[i].getElementsByTagName("Icon")[0].getElementsByTagName("href")[0]);
	  
	  var infoWindowTabs = placemarks[i].getElementsByTagName("infoWindowTabs");
	  index_max = infoWindowTabs.length;
	  
	 var GInfoWindowTab = []; 
	 
	 
	 for ( index=0; index<index_max; index++ )
	 {
		GInfoWindowTab.push (  getInfoWindowTab( EGeoXml.value(infoWindowTabs[index].getElementsByTagName("title")[0]), EGeoXml.value(infoWindowTabs[index].getElementsByTagName("content")[0]) ) );
	 
	 }
	  

	 // <infoWindowTabs> 
		// <tabIw>  
		// <title></title> 
		// <content></content></tabIw>
	// </infoWindowTabs>
	  
	  
	  
      if (desc=="") {
        var desc=EGeoXml.value(placemarks[i].getElementsByTagName("text")[0]);
        desc = desc.replace(/\$\[name\]/,name);
        desc = desc.replace(/\$\[geDirections\]/,"");
      }
      if (desc.match(/^http:\/\//i)) {
        desc = '<a href="' + desc + '">' + desc + '</a>';
      }
      if (desc.match(/^https:\/\//i)) {
        desc = '<a href="' + desc + '">' + desc + '</a>';
      }
      var style=EGeoXml.value(placemarks[i].getElementsByTagName("styleUrl")[0]);
      var coords=GXml.value(placemarks[i].getElementsByTagName("coordinates")[0]);
      coords=coords.replace(/\s+/g," "); // tidy the whitespace
      coords=coords.replace(/^ /,"");    // remove possible leading whitespace
      coords=coords.replace(/ $/,"");    // remove possible trailing whitespace
      coords=coords.replace(/, /,",");   // tidy the commas
      var path = coords.split(" ");

      // Is this a polyline/polygon?
      if (path.length > 1) {
        // Build the list of points
        var points = [];
        var pbounds = new GLatLngBounds();
        for (var p=0; p<path.length; p++) {
          var bits = path[p].split(",");
          var point = new GLatLng(parseFloat(bits[1]),parseFloat(bits[0]));
          points.push(point);
          that.bounds.extend(point);
          pbounds.extend(point);
        }
        var linestring=placemarks[i].getElementsByTagName("LineString");
        if (linestring.length) {
          // it's a polyline grab the info from the style
          if (!!that.styles[style]) {
            var width = that.styles[style].width; 
            var color = that.styles[style].color; 
            var opacity = that.styles[style].opacity; 
          } else {
            var width = 5;
            var color = "#0000ff";
            var opacity = 0.45;
          }
          // Does the user have their own createmarker function?
          if (!!that.opts.createpolyline) {
            that.opts.createpolyline(points,color,width,opacity,pbounds,name,desc);
          } else {
            that.createPolyline(points,color,width,opacity,pbounds,name,desc);
          }
        }

        var polygons=placemarks[i].getElementsByTagName("Polygon");
        if (polygons.length) {
          // it's a polygon grab the info from the style
          if (!!that.styles[style]) {
            var width = that.styles[style].width; 
            var color = that.styles[style].color; 
            var opacity = that.styles[style].opacity; 
            var fillopacity = that.styles[style].fillopacity; 
            var fillcolor = that.styles[style].fillcolor; 
          } else {
            var width = 5;
            var color = "#0000ff";
            var opacity = 0.45;
            var fillopacity = 0.25;
            var fillcolor = "#0055ff";
          }
          // Does the user have their own createmarker function?
          if (!!that.opts.createpolygon) {
            that.opts.createpolygon(points,color,width,opacity,fillcolor,fillopacity,pbounds,name,desc);
          } else {
            that.createPolygon(points,color,width,opacity,fillcolor,fillopacity,pbounds,name,desc);
          }
        }


      } else {
        // It's not a poly, so I guess it must be a marker
        var bits = path[0].split(",");
        var point = new GLatLng(parseFloat(bits[1]),parseFloat(bits[0]));
        that.bounds.extend(point);
        // Does the user have their own createmarker function?
        if (!!that.opts.createmarker) {
          that.opts.createmarker(point, name, GInfoWindowTab, style, idCategorie, icon, idMarker);
        } else {
          that.createMarker(point, name, GInfoWindowTab, style, idCategorie, icon, idMarker);
        }
      }
    }
    
    // Scan through the Ground Overlays
    var grounds = xmlDoc.documentElement.getElementsByTagName("GroundOverlay");
    for (var i = 0; i < grounds.length; i++) {
      var url=EGeoXml.value(grounds[i].getElementsByTagName("href")[0]);
      var north=parseFloat(GXml.value(grounds[i].getElementsByTagName("north")[0]));
      var south=parseFloat(GXml.value(grounds[i].getElementsByTagName("south")[0]));
      var east=parseFloat(GXml.value(grounds[i].getElementsByTagName("east")[0]));
      var west=parseFloat(GXml.value(grounds[i].getElementsByTagName("west")[0]));
      var sw = new GLatLng(south,west);
      var ne = new GLatLng(north,east);                           
      var ground = new GGroundOverlay(url, new GLatLngBounds(sw,ne));
      that.bounds.extend(sw); 
      that.bounds.extend(ne); 
      that.groundoverlays.push(ground);
      that.map.addOverlay(ground);
    }

    // Is this the last file to be processed?
    that.progress--;
    if (that.progress == 0) {
      // Shall we zoom to the bounds?
      if (!that.opts.nozoom) {
        that.map.setZoom(that.map.getBoundsZoomLevel(that.bounds));
        that.map.setCenter(that.bounds.getCenter());
      }
      // Shall we display the sidebar?
      if (that.opts.sortbyname) {
        that.side_bar_list.sort();
      }
      if (that.opts.sidebarid) {
        for (var i=0; i<that.side_bar_list.length; i++) {
          var bits = that.side_bar_list[i].split("$$$",4);
          that.side_bar_html += that.sidebarfn(that.myvar,bits[0],bits[1],bits[2],bits[3]); 
        }
        document.getElementById(that.opts.sidebarid).innerHTML += that.side_bar_html;
      }
      if (that.opts.dropboxid) {
        for (var i=0; i<that.side_bar_list.length; i++) {
          var bits = that.side_bar_list[i].split("$$$",4);
          if (bits[1] == "marker") {
            that.side_bar_html += that.dropboxfn(that.myvar,bits[0],bits[1],bits[2],bits[3]); 
          }
        }
        document.getElementById(that.opts.dropboxid).innerHTML = '<select onChange="var I=this.value;if(I>-1){GEvent.trigger('+that.myvar+'.gmarkers[I],\'click\'); }">'
          + '<option selected> - Select a location - </option>'
          + that.side_bar_html
          + '</select>';
      }

      GEvent.trigger(that,"parsed");
    }
}

EGeoXml.prototype.hide = function() {
  for (var i=0; i<this.gmarkers.length; i++) {
    this.gmarkers[i].hide();
  }
  for (var i=0; i<this.gpolylines.length; i++) {
    this.gpolylines[i].hide();
  }
  for (var i=0; i<this.gpolygons.length; i++) {
    this.gpolygons[i].hide();
  }
  for (var i=0; i<this.groundoverlays.length; i++) {
    this.groundoverlays[i].hide();
  }
  if (this.opts.sidebarid) {
    document.getElementById(this.opts.sidebarid).style.display="none";
  }
  if (this.opts.dropboxid) {
    document.getElementById(this.opts.dropboxid).style.display="none";
  }
}

EGeoXml.prototype.show = function() {
  for (var i=0; i<this.gmarkers.length; i++) {
    this.gmarkers[i].show();
  }
  for (var i=0; i<this.gpolylines.length; i++) {
    this.gpolylines[i].show();
  }
  for (var i=0; i<this.gpolygons.length; i++) {
    this.gpolygons[i].show();
  }
  for (var i=0; i<this.groundoverlays.length; i++) {
    this.groundoverlays[i].show();
  }
  if (this.opts.sidebarid) {
    document.getElementById(this.opts.sidebarid).style.display="";
  }
  if (this.opts.dropboxid) {
    document.getElementById(this.opts.dropboxid).style.display="";
  }
}

/* // script.aculo.us effects.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008

// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

// converts rgb() and #xxx to #xxxxxx format,
// returns self (or first argument) if not convertable */
String.prototype.parseColor = function() {
  var color = '#';
  if (this.slice(0,4) == 'rgb(') {
    var cols = this.slice(4,this.length-1).split(',');
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
  } else {
    if (this.slice(0,1) == '#') {
      if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
      if (this.length==7) color = this.toLowerCase();
    }
  }
  return (color.length==7 ? color : (arguments[0] || this));
};

/*--------------------------------------------------------------------------*/

Element.collectTextNodes = function(element) {
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue :
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
};

Element.collectTextNodesIgnoreClass = function(element, className) {
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue :
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
};

Element.setContentZoom = function(element, percent) {
  element = $(element);
  element.setStyle({fontSize: (percent/100) + 'em'});
  if (Prototype.Browser.WebKit) window.scrollBy(0,0);
  return element;
};

Element.getInlineOpacity = function(element){
  return $(element).style.opacity || '';
};

Element.forceRerendering = function(element) {
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
  } catch(e) { }
};

/*--------------------------------------------------------------------------*/

var Effect = {
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
  Transitions: {
    linear: Prototype.K,
    sinoidal: function(pos) {
      return (-Math.cos(pos*Math.PI)/2) + .5;
    },
    reverse: function(pos) {
      return 1-pos;
    },
    flicker: function(pos) {
      var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
      return pos > 1 ? 1 : pos;
    },
    wobble: function(pos) {
      return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
    },
    pulse: function(pos, pulses) {
      return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
    },
    spring: function(pos) {
      return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
    },
    none: function(pos) {
      return 0;
    },
    full: function(pos) {
      return 1;
    }
  },
  DefaultOptions: {
    duration:   1.0,  /*  // seconds */
    fps:        100,   /* // 100= assume 66fps max. */
    sync:       false, /* // true for combining */
    from:       0.0,
    to:         1.0,
    delay:      0.0,
    queue:      'parallel'
  },
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';

    element = $(element);
    $A(element.childNodes).each( function(child) {
      if (child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            new Element('span', {style: tagifyStyle}).update(
              character == ' ' ? String.fromCharCode(160) : character),
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if (((typeof element == 'object') ||
        Object.isFunction(element)) &&
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;

    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || { });
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
    }, arguments[2] || { });
    Effect[element.visible() ?
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create(Enumerable, {
  initialize: function() {
    this.effects  = [];
    this.interval = null;
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();

    var position = Object.isString(effect.options.queue) ?
      effect.options.queue : effect.options.queue.position;

    switch(position) {
      case 'front':
       /*  // move unstarted effects after this effect */
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'with-last':
        timestamp = this.effects.pluck('startOn').max() || timestamp;
        break;
      case 'end':
        /* // start effect after last queued effect has finished */
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }

    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);

    if (!this.interval)
      this.interval = setInterval(this.loop.bind(this), 15);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if (this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    for(var i=0, len=this.effects.length;i<len;i++)
      this.effects[i] && this.effects[i].loop(timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if (!Object.isString(queueName)) return queueName;

    return this.instances.get(queueName) ||
      this.instances.set(queueName, new Effect.ScopedQueue());
  }
};
Effect.Queue = Effect.Queues.get('global');

Effect.Base = Class.create({
  position: null,
  start: function(options) {
    function codeForEvent(options,eventName){
      return (
        (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
        (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
      );
    }
    if (options && options.transition === false) options.transition = Effect.Transitions.linear;
    this.options      = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn+(this.options.duration*1000);
    this.fromToDelta  = this.options.to-this.options.from;
    this.totalTime    = this.finishOn-this.startOn;
    this.totalFrames  = this.options.fps*this.options.duration;

    this.render = (function() {
      function dispatch(effect, eventName) {
        if (effect.options[eventName + 'Internal'])
          effect.options[eventName + 'Internal'](effect);
        if (effect.options[eventName])
          effect.options[eventName](effect);
      }

      return function(pos) {
        if (this.state === "idle") {
          this.state = "running";
          dispatch(this, 'beforeSetup');
          if (this.setup) this.setup();
          dispatch(this, 'afterSetup');
        }
        if (this.state === "running") {
          pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
          this.position = pos;
          dispatch(this, 'beforeUpdate');
          if (this.update) this.update(pos);
          dispatch(this, 'afterUpdate');
        }
      };
    })();

    this.event('beforeStart');
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ?
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if (timePos >= this.startOn) {
      if (timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if (this.finish) this.finish();
        this.event('afterFinish');
        return;
      }
      var pos   = (timePos - this.startOn) / this.totalTime,
          frame = (pos * this.totalFrames).round();
      if (frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  cancel: function() {
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ?
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if (this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    var data = $H();
    for(property in this)
      if (!Object.isFunction(this[property])) data.set(property, this[property]);
    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
});

Effect.Parallel = Class.create(Effect.Base, {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if (effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Tween = Class.create(Effect.Base, {
  initialize: function(object, from, to) {
    object = Object.isString(object) ? $(object) : object;
    var args = $A(arguments), method = args.last(),
      options = args.length == 5 ? args[3] : null;
    this.method = Object.isFunction(method) ? method.bind(object) :
      Object.isFunction(object[method]) ? object[method].bind(object) :
      function(value) { object[method] = value };
    this.start(Object.extend({ from: from, to: to }, options || { }));
  },
  update: function(position) {
    this.method(position);
  }
});

Effect.Event = Class.create(Effect.Base, {
  initialize: function() {
    this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
  },
  update: Prototype.emptyFunction
});

Effect.Opacity = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
   /*  // make this work on IE on elements without 'layout' */
    if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
      this.element.setStyle({zoom: 1});
    var options = Object.extend({
      from: this.element.getOpacity() || 0.0,
      to:   1.0
    }, arguments[1] || { });
    this.start(options);
  },
  update: function(position) {
    this.element.setOpacity(position);
  }
});

Effect.Move = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
    this.element.makePositioned();
    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
    if (this.options.mode == 'absolute') {
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    this.element.setStyle({
      left: (this.options.x  * position + this.originalLeft).round() + 'px',
      top:  (this.options.y  * position + this.originalTop).round()  + 'px'
    });
  }
});

/* // for backwards compatibility */
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element,
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
};

Effect.Scale = Class.create(Effect.Base, {
  initialize: function(element, percent) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        /* // 'box' or 'contents' or { } with provided values */
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || { });
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');

    this.originalStyle = { };
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));

    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;

    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%','pt'].each( function(fontSizeType) {
      if (fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));

    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;

    this.dims = null;
    if (this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if (/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if (!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if (this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = { };
    if (this.options.scaleX) d.width = width.round() + 'px';
    if (this.options.scaleY) d.height = height.round() + 'px';
    if (this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if (this.elementPositioning == 'absolute') {
        if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if (this.options.scaleY) d.top = -topd + 'px';
        if (this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});

Effect.Highlight = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
  /*   // Prevent executing on elements not in the layout flow */
    if (this.element.getStyle('display')=='none') { this.cancel(); return; }
  /*   // Disable background image during the effect */
    this.oldStyle = { };
    if (!this.options.keepBackgroundImage) {
      this.oldStyle.backgroundImage = this.element.getStyle('background-image');
      this.element.setStyle({backgroundImage: 'none'});
    }
    if (!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
    if (!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('background-color');
   /*  // init color calculations */
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = function(element) {
  var options = arguments[1] || { },
  scrollOffsets = document.viewport.getScrollOffsets(),
  elementOffsets = $(element).cumulativeOffset();

  if (options.offset) elementOffsets[1] += options.offset;

  return new Effect.Tween(null,
    scrollOffsets.top,
    elementOffsets[1],
    options,
    function(p){ scrollTo(scrollOffsets.left, p.round()); }
  );
};

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  var options = Object.extend({
    from: element.getOpacity() || 1.0,
    to:   0.0,
    afterFinishInternal: function(effect) {
      if (effect.options.to!=0) return;
      effect.element.hide().setStyle({opacity: oldOpacity});
    }
  }, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Appear = function(element) {
  element = $(element);
  var options = Object.extend({
  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
  to:   1.0,
 /*  // force Safari to render floated elements properly */
  afterFinishInternal: function(effect) {
    effect.element.forceRerendering();
  },
  beforeSetup: function(effect) {
    effect.element.setOpacity(effect.options.from).show();
  }}, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = {
    opacity: element.getInlineOpacity(),
    position: element.getStyle('position'),
    top:  element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height
  };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200,
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
     Object.extend({ duration: 1.0,
      beforeSetupInternal: function(effect) {
        Position.absolutize(effect.effects[0].element);
      },
      afterFinishInternal: function(effect) {
         effect.effects[0].element.hide().setStyle(oldStyle); }
     }, arguments[1] || { })
   );
};

Effect.BlindUp = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false,
      scaleX: false,
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      }
    }, arguments[1] || { })
  );
};

Effect.BlindDown = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({
    scaleContent: false,
    scaleX: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({height: '0px'}).show();
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};


	Effect.BlindRight = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({
    scaleContent: false,
    scaleY: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({width: '0px'}).show();
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};

Effect.BlindLeft = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false,
      scaleY: false,
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      }
    }, arguments[1] || { })
  );
};

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  return new Effect.Appear(element, Object.extend({
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, {
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) {
          effect.element.makePositioned().makeClipping();
        },
        afterFinishInternal: function(effect) {
          effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
        }
      });
    }
  }, arguments[1] || { }));
};

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left'),
    opacity: element.getInlineOpacity() };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) {
          effect.effects[0].element.makePositioned();
        },
        afterFinishInternal: function(effect) {
          effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
        }
      }, arguments[1] || { }));
};

Effect.Shake = function(element) {
  element = $(element);
  var options = Object.extend({
    distance: 20,
    duration: 0.5
  }, arguments[1] || {});
  var distance = parseFloat(options.distance);
  var split = parseFloat(options.duration) / 10.0;
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left') };
    return new Effect.Move(element,
      { x:  distance, y: 0, duration: split, afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
        effect.element.undoPositioned().setStyle(oldStyle);
  }}); }}); }}); }}); }}); }});
};

Effect.SlideDown = function(element) {
  element = $(element).cleanWhitespace();
 /*  // SlideDown need to have the content of the element wrapped in a container element with fixed height! */
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({
    scaleContent: false,
    scaleX: false,
    scaleFrom: window.opera ? 0 : 1,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().setStyle({height: '0px'}).show();
    },
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
    }, arguments[1] || { })
  );
};

Effect.SlideUp = function(element) {
  element = $(element).cleanWhitespace();
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, window.opera ? 0 : 1,
   Object.extend({ scaleContent: false,
    scaleX: false,
    scaleMode: 'box',
    scaleFrom: 100,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().show();
    },
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    },
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
    }
   }, arguments[1] || { })
  );
};
/* 
// Bug in opera makes the TD containing this element expand for a instance after finish */
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, {
    restoreAfterFinish: true,
    beforeSetup: function(effect) {
      effect.element.makeClipping();
    },
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping();
    }
  });
};

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var initialMoveX, initialMoveY;
  var moveX, moveY;

  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0;
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }

  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01,
    beforeSetup: function(effect) {
      effect.element.hide().makeClipping().makePositioned();
    },
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) {
               effect.effects[0].element.setStyle({height: '0px'}).show();
             },
             afterFinishInternal: function(effect) {
               effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
             }
           }, options)
      );
    }
  });
};

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var moveX, moveY;

  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }

  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned().makeClipping();
         },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
       }, options)
  );
};

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || { },
    oldOpacity = element.getInlineOpacity(),
    transition = options.transition || Effect.Transitions.linear,
    reverser   = function(pos){
      return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
    };

  return new Effect.Opacity(element,
    Object.extend(Object.extend({  duration: 2.0, from: 0,
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    }, options), {transition: reverser}));
};

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  element.makeClipping();
  return new Effect.Scale(element, 5, Object.extend({
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, {
      scaleContent: false,
      scaleY: false,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping().setStyle(oldStyle);
      } });
  }}, arguments[1] || { }));
};

Effect.Morph = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      style: { }
    }, arguments[1] || { });

    if (!Object.isString(options.style)) this.style = $H(options.style);
    else {
      if (options.style.include(':'))
        this.style = options.style.parseStyle();
      else {
        this.element.addClassName(options.style);
        this.style = $H(this.element.getStyles());
        this.element.removeClassName(options.style);
        var css = this.element.getStyles();
        this.style = this.style.reject(function(style) {
          return style.value == css[style.key];
        });
        options.afterFinishInternal = function(effect) {
          effect.element.addClassName(effect.options.style);
          effect.transforms.each(function(transform) {
            effect.element.style[transform.style] = '';
          });
        };
      }
    }
    this.start(options);
  },

  setup: function(){
    function parseColor(color){
      if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
      color = color.parseColor();
      return $R(0,2).map(function(i){
        return parseInt( color.slice(i*2+1,i*2+3), 16 );
      });
    }
    this.transforms = this.style.map(function(pair){
      var property = pair[0], value = pair[1], unit = null;

      if (value.parseColor('#zzzzzz') != '#zzzzzz') {
        value = value.parseColor();
        unit  = 'color';
      } else if (property == 'opacity') {
        value = parseFloat(value);
        if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
          this.element.setStyle({zoom: 1});
      } else if (Element.CSS_LENGTH.test(value)) {
          var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
          value = parseFloat(components[1]);
          unit = (components.length == 3) ? components[2] : null;
      }

      var originalValue = this.element.getStyle(property);
      return {
        style: property.camelize(),
        originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
        targetValue: unit=='color' ? parseColor(value) : value,
        unit: unit
      };
    }.bind(this)).reject(function(transform){
      return (
        (transform.originalValue == transform.targetValue) ||
        (
          transform.unit != 'color' &&
          (isNaN(transform.originalValue) || isNaN(transform.targetValue))
        )
      );
    });
  },
  update: function(position) {
    var style = { }, transform, i = this.transforms.length;
    while(i--)
      style[(transform = this.transforms[i]).style] =
        transform.unit=='color' ? '#'+
          (Math.round(transform.originalValue[0]+
            (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
          (Math.round(transform.originalValue[1]+
            (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
          (Math.round(transform.originalValue[2]+
            (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
        (transform.originalValue +
          (transform.targetValue - transform.originalValue) * position).toFixed(3) +
            (transform.unit === null ? '' : transform.unit);
    this.element.setStyle(style, true);
  }
});

Effect.Transform = Class.create({
  initialize: function(tracks){
    this.tracks  = [];
    this.options = arguments[1] || { };
    this.addTracks(tracks);
  },
  addTracks: function(tracks){
    tracks.each(function(track){
      track = $H(track);
      var data = track.values().first();
      this.tracks.push($H({
        ids:     track.keys().first(),
        effect:  Effect.Morph,
        options: { style: data }
      }));
    }.bind(this));
    return this;
  },
  play: function(){
    return new Effect.Parallel(
      this.tracks.map(function(track){
        var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
        var elements = [$(ids) || $$(ids)].flatten();
        return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
      }).flatten(),
      this.options
    );
  }
});

Element.CSS_PROPERTIES = $w(
  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
  'fontSize fontWeight height left letterSpacing lineHeight ' +
  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
  'right textIndent top width wordSpacing zIndex');

Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

String.__parseStyleElement = document.createElement('div');
String.prototype.parseStyle = function(){
  var style, styleRules = $H();
  if (Prototype.Browser.WebKit)
    style = new Element('div',{style:this}).style;
  else {
    String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
    style = String.__parseStyleElement.childNodes[0].style;
  }

  Element.CSS_PROPERTIES.each(function(property){
    if (style[property]) styleRules.set(property, style[property]);
  });

  if (Prototype.Browser.IE && this.include('opacity'))
    styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);

  return styleRules;
};

if (document.defaultView && document.defaultView.getComputedStyle) {
  Element.getStyles = function(element) {
    var css = document.defaultView.getComputedStyle($(element), null);
    return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
      styles[property] = css[property];
      return styles;
    });
  };
} else {
  Element.getStyles = function(element) {
    element = $(element);
    var css = element.currentStyle, styles;
    styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
      results[property] = css[property];
      return results;
    });
    if (!styles.opacity) styles.opacity = element.getOpacity();
    return styles;
  };
}

Effect.Methods = {
  morph: function(element, style) {
    element = $(element);
    new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
    return element;
  },
  visualEffect: function(element, effect, options) {
    element = $(element);
    var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
    new Effect[klass](element, options);
    return element;
  },
  highlight: function(element, options) {
    element = $(element);
    new Effect.Highlight(element, options);
    return element;
  }
};

$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
  'pulsate shake puff squish switchOff dropOut').each(
  function(effect) {
    Effect.Methods[effect] = function(element, options){
      element = $(element);
      Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
      return element;
    };
  }
);

$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
  function(f) { Effect.Methods[f] = Element[f]; }
);

Element.addMethods(Effect.Methods);function changeColor ( id, color )
{
	$(id).style.color = color;

} /* On definit ici les differents styles de clustering */
 var styles = [[
	{
        url: '../images/people35.png',
        height: 35,
        width: 35,
        opt_anchor: [16, 0],
        opt_textColor: '#FF00FF'
      },
      {
        url: '../images/people45.png',
        height: 45,
        width: 45,
        opt_anchor: [24, 0],
        opt_textColor: '#FF0000'
      },
      {
        url: '../images/people55.png',
        height: 55,
        width: 55,
        opt_anchor: [32, 0]
      }],
      [{
        url: '../images/conv30.png',
        height: 27,
        width: 30,
        anchor: [3, 0],
        textColor: '#FF00FF'
      },
      {
        url: '../images/conv40.png', 
        height: 36,
        width: 40,
        opt_anchor: [6, 0],
        opt_textColor: '#FF0000'
      },
      {
        url: '../images/conv50.png',
        width: 50,
        height: 45,
        opt_anchor: [8, 0]
      }],
      [{
        url: '../images/heart30.png',
        height: 26,
        width: 30,
        opt_anchor: [4, 0],
        opt_textColor: '#FF00FF'
      },
      {
        url: '../images/heart40.png', 
        height: 35,
        width: 40,
        opt_anchor: [8, 0],
        opt_textColor: '#FF0000'
      },
      {
        url: '../images/heart50.png',
        width: 50,
        height: 44,
        opt_anchor: [12, 0]
      }]];
var basicUrlIcon = "http://www.mapize.com/generator/generatorSource/images_mapize/orangeMarker_Mapize.png";
var basicIconWidth = 32;
var basicIconHeigth = 32;


// var urlLoader = "http://www.mapize.com/generator/generatorSource/images_mapize/loading_Mapize.gif";
var urlLoader = "http://www.mapize.com/generator/generatorSource/images_mapize/mapize_loading.gif";


var expressionId = new RegExp("^[0-9]*$"); 
var expressionNew = new RegExp("New_*"); 
var expressionCallBack = new RegExp(".*|#|.*"); 
	
	
var idDesignSidebarVertical = 6;
var idDesignSidebarElementVertical  = 7;

var idDesignSidebarHorizontal= 1;
var idDesignSidebarElementHorizontal = 4;

var idSearchEngineVertical  = 1;

var versionMobileDistance = 0.01;


/*Configuration des modules de la sidebar*/
var sidebarParameters = new Array ();
sidebarParameters["Search"] = new Array();
sidebarParameters["Search"]["title"] = "Search Engine";
sidebarParameters["Search"]["subtitle"] = "&nbsp;";

sidebarParameters["HTML"] = new Array();
sidebarParameters["HTML"]["title"] = "HTML Container";
sidebarParameters["HTML"]["subtitle"] = "&nbsp;";

sidebarParameters["Category"] = new Array();
sidebarParameters["Category"]["title"] = "Category Management";
sidebarParameters["Category"]["subtitle"] = "&nbsp;";

/*Clustering Image */
var clusteringGeneral;
var firstIconImageTemp = "http://chart.apis.google.com/chart?chf=bg,s,65432100&cht=it&chs=20x20&chco=27E800,27E800,000000&chx=FFFFFF&ext=.png";
var secondIconImageTemp = "http://chart.apis.google.com/chart?chf=bg,s,65432100&cht=it&chs=30x30&chco=FEAA00,FEAA00,000000&chx=FFFFFF&ext=.png";
var thirdIconImageTemp = "http://chart.apis.google.com/chart?chf=bg,s,65432100&cht=it&chs=40x40&chco=B9121B,B9121B,000000&chx=FFFFFF&ext=.png";
var clusterMarkerTitleTemp = "Voir le detail";

/* MAP INITIALISATION */
var initTypeMap;
var zoomPosition;
var initZoom = 4;
var initLat = 44.28269110344576;
var initLng =  23.692618700000008;
var allTypes= new Array();
var earthAngle;


// Execution des scripts au chargement de la page


	window.onload = function() 
	{ 
		for(i=0; i<FuncOL.length; i++) 
		{
			FuncOL[i]();
		} 
	}			
	
	
	
	
	
	
/***************************** PAGER JAVASCRIPT PARAMETRE : le numero de la page a afficher, l'id du spreadsheete en general et l'id du footer pour pouvoir laisser visible celui-ci **********************************/	

/*Methode utilisee pour changer de page dans les spreadsheet */
function changerPageSpreadSheet ( page, idSpreadSheet, idFooter, activeClass, nonActiveClass, typeElementFooter  )
{
	/*Cache toutes les pages puis affiche la bonne */
	var pages = document.getElementById(idSpreadSheet).getElementsByTagName('DIV'); 

	for(var i=0;i<pages.length;i++)
	{
		pages[i].style.display="none";

	}
	
	
	var visibleDiv = document.getElementById(idSpreadSheet+'_'+page).getElementsByTagName('DIV'); 
	
	for(var i=0;i<visibleDiv.length;i++)
	{
		visibleDiv[i].style.display="";
		
		
	}
	 document.getElementById(idSpreadSheet+'_'+page).style.display=""; 

	 
	 
	 
	 
	/*Si l'idFooter est renseigne */
	if ( idFooter )
	{
		if  ( !typeElementFooter )
			typeElementFooter = "DIV";
		
		
		var footer = document.getElementById(idFooter).getElementsByTagName(typeElementFooter); 

		for(var i=0;i<footer.length;i++)
		{
			footer[i].style.display="";
			
			if ( nonActiveClass )
				footer[i].className=nonActiveClass;
		}
		
		document.getElementById(idFooter).style.display=""; 
		if ( activeClass )
			 document.getElementById(idFooter+'_'+page).className=activeClass;
	}
	
	
	

}

	
	
/***************************** Change le style d'un element par rapport a son id **********************************/	
function changeClass ( id, className )
{
	if ( document.getElementById(id) )
		document.getElementById(id).className= className; 
		
}
	

/***************************** function load**********************************/	
var loadingButtonValue;
var isLoading = false;	
/*Remplace le boutton par le loader, garde en memoire la valeur de celui ci */	
function initLoading ( id )
{
	loadingCount++;
	
	
	if ( !isLoading )
	{
		loadingButtonValue = $(id).innerHTML;
		$(id).innerHTML = "<img src=\""+urlLoader+"\" alt=\"\" >";
	}
	
	isLoading = true;
}

/*Remplace le loader par le boutton avec la valeur mise en memoire à l'aide de la fonction initLoading */	
function endLoading ( id )
{
	loadingCount--;
	
	if ( loadingCount <= 0 )
	{
		isLoading = false;
		$(id).innerHTML = loadingButtonValue;
	}
}	
	

/*Remplace le boutton par le loader, garde en memoire la valeur de celui ci */	
var loadingCount = 0;
function initFrontLoading ()
{
	try
	{
		$("loader").style.display = "block";
		loadingCount++;
	}
	catch (err){};

}

/*Remplace le loader par le boutton avec la valeur mise en memoire à l'aide de la fonction initLoading */	
function endFrontLoading ( )
{
	loadingCount--;
	
	if ( loadingCount == 0 )
	{
		try
		{
			$("loader").style.display = "none";
		}
		catch (err){};
	}

}		

/******************* deroule ou enroule le menu  *****************************/
function deroulerMenu ( id, first, last, checkBox, withoutEffect )
{

		/*On deroule et on enroule par rapport a une checkbox */
		if ( checkBox )
		{
			/*On deroule */
			if ( $F(id+"Etat") == 0 && $(checkBox).checked)
			{
				if ( withoutEffect )
					$(id).style.display="block";
				else
					new Effect.SlideDown(id);
					
					
				$("developper_"+id).innerHTML = last;
				
				$(id+"Etat").value=1;
			}/*On enroule */
			else if ( $F(id+"Etat") != 0 && !$(checkBox).checked)
			{
				
				
				if ( withoutEffect )
					$(id).style.display="none";
				else
					new Effect.SlideUp(id);
				
				
				$("developper_"+id).innerHTML = first 
			
				$(id+"Etat").value=0;
				
			}
			
		}
		else
		{
		
			/*On deroule */
			if ( $F(id+"Etat") == 0 )
			{
				if ( withoutEffect )
					$(id).style.display="block";
				else
					new Effect.SlideDown(id);
					
					
				$("developper_"+id).innerHTML = last;
				
				$(id+"Etat").value=1;
			}/*On enroule */
			else
			{
			
			
					
				if ( withoutEffect )
					$(id).style.display="none";
				else
					new Effect.SlideUp(id);
				
				
				$("developper_"+id).innerHTML = first 
				
				$(id+"Etat").value=0;
			}
		}

}
 /**
*
*  AJAX IFRAME METHOD (AIM) PERMET D'UPLODER DES FICHIERS SANS RECHARGEMETN DE PAGE 
*
**/
 
AIM = {
 
	frame : function(c) {
 
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);
 
		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}
 
		return n;
	},
 
	form : function(f, name) {
		f.setAttribute('target', name);
	},
 
	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},
 
	loaded : function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}
 
		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}
	}
 
}


/***************************** EQUIVALENT DU IS_ARRAY EN PHP **********************************/	
	
  function is_array(input){
    return typeof(input)=='object'&&(input instanceof Array);
  }




	
/***************************** EQUIVALENT DU PRINT_R EN PHP **********************************/	
	
function print_r(obj) 
{
	  win_print_r = window.open('about:blank', 'win_print_r');
  win_print_r.document.write('<html><body>');
  r_print_r(obj, win_print_r);
  win_print_r.document.write('</body></html>');

/* 
 // popContent( "content" ) ; */
	

 }

 function r_print_r(theObj, win_print_r)
{
	if(theObj.constructor == Array ||theObj.constructor == Object)
	{
		if (win_print_r == null)
			win_print_r = window.open('about:blank', 'win_print_r');
	}
	
	for(var p in theObj)
	{
		if(theObj[p].constructor == Array||	theObj[p].constructor == Object)
		{
			win_print_r.document.write("<li>["+p+"] =>"+typeof(theObj)+"</li>");
			win_print_r.document.write("<ul>")
			r_print_r(theObj[p], win_print_r);
			win_print_r.document.write("</ul>")
		} else 
		{
			win_print_r.document.write("<li>["+p+"] =>"+theObj[p]+"</li>");
		}
	}
	
	win_print_r.document.write("</ul>")
}


/***************************** LES POP UP AVEC HTML OU AVEC URL**********************************/		
	
function popURL(url) 
{

	newwindow=window.open(url,'name','height=500,width=500');
	if (window.focus) {newwindow.focus()}
	return false;
}

	
	
function popContent( content ) 
{
	/*On cree un fichier html ou on ecrit le resultat de la pop up */
	var url = "c:\\testfile.txt"
	creerFichier ( url, content )


	newwindow=window.open(url,'Test','height=500,width=500');
	if (window.focus) {newwindow.focus()}
	return false;
}

	

/***************************** CREE UN FICHIER AVEC SON CONTENU**********************************/			
function creerFichier ( url, content )
{
	var file = new ActiveXObject("Scripting.FileSystemObject");alert ('dd');
	var a = file.CreateTextFile(url, true);
	a.WriteLine(content);
	a.Close();
alert ('dd');
}



/***************************** comme addslashes php**********************************/	
function addslashes(ch) 
{
	ch = ch.replace(/\\/g,"\\\\")
	ch = ch.replace(/\'/g,"\\'")
	ch = ch.replace(/\"/g,"\\\"")
	return ch;
}



/***************************** comme htmlentities php**********************************/	
function htmlentities(texte) {

texte = texte.replace(/"/g,'&quot;'); // 34 22
texte = texte.replace(/&/g,'&amp;'); // 38 26
texte = texte.replace(/\'/g,'&#39;'); // 39 27
texte = texte.replace(/</g,'&lt;'); // 60 3C
texte = texte.replace(/>/g,'&gt;'); // 62 3E
texte = texte.replace(/\^/g,'&circ;'); // 94 5E
texte = texte.replace(/‘/g,'&lsquo;'); // 145 91
texte = texte.replace(/’/g,'&rsquo;'); // 146 92
texte = texte.replace(/“/g,'&ldquo;'); // 147 93
texte = texte.replace(/”/g,'&rdquo;'); // 148 94
texte = texte.replace(/•/g,'&bull;'); // 149 95
texte = texte.replace(/–/g,'&ndash;'); // 150 96
texte = texte.replace(/—/g,'&mdash;'); // 151 97
texte = texte.replace(/˜/g,'&tilde;'); // 152 98
texte = texte.replace(/™/g,'&trade;'); // 153 99
texte = texte.replace(/š/g,'&scaron;'); // 154 9A
texte = texte.replace(/›/g,'&rsaquo;'); // 155 9B
texte = texte.replace(/œ/g,'&oelig;'); // 156 9C
texte = texte.replace(//g,'&#357;'); // 157 9D
texte = texte.replace(/ž/g,'&#382;'); // 158 9E
texte = texte.replace(/Ÿ/g,'&Yuml;'); // 159 9F
// texte = texte.replace(/ /g,'&nbsp;'); // 160 A0
texte = texte.replace(/¡/g,'&iexcl;'); // 161 A1
texte = texte.replace(/¢/g,'&cent;'); // 162 A2
texte = texte.replace(/£/g,'&pound;'); // 163 A3
//texte = texte.replace(/ /g,'&curren;'); // 164 A4
texte = texte.replace(/¥/g,'&yen;'); // 165 A5
texte = texte.replace(/¦/g,'&brvbar;'); // 166 A6
texte = texte.replace(/§/g,'&sect;'); // 167 A7
texte = texte.replace(/¨/g,'&uml;'); // 168 A8
texte = texte.replace(/©/g,'&copy;'); // 169 A9
texte = texte.replace(/ª/g,'&ordf;'); // 170 AA
texte = texte.replace(/«/g,'&laquo;'); // 171 AB
texte = texte.replace(/¬/g,'&not;'); // 172 AC
texte = texte.replace(/­/g,'&shy;'); // 173 AD
texte = texte.replace(/®/g,'&reg;'); // 174 AE
texte = texte.replace(/¯/g,'&macr;'); // 175 AF
texte = texte.replace(/°/g,'&deg;'); // 176 B0
texte = texte.replace(/±/g,'&plusmn;'); // 177 B1
texte = texte.replace(/²/g,'&sup2;'); // 178 B2
texte = texte.replace(/³/g,'&sup3;'); // 179 B3
texte = texte.replace(/´/g,'&acute;'); // 180 B4
texte = texte.replace(/µ/g,'&micro;'); // 181 B5
texte = texte.replace(/¶/g,'&para'); // 182 B6
texte = texte.replace(/·/g,'&middot;'); // 183 B7
texte = texte.replace(/¸/g,'&cedil;'); // 184 B8
texte = texte.replace(/¹/g,'&sup1;'); // 185 B9
texte = texte.replace(/º/g,'&ordm;'); // 186 BA
texte = texte.replace(/»/g,'&raquo;'); // 187 BB
texte = texte.replace(/¼/g,'&frac14;'); // 188 BC
texte = texte.replace(/½/g,'&frac12;'); // 189 BD
texte = texte.replace(/¾/g,'&frac34;'); // 190 BE
texte = texte.replace(/¿/g,'&iquest;'); // 191 BF
texte = texte.replace(/À/g,'&Agrave;'); // 192 C0
texte = texte.replace(/Á/g,'&Aacute;'); // 193 C1
texte = texte.replace(/Â/g,'&Acirc;'); // 194 C2
texte = texte.replace(/Ã/g,'&Atilde;'); // 195 C3
texte = texte.replace(/Ä/g,'&Auml;'); // 196 C4
texte = texte.replace(/Å/g,'&Aring;'); // 197 C5
texte = texte.replace(/Æ/g,'&AElig;'); // 198 C6
texte = texte.replace(/Ç/g,'&Ccedil;'); // 199 C7
texte = texte.replace(/È/g,'&Egrave;'); // 200 C8
texte = texte.replace(/É/g,'&Eacute;'); // 201 C9
texte = texte.replace(/Ê/g,'&Ecirc;'); // 202 CA
texte = texte.replace(/Ë/g,'&Euml;'); // 203 CB
texte = texte.replace(/Ì/g,'&Igrave;'); // 204 CC
texte = texte.replace(/Í/g,'&Iacute;'); // 205 CD
texte = texte.replace(/Î/g,'&Icirc;'); // 206 CE
texte = texte.replace(/Ï/g,'&Iuml;'); // 207 CF
texte = texte.replace(/Ð/g,'&ETH;'); // 208 D0
texte = texte.replace(/Ñ/g,'&Ntilde;'); // 209 D1
texte = texte.replace(/Ò/g,'&Ograve;'); // 210 D2
texte = texte.replace(/Ó/g,'&Oacute;'); // 211 D3
texte = texte.replace(/Ô/g,'&Ocirc;'); // 212 D4
texte = texte.replace(/Õ/g,'&Otilde;'); // 213 D5
texte = texte.replace(/Ö/g,'&Ouml;'); // 214 D6
texte = texte.replace(/×/g,'&times;'); // 215 D7
texte = texte.replace(/Ø/g,'&Oslash;'); // 216 D8
texte = texte.replace(/Ù/g,'&Ugrave;'); // 217 D9
texte = texte.replace(/Ú/g,'&Uacute;'); // 218 DA
texte = texte.replace(/Û/g,'&Ucirc;'); // 219 DB
texte = texte.replace(/Ü/g,'&Uuml;'); // 220 DC
texte = texte.replace(/Ý/g,'&Yacute;'); // 221 DD
texte = texte.replace(/Þ/g,'&THORN;'); // 222 DE
texte = texte.replace(/ß/g,'&szlig;'); // 223 DF
texte = texte.replace(/à/g,'&aacute;'); // 224 E0
texte = texte.replace(/á/g,'&aacute;'); // 225 E1
texte = texte.replace(/â/g,'&acirc;'); // 226 E2
texte = texte.replace(/ã/g,'&atilde;'); // 227 E3
texte = texte.replace(/ä/g,'&auml;'); // 228 E4
texte = texte.replace(/å/g,'&aring;'); // 229 E5
texte = texte.replace(/æ/g,'&aelig;'); // 230 E6
texte = texte.replace(/ç/g,'&ccedil;'); // 231 E7
texte = texte.replace(/è/g,'&egrave;'); // 232 E8
texte = texte.replace(/é/g,'&eacute;'); // 233 E9
texte = texte.replace(/ê/g,'&ecirc;'); // 234 EA
texte = texte.replace(/ë/g,'&euml;'); // 235 EB
texte = texte.replace(/ì/g,'&igrave;'); // 236 EC
texte = texte.replace(/í/g,'&iacute;'); // 237 ED
texte = texte.replace(/î/g,'&icirc;'); // 238 EE
texte = texte.replace(/ï/g,'&iuml;'); // 239 EF
texte = texte.replace(/ð/g,'&eth;'); // 240 F0
texte = texte.replace(/ñ/g,'&ntilde;'); // 241 F1
texte = texte.replace(/ò/g,'&ograve;'); // 242 F2
texte = texte.replace(/ó/g,'&oacute;'); // 243 F3
texte = texte.replace(/ô/g,'&ocirc;'); // 244 F4
texte = texte.replace(/õ/g,'&otilde;'); // 245 F5
texte = texte.replace(/ö/g,'&ouml;'); // 246 F6
texte = texte.replace(/÷/g,'&divide;'); // 247 F7
texte = texte.replace(/ø/g,'&oslash;'); // 248 F8
texte = texte.replace(/ù/g,'&ugrave;'); // 249 F9
texte = texte.replace(/ú/g,'&uacute;'); // 250 FA
texte = texte.replace(/û/g,'&ucirc;'); // 251 FB
texte = texte.replace(/ü/g,'&uuml;'); // 252 FC
texte = texte.replace(/ý/g,'&yacute;'); // 253 FD
texte = texte.replace(/þ/g,'&thorn;'); // 254 FE
texte = texte.replace(/ÿ/g,'&yuml;'); // 255 FF
return texte;
}

/* equivalent en javascript de trim php */
function trim (myString)
{
	return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
} 



/* donne l'equivalent d'un zoom gmap pour gearth */
function gmapToGearthZoom(geocodeZoom)
{
	
	
	if(geocodeZoom >= 17) /* good */
		return 800;
		
	if(geocodeZoom == 16) /* good */
		return 1000;
	
	if(geocodeZoom == 15) 
		return 2000;
		
	if(geocodeZoom == 14) 
		return 3000;
		
	if(geocodeZoom == 13) 
		return 4000;	
		
	if(geocodeZoom == 12) 
		return 5000;
	
	if(geocodeZoom == 11)
		return 6000;
	
	if(geocodeZoom == 10) 
		return 7000;
		
	if(geocodeZoom == 9) 
		return 8000;
		
	if(geocodeZoom == 8) 
		return 9000;
		
	if(geocodeZoom == 7) 
		return 10000;
		
	if(geocodeZoom == 6) /* good */
		return 300000;

	if(geocodeZoom == 5) 
		return 1000000;
		
	if(geocodeZoom == 4) /* good */
		return 2000000;
	
	if(geocodeZoom <= 2) /* good */
		return 5000000;

}


var regExpBeginning = /^\s+/;

var regExpEnd = /\s+$/;  

// Supprime les espaces inutiles en début et fin de la chaîne passée en paramètre.

function trim(aString) {

    return aString.replace(regExpBeginning, "").replace(regExpEnd, "");
}

 

// Supprime les espaces inutiles en début de la chaîne passée en paramètre.

function ltrim(aString) {

    return aString.replace(regExpBeginning, "");
}

 

// Supprime les espaces inutiles en fin de la chaîne passée en paramètre.

function rtrim(aString) {

    return aString.replace(regExpEnd, "");
}



/*Deploie un menu*/
var menuEtatDeployer = true;
function deployerReduire ( sousMenus, $this, firstTexte, lastTexte )
{
	var display = "none";
	
	if ( this.menuEtatDeployer )
		display = "block";

	for ( var i = 0; i<sousMenus.length; i++ )
	{
		$(sousMenus[i]).style.display = display;
	}

	if ( this.menuEtatDeployer )
	{
		$this.innerHTML = lastTexte;
		this.menuEtatDeployer = false;	
	}
	else
	{
		$this.innerHTML = firstTexte;
		this.menuEtatDeployer = true;	
	}
		
	
}



/***************************** Infobulle de confirmation de suppression **********************************/	

function openInfobulleDeleteModule ( $this, id, type, texte )
{
	var content = $("deleteModuleInfobulle").innerHTML;
	
	content = content.replace(/__id__/gi, id);	
	content = content.replace(/__type__/gi, type);	
	content = content.replace(/__texte__/gi, texte);	
	
	
	$("miniBoxTemp").innerHTML = 	content;
	openbox ( "miniBoxTemp", this.mousePosY +5, this.mousePosX - 43 );

}

function openInfobulleConfirmation ( $this, function1, function2, texte )
{
	var content = $("infobulleConfirmation").innerHTML;
	
	content = content.replace(/__function1__/gi, function1);	
	content = content.replace(/__function2__/gi, function2);	
	content = content.replace(/__texte__/gi, texte);	
	
	
	$("miniBoxTemp").innerHTML = 	content;
	openbox ( "miniBoxTemp", this.mousePosY +5, this.mousePosX - 43 );

}


function deleteModule ( id, type )
{
	
	closebox ( 'miniBoxTemp' );
	switch ( type )
	{
		case "Search" :
			deleteSearchEngine( id );
		break;
		
		case "HTML" :
			deleteHtmlContainer( id );
		break;
		
		case "Category" :
			deleteCategoryModule( id );
		break;
		
		case "CategoryContent" :
			ajaxDeleteCategorie( id );
		break;
		
		case "Onglet" :
			var id_idTab_nb = id.split ("|#|");
		
			changerPageSpreadSheet('1', 'onglets_'+id_idTab_nb[0], 'footerOnglets_'+id_idTab_nb[0],'ongletTitleActif left', 'ongletTitle left' );
			
			document.getElementById('footerOnglets_'+id_idTab_nb[0]).removeChild(document.getElementById('footerOnglets_'+id_idTab_nb[0]+'_'+id_idTab_nb[2]));
			
			// document.getElementById('footerOnglets_'+id_idTab_nb[0]+'_'+id_idTab_nb[2]).style.display='none';
			ajaxDeleteTabContent( id_idTab_nb[0], id_idTab_nb[1] );
			
	
		break;
		
		case "Marker" :
			ajaxDeleteMarker( id );
			try
			{
				this.reloadMarkersTable();
			}
			catch (err){}
		break;
		
		
		case "DocumentContent" :
			initLoading ( 'mainLoading' );
			$("ficSelected").value = id;
			document.formSuppressionDocument.submit();
			
		break;
		
		case "KMLContent" :
			initLoading ( 'mainLoading' );
			$("ficSelected").value = id;
			document.formSuppressionKML.submit();
			
		break;
		
		case "Sidebar" :
			initLoading ( 'mainLoading' );
			supprimerSideBarre ( id );
			
		break;
		
		case "Banner" :
			initLoading ( 'mainLoading' );
			supprimerBanner ( id );
			
		break;
		
		case "Keyword" :
			initLoading ( 'mainLoading' );
			
			var id_nb = id.split ("|#|");
			supprimerKeyword ( id_nb[0], id_nb[1] );
			
		break;
		
	}
	

}


/***************************** Infobulle de confirmation de changement d'etat**********************************/	

function openInfobulleChangeEtatModule ( $this, id, type, texte )
{
	var content = $("changeEtatInfobulle").innerHTML;
	
	content = content.replace(/__id__/gi, id);	
	content = content.replace(/__type__/gi, type);	
	content = content.replace(/__texte__/gi, texte);	
	
	
	$("miniBoxTemp").innerHTML = 	content;
	openbox ( "miniBoxTemp", this.mousePosY +5, this.mousePosX - 43 );

}


function changeEtatModule ( id, type, etat )
{
	
	closebox ( 'miniBoxTemp' );
	switch ( type )
	{
		case "CategoryContent" :
			ajaxChangeEtatCategorie( id, etat );
		break;
		
		case "KmlContent" :
			ajaxChangeEtatKml( id, etat );
		break;

	}
	
}


/***************************** Infobulle de confirmation de changement d'etat du clustering**********************************/	

function openInfobulleChangeEtatClusteringModule ( $this, id, type, texte )
{
	var content = $("changeEtatClusteringInfobulle").innerHTML;
	
	content = content.replace(/__id__/gi, id);	
	content = content.replace(/__type__/gi, type);	
	content = content.replace(/__texte__/gi, texte);	
	
	
	$("miniBoxTemp").innerHTML = 	content;
	openbox ( "miniBoxTemp", this.mousePosY +5, this.mousePosX - 43 );

}



function changeClusteringModule ( id, type, etat )
{
	
	closebox ( 'miniBoxTemp' );
	switch ( type )
	{
		case "CategoryContent" :
			ajaxChangeClusteringCategorie( id, etat );
		break;

	}
	
}

/************** verfie la securite d'un mot de pass ********************/
function passwordStrength(A)
{
	var D=new Array();
	var C=0;
	if(A.length>6)
		C++

	if((A.match(/[a-z]/))&&(A.match(/[A-Z]/)))
		C++;

	if(A.match(/\d+/))
		C++;

	if(A.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/))
		C++;
	
	if(A.length>12)
		C++;

	var B=document.getElementById("passwordquality").getElementsByTagName("td");
	
	for(i=0;i<B.length;i++)
	{
		if(document.getElementById("passwordquality_q"+i)!=null)
			document.getElementById("passwordquality_q"+i).style.display="none";
		
		B[i].className="";
		
		if(C>=i&&A!="")
			B[i].className="q"+C;
		
	}
	
	if(A!="")
		document.getElementById("passwordquality_q"+C).style.display="";
	
}

/* compare 2 elements et en affiche une erreur selon si le resultat est different */
function findError ( v1, v2, idError )
{
	if ( v1 != v2 )
		$(idError).style.display = "block";
	else
		$(idError).style.display = "none";

}/************************************************************************************************************************
*																														*
*																														*
*										FONCTION  ET OPERATION UTILE SUR LES MAPS										*													
*																														*
*																														*
*																														*
************************************************************************************************************************/

/*Sont stockés tous les evenement avec l'id de leurs parents*/
var arrayIdMarker_GEvent = new Array();






/***************************************Centre la map par rapport à un point ou sur un marker************************************************/
function centrerMap ( type, value, zoom )
{
	switch ( type )
	{
		case "LatLng" :
			this.map.setCenter ( value );
		break;
		
		case "Marker" :
			
			this.map.setCenter ( value.getLatLng()  );
			
		break;
	
	}
	
	if ( zoom )
		this.map.setZoom ( zoom  );


}

/***************************************Prend en parametre un marker, une liste d'option et l'affiche sur la map**************************************************************/
function placerMarker ( marker, parameters )
{
	
	this.map.addOverlay( marker );	
	
	//Liste des options
	if ( parameters )
	{
		if ( parameters["center"] )
		{
			
			if ( parameters["zoom"] )
				centrerMap ( "Marker", marker, parameters["zoom"] );
			else
				centrerMap ( "Marker", marker );
				
			
		}
			
		
		
		
		
			
	}		
	

}



/***************************************Prend en parametre l'url de l'image de l'icon, l'url de son ombre et sa taille => retourne une gIcon**************************************************************/
var preloadedImages = new Array();
function makeIcon ( urlImage, urlShadow, width, height )
{

	var icon = new GIcon();
	icon.image = urlImage;
	icon.shadow = urlShadow;
	
	if ( !preloadedImages[urlImage] )
	{
		var myIcon= new Image(); 
		myIcon.src=urlImage; 
		preloadedImages[urlImage] = myIcon;
	}
	
	
	if ( !width )
		width =	preloadedImages[urlImage].width;
	
	if ( !height )
		height =preloadedImages[urlImage].height;
		
	if ( width == 0 )
		width = this.basicIconWidth;
			
	if ( height == 0 )
		height = this.basicIconHeigth;
	
	/* place la petite crois en bas a gauche */
	if ( width > height )
	{
		icon.iconAnchor=new GPoint(1, parseInt (height)+1);
		// icon.infoWindowAnchor=new GPoint(parseInt (width), 1);
	}
	else/* place la petite crois au en bas au milieux  */
	{
		icon.iconAnchor=new GPoint(parseInt (width)/2, parseInt (height)+1);
		// icon.infoWindowAnchor=new GPoint(parseInt (width), 1);
	}
				
	icon.iconSize  = new GSize( parseInt (width), parseInt (height));
	// icon.iconAnchor  = new GPoint( parseInt (width)/2, parseInt (height)/2);
	


	// var icon =new GIcon();
	// icon.image = urlImage;
	// icon=new GPoint(6, 20);
	// icon.infoWindowAnchor=new GPoint(6, 1);
	
	return icon;

}


/***************************************Prend en parametre un marker, une Url et lui affecte l'icon**************************************************************/
function changeIcon ( marker, urlImage )
{
	marker.setImage ( urlImage );
}



/***************************************Permet de placer un element, calque sur la map****************************************************************
																	 								   
********************************************************************************************************************************************************************************/							function placerElement ( elem )
{
	this.map.addOverlay( elem );																																				   
}


/***************************************Permet d'enlever un element, calque sur la map****************************************************************
																	 								   
********************************************************************************************************************************************************************************/							function enleverElement ( elem )
{
	this.map.removeOverlay( elem );																																				   
}

/***************************************Prend en parametre un marker, une liste d'option et le supprime de la map****************************************************************
	parameters : 	center ( true or false ) : centre la map sur le marker																			 								   
																																											   
********************************************************************************************************************************************************************************/
function enleverMarker ( marker, parameters )
{
	
	enleverElement ( marker );
	
	//Liste des options
	if ( parameters )
	{
		if ( parameters["center"] )
			centrerMap ( "Marker", marker );
	}		
	

}

/***************************************Creer un marker sans pour autant le placer sur la map***********************************************************************************
																																											   
	infoWindowParameters : 	Event ( true or false ) : click, mouseover																										   
							content : contenu de l'infoWindows ( type : objet ou string )																					   
							type :simple ou multi (avec tabs)																				 								   
							isOpen :( true or false )	

	markerParameters : 		title : titre du marker lors du passage de la souris sur celui ci	
							draggable  : drag & drop active ou non
							icon : icon de celui ci
																																											   
********************************************************************************************************************************************************************************/



function createMarker (lat, lng , markerParameters, infoWindowParameters )
{
		
	
	/*Si l'icon n'es pas deja passe en parametre on lui cree une icon*/
	if ( !markerParameters["icon"] )
	{

	
		// var widthIcon = this.basicIconWidth;
		// var heightIcon = this.basicIconHeigth;
		
		var widthIcon;
		var heightIcon;
		
		
		var urlIcon = this.basicIconUrl;
		
		if (  markerParameters["iconUrl"] )
			urlIcon = markerParameters["iconUrl"];
			
		if (  markerParameters["iconHeight"] )
			heightIcon = markerParameters["iconHeight"];
			
		if (  markerParameters["iconWidth"] )
			widthIcon = markerParameters["iconWidth"];

		markerParameters["icon"] = makeIcon (  urlIcon, "", widthIcon, heightIcon );
	}
	
	

	
	var marker = new GMarker( new GLatLng ( parseFloat (lat),  parseFloat (lng) ),markerParameters );

	//Liste des options
	
		
	
	if ( infoWindowParameters )
	{	
	
		
	// alert( infoWindowParameters["click"] );
		
		//Ouverture de l'infowindows grace au click sur le marker
		if ( infoWindowParameters["click"] )
			addEventInfoWindow ( "new",  marker, "click", infoWindowParameters["type"], infoWindowParameters["content"], infoWindowParameters["isOpen"]  )
		
		if ( infoWindowParameters["mouseover"] )
			addEventInfoWindow ( "new", marker, "mouseover", infoWindowParameters["type"], infoWindowParameters["content"], infoWindowParameters["isOpen"]  )
			
			

	}		
	
	
	return marker;
	
}


/***************************Prend en parametre un marker le type d'event qu'on va faire le contenu de l'infoWindow et le type d'infowindo... **********************************
									isOpen (savoir si l'on ouvre tout de suite l'infowindow
********************************************************************************************************************************************************************************/




function addEventInfoWindow ( id, marker, event, type, content, isOpen, myFunction )
{	
// alert (type+"                "+content );
	var myEvent;
	/*On supprime l'ancien evenement*/
	if ( this.arrayIdMarker_GEvent[id] )
		GEvent.removeListener ( this.arrayIdMarker_GEvent[id] )
	
	switch ( type )
	{
		case "simple" :
			
			myEvent = GEvent.addListener(marker, event, function() 
			{
				currentIdMarker = id;
				marker.openExtInfoWindow(map, "mainInfobulle", content, {beakOffset: 3});


			});
					
						
			if ( isOpen )
			{	
				marker.openExtInfoWindow(map, "mainInfobulle", content, {beakOffset: 3});
				currentIdMarker = id;
			}	
					

		break;
		
		
		case "normal" :

			myEvent = GEvent.addListener(marker, event, function() 
			{

				marker.openInfoWindowHtml( content );

			});	
			
			try	
			{
				if ( isOpen )
					marker.openInfoWindowHtml(  content );
			}
			catch ( err ) { }
			
			
		break;		
		
		case "map" :

			myEvent = GEvent.addListener(marker, event, function() 
			{

				map.openInfoWindowHtml( marker.getLatLng(), content );

			});	
			
			try	
			{
				if ( isOpen )
					map.openInfoWindowHtml( marker.getLatLng(), content );
			}
			catch ( err ) { }
				

			
			
			
			
		break;
		
		/*Ici content ===> [new GInfoWindowTab("Create","infoWindowHTML"), new GInfoWindowTab("Preview","")  ...] */
		case "multiTab" :

						
			myEvent = GEvent.addListener(marker, event, function () 
			{
			
				marker.openInfoWindowTabsHtml
				(
					
						
					content
				);

			});
			
			if ( isOpen )
				marker.openInfoWindowTabsHtml( content, {beakOffset: 3});
			
		break;
		
		
		case "function" :
		
			myEvent = GEvent.addListener(marker, event, function() 
			{
				
				myFunction;
			
			});	
		
	
		break;
		
		case "ajaxIW" :
		
			myEvent = GEvent.addListener(marker, event, function() 
			{
				ajaxGetInfoWindows ( content["id"], content["print"], content["partage"] );
				
				/*socialMarker*/
				if ( sociableMarkerTable [content["id"]] )
					afficherSocialElements ( content["id"] );
			
			});	
		
	
		break;
		
		case "simpleAndFunction" :
		
			myEvent = GEvent.addListener(marker, event, function() 
			{
				currentIdMarker = id;
				marker.openExtInfoWindow(map, "mainInfobulle", content, {beakOffset: 3});
				myFunction();
				
			});	
				
			if ( isOpen )
			{
				currentIdMarker = id;
				marker.openExtInfoWindow(map, "mainInfobulle", content, {beakOffset: 3});
				myFunction();	
			}	
				
		
				
	
		break;
		
		
	}

	
	return myEvent;

}




/***************************Prend en parametre un marker et les 3 fonctions à utilise au debut, pendant et à la fin du drag&drop **************************************/




function addEventDrag ( marker, beginDrag, onDrag, endDrag )
{	
 
	GEvent.addListener(marker, "dragstart", beginDrag );
	GEvent.addListener(marker, "drag", onDrag );
	GEvent.addListener(marker, "dragend", endDrag );


}





/**********************************************************************************Class MarkerClass ************************************************************************
								
********************************************************************************************************************************************************************************/



var MarkerClass = function ( marker, content, visible ) 
{ 

    // this.idMarker = idMarker;
    this.visible = visible;
    this.marker = marker;
    this.content = content;
	
} 




/***************************************Place street view dans une infofowindows*****************************************************************************************************************/


var idDivStreetView;
var centerStreetView;

function runStreetView ()
{
			
	try
	{
		document.getElementById( idDivStreetView ).innerHTML ="";
		var panorama = new GStreetviewPanorama(document.getElementById(idDivStreetView));
		panorama.setLocationAndPOV(centerStreetView, {yaw:80.5}); 

		GEvent.addListener(panorama, "error", function ( errorCode )
		{
				
			 document.getElementById(idDivStreetView).innerHTML ="There is no available Street View for this bus stop!";

		});
	}
	catch ( err ) {}
}


			

var geocodeLat;
var geocodeLng;
var geocodeZoom;
var tabAccuracy = new Array(2,4,6,10,13,14,16,16,17);
var geocodeFlag = true;
/***************************************Place geocode une adresse la map*****************************************************************************************************************/
function geocodeAdresse( lieu )
{
	geoCodeur.getLocations( lieu, function(response)
	{
			/* // document.getElementById("test").innerHTML += response.Status.code+"<BR />"; */
			if (response.Status.code == 200) 
			{ 
				 var place = response.Placemark[0];
			/*	 map.setCenter(new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]), 7);
			 */
				geocodeLat =  place.Point.coordinates[1];
				geocodeLng =  place.Point.coordinates[0];
				accuracy = place.AddressDetails.Accuracy;
				geocodeZoom = tabAccuracy[accuracy];
	
		
			}
			else
			{
				geocodeLat = false;
				geocodeLng = false;
			
			}

	});

}



/***************************************Depalce un marker sur la map prend en parametre le marker et sa position*****************************************************************************************************************/
function deplacerMarker ( marker, lat, lng )
{

	marker.setLatLng ( new GLatLng ( parseFloat (lat), parseFloat (lng) ) );

}


/***************************************Ouvre l'infobulle d'un marker*****************************************************************************************************************/
function openInfowindow ( objet, content )
{
	objet.openExtInfoWindow(map, "mainInfobulle", content, {beakOffset: 3});

}





/***************************************retourne une tab d'une infobulle *****************************************************************************************************************/
function getInfoWindowTab( title, content)
{
	return new GInfoWindowTab(title, content);

}




/***************************************ouvre une infobulle sur la map grace a sa latlng et son contenu *****************************************************************************************************************/
function openMapInfobulle( lat, lng, content)
{

	var latLng =  new GLatLng (lat, lng);
	map.openInfoWindowTabsHtml
	(	
		latLng,
		content
	);

}


/***************************************Dessine un cercle sur la map en fontion du centre et du rayon *****************************************************************************************************************/

function drawCircle(lat, lng, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa)
{

	var poly = createCircle(lat, lng, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa);
	placerElement ( poly );
	
	return poly;
	
}





/***************************************Dessine un cercle sur la map en fontion du centre et du rayon *****************************************************************************************************************/

function createCircle(lat, lng, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa)
{
	var center =  new GLatLng (lat, lng);

	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;

	//Loop 
	var points = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step)
	{
	var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
	points.push(pint);
	//bounds.extend(pint); //this is for fit function
	}
	points.push(points[0]); // Closes the circle, thanks Martin
	fillColor = fillColor||liColor||"#0055ff";
	liWidth = liWidth||2;
	var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
	
	
	return poly;
	
}







var arrayCategories_visibility = new Array ();
var allMarkers = new Array ();

/*cree la chaine de caractere en ajax qui va etre executer en javascript */
// function firstMarkersLoading (  c, i, p )
// {
	// var url = this.path+'/modules/mod01_markers/include/ajax/ajax_firstMarkersLoading.php';

	// $("bannerTop").innerHTML = "Debut";	
	// var params = 
			// { 	
				// idMap:this.idMap, 
				// clusteringGeneral:c,		
				// imprimer:i,	
				// paratager:p		
			// };				
			
	// var ajax = new Ajax.Request(
		// url,
		// {
			// method:'post',
			// parameters: params,	
			// onComplete:firstMarkersLoadingCallBack
		// });
	
// }

// function firstMarkersLoadingCallBack ( request )
// {
// $("bannerTop").innerHTML += " callBack1";
	// eval (  request.responseText );
// $("bannerTop").innerHTML += " callBack2";
// }

/*******************On envoie une requete ajax qui va recuperer le contenu de l'infobulle du marker ***************************/
function ajaxGetInfoWindows ( markerId, i, p)
{
	var url = this.path+'/modules/mod01_markers/include/ajax/ajax_getInfowindow.php';

	// $("bannerTop").innerHTML = "Debut";	
	var params = 
			{ 	
				idMap:this.idMap, 
				id:markerId,
				imprimer:i,	
				partager:p	
			};				
			
	var ajax = new Ajax.Request(
		url,
		{
			method:'post',
			parameters: params,	
			onComplete:ajaxGetInfoWindowsCallBack
		});
	
}

function ajaxGetInfoWindowsCallBack ( request )
{
	eval ( request.responseText );

}




/*******************On enregistre les markers dans le tableau de categorie***************************/

function enregistrerMarker ( idMarker, marker )
{	
	marker.id  = idMarker;
	this.allMarkers[idMarker] = marker;

}


/********************************************* change la visibilite des markers contenu dans un tableau **********************************************************************/
var arrayCatClusteringTemp = new Array();
function changeVisibilityMarkers ( idCategorie, arrayMarker, visibility )
{ 

	this.initFrontLoading();
	this.arrayCatClusteringTemp = new Array();

			
	changeVisibilityMarkersWithAjax( idCategorie, arrayMarker );

	
}


/********************************************* change la visibilite des markers contenu dans un tableau **********************************************************************/
function changeVisibilityMarkersWithAjax ( idCats, idCatsInvisible )
{
	
	var url = this.path+'/modules/mod01_markers/include/ajax/ajax_changeVisibility.php';

		
	var params = 
			{ 	
				idMap:this.idMap, 
				idCategories:idCats,		
				idCategoriesInvisible:idCatsInvisible,	
				search:this.currentSearch		
			};				
			
	var ajax = new Ajax.Request(
		url,
		{
			method:'post',
			parameters: params,	
			onComplete:changeVisibilityMarkersWithAjaxCallBack
		});
	
	
}



var lastMarkersWithOutClustering = new Array();
function changeVisibilityMarkersWithAjaxCallBack ( request )
{
	reloadVisibility ( ltrim (request.responseText) );

	this.endFrontLoading();	

	
}

function reloadVisibility ( ids )
{
	var idClusterMarkers_idMarkers = ids.split("|##|");
	var idClusterMarkers = idClusterMarkers_idMarkers[0].split("|#|");
	var idMarkers = idClusterMarkers_idMarkers[1].split("|#|");
	
	/*On affiche les markers avec le clustering */
	if ( idClusterMarkers != "" )
	{
		var markersArray = new Array ();
		
		for ( var id in idClusterMarkers )
		{
		
			if  ( this.expressionId.test(idClusterMarkers[id]) )
				markersArray.push( this.allMarkers[idClusterMarkers[id]] );
	
		}
		
		if ( this.clusteringGeneral )
			redrawClusteringWithArray ( markersArray, "allMarkers" );
		else
		{
			
			redrawClusteringWithArray ( markersArray, idMarkers_idCategorie[1] );

		}
		
	}
	else
		redrawClusteringWithArray ( '', "allMarkers" );
		
	
	/*On affiche les markers sans le clustering*/
	var inArray = false;
	for ( var lastId in lastMarkersWithOutClustering )
	{
		if  ( this.expressionId.test(lastMarkersWithOutClustering[lastId]) )
		{
				
				desafficherSocialElements ( lastMarkersWithOutClustering[lastId] );	
				enleverMarker ( this.allMarkers[lastMarkersWithOutClustering[lastId]] );
				delete ( lastMarkersWithOutClustering[lastId] );
		
		
		}
	
	}
	

	
	try
	{
		for ( var id in idMarkers )
			{
				if  ( this.expressionId.test(idMarkers[id]) )
				{
					// if ( !lastMarkersWithOutClustering[idMarkers[id]] )
					// {
							// if ( this.idMap == 70 )
								// alert (idMarkers[id]);
							//afficherSocialElements ( idMarkers[id] );		
							placerMarker ( this.allMarkers[idMarkers[id]] );
							lastMarkersWithOutClustering.push (idMarkers[id]) ;
					// }
				}
			}
	}
	catch ( err ){}

}



// function afficherDesafficherMarker ( idCategorie, myMark, visible  )
// {
	
	// if ( visible )
	// {
		// myMark.visible = false;

		// if ( !markerClusterer[idCategorie] )
		// {
			
			// if ( !this.arrayCategories[idCategorie]["clustering"])
				// map.addOverlay ( myMark.marker );
		// }
	
	// }
	// else
	// {
	
		// myMark.visible = true;

		// if ( !markerClusterer[idCategorie]  )
		// {
		
			// if ( !this.arrayCategories[idCategorie]["clustering"])
					// map.removeOverlay ( myMark.marker );
		// }	

	// }

// }

/*Recupere tous les markers contenu dans l'arbre devant etre dans le clustering *
var allMarkersWithClustering = new Array();
function getAllMarkers ( arrayCat )
{
		

	for ( var i in arrayCat )
	{
		
	
		/*Si c'est le tableau de marker on le parcours (recursivite) *
		if ( is_array ( arrayCat[i] ) && i!= "kml"  )
		{

			if ( arrayCat[i]["clustering"] || i == "marker")
				getAllMarkers ( arrayCat[i] );
			else
				getAllMarkersWithoutClustering ( arrayCat[i] );
		}
		else
		if ( expressionId.test ( i ) || i == -1 )
			this.allMarkersWithClustering[i] =  arrayCat[i];
				
		
		
		
	}

}


/*Recupere tous les markers contenu dans l'arbre ne devant pas etre dans le clustering *
var allMarkersWithoutClustering = new Array();
function getAllMarkersWithoutClustering ( arrayCat )
{
			
	for ( var i in arrayCat )
	{		
	
		
		/*Si c'est le tableau de marker on le parcours (recursivite) *
		if ( is_array ( arrayCat[i] ) && i!= "kml" )
		{
			if ( arrayCat[i]["clustering"] )
				getAllMarkers ( arrayCat[i] );
			else
				getAllMarkersWithoutClustering ( arrayCat[i] );
			
		}
		else
		if ( expressionId.test ( i ) || i == -1 )
			this.allMarkersWithoutClustering[i] =  arrayCat[i];

		
	}

}





/* zoom sur le marker et ouvre son infobulle */
function afficherMarker ( idMarker, idCategorie )
{
	
	var myMark = this.allMarkers [idMarker];
	centrerMap ( "Marker", myMark, 11 );
	this.ajaxGetInfoWindows ( idMarker );

}
/*

function redrawMarkersWithoutClustering ( markers, idCategorie )
{

	var markersTemp = new Array();
	
	for ( var idMarker in markers )
	{
		if ( this.expressionId.test ( idMarker ) )
		{
			
			with ( markers[idMarker] )
			{
			
				if ( visible )
					placerMarker ( marker );
				else
					enleverMarker ( marker );
			
			}
			
		}
	}

}*/


/*Charge avec ajax les markers de la base de donnee compris dans un certain perimetre*/
function loadMarkersWithBounds ( swLatitude, swLongitude, neLatitude, neLongitude )
{
	var url = this.path+'/modules/mod01_markers/include/ajax/ajax_LoadWithBounds.php';
			
		var ajax = new Ajax.Request(
			url,
			{
				method:'post',
				parameters: 
				{ 	
					idMap:this.idMap, 
					swLat:swLatitude, 
					swLng:swLongitude, 
					neLat:neLatitude, 
					neLng:neLongitude 		
				},						
				onComplete:loadMarkersWithBoundsCallback
			});

}


function loadMarkersWithBoundsCallback ( request )
{
		
	eval ( request.responseText );
}


var sociableMarkerTable = new Array ();

/* function qui va creer les parmatres autour du marker et charge les tweets, checkins.... ayant comme mot cle le titre du points a l'interieur de ce cercle */
function enableSocialMarker  ( id, lat, lng , radius, keyword, parameters)
{
	this.sociableMarkerTable [id] = new Array ();
	this.sociableMarkerTable [id]["markers"] = new Array ();
	this.sociableMarkerTable [id]["visible"] = false;
	this.sociableMarkerTable [id]["circle"] = createCircle ( lat, lng, radius, '', "#000000" );
	
 	
	this.sociableMarkerTable [id]['lat'] = lat;
 	this.sociableMarkerTable [id]['lng']  = lng;
 	this.sociableMarkerTable [id]['radius'] = radius;
    this.sociableMarkerTable [id]['keyword'] = keyword;
    this.sociableMarkerTable [id]['parameters'] = parameters;

	
	/*La fct tweet sera tjrs lancŽe*/
	
	if ( parameters["twitter"] == 1 )
		twitterReloadRadius( keyword, lat, lng, radius );
	
	

}




/*Va desafficher les elements autour du social marker */

function desafficherSocialElements ( id )
{
	
	
	if  ( this.sociableMarkerTable [id] && this.sociableMarkerTable [id]["visible"] )
	{
		//alert ( "desafficher : "+id );
		this.enleverElement ( this.sociableMarkerTable [id]["circle"] );
		
		
		/*On desaffiche tous les markers */
		for ( var i = 0; i< this.sociableMarkerTable [id]['markers'].length; i++ )
			this.enleverElement (  this.sociableMarkerTable [id]['markers'][i] );
		
		this.sociableMarkerTable [id]["visible"] = false;
	
	}

}

/*Va afficher les elements autour du social marker */

function afficherSocialElements ( id )
{

	
	if  ( this.sociableMarkerTable [id] && !this.sociableMarkerTable [id]["visible"] )
	{
		//alert ( "afficher : "+id ); 
		this.placerElement ( this.sociableMarkerTable [id]["circle"] );
		
		
		if ( this.sociableMarkerTable [id]['parameters']["foursquare"] == 1 )	
		{
			
			
			
			/*On teste si les markers n'ont jamais ete charge */
			if ( this.sociableMarkerTable [id]['markers'].length == 0 )
			{
				foursquareGetVenues( id, this.sociableMarkerTable [id]['keyword'], this.sociableMarkerTable [id]['lat'], this.sociableMarkerTable [id]['lng'], this.sociableMarkerTable [id]['radius']  );
				
			}
			else
			{
				/*On desaffiche tous les markers */
				for ( var i = 0; i< this.sociableMarkerTable [id]['markers'].length; i++ )
					this.placerElement (  this.sociableMarkerTable [id]['markers'][i] );
			
			}
	
			
		}
			
		this.sociableMarkerTable [id]["visible"] = true;	

	}

}

/***************************************************************************************************************************

								FICHIER CONTENANT LES FONCTIONS POUR LES DIFFERENTS STYLES DE MARKERS

***************************************************************************************************************************/

function createFlatIcon ( latlng, title, html, size, label, color, colorSelected) 
{
	  var iconNormal = MapIconMaker.createFlatIcon({width: size, height: size, label: label, labelColor: "#ffffff", primaryColor: color});
	  var iconSelected = MapIconMaker.createFlatIcon({width: size, height: size, label: label, labelColor: "#ffffff", primaryColor: colorSelected});
	  
	  var marker = new GMarker(latlng, {icon: iconNormal, title: title});
	  marker.iconNormal = iconNormal;
	  marker.iconSelected = iconSelected;

	  return marker; 
}/***********************************************Tableau avec pour index l'id de la categorie : tableau de al forme***********************************************************************************************************

																						arrayCategories[id]
																						
						arrayCategories[id]['marker']										arrayCategories[id]['clustering']														arrayCategories[id]['kml']	...		
														
arrayCategories[id]['marker'][idMarker1]	arrayCategories[id][marker][idMarker2] .....			true or false																		.......					

*****************************************************************************************************************************************************************************************************************************/
var arrayCategories = new Array ();
arrayCategories["noParent"] = new Array ();
arrayCategories["noParent"]["clustering"] = true;
arrayCategories["-1"] = new Array ();
arrayCategories["-1"]["clustering"] = true;

var arrayAllCategories = new Array ();

/* Charge les categories ( cree une arborescence) !!!!!!! POUR L'INSTANT UN SEUL NIVEAU DE SOUS CATEGORIES !!!!!!******************/
function addCategorie ( idCategorie, idParent, clustering )
{

	switch ( idParent )
	{
		case -1 :
			if ( !this.arrayCategories[ idCategorie ] )
				this.arrayCategories[ idCategorie ] = new Array ();
				
				this.arrayCategories[idCategorie]["clustering"] = clustering;
				
		
		break;
		default :
		/*Sinon on cherche l'element de lm'arbre ou l'on va ajouter la categorie*/
			
			if ( !this.arrayCategories[ idParent ] )
				this.arrayCategories[ idParent ] = new Array ();
				
			if ( !this.arrayCategories[ idParent ][idCategorie] )
				this.arrayCategories[ idParent ][idCategorie]= new Array ();
				
			this.arrayCategories[ idParent ][idCategorie]["clustering"] = clustering;
			
			
		break;
			
	}
	
	this.arrayAllCategories[idCategorie] = idCategorie;
	
	

}


var goodResultPath;
/* Retourne le chemin exact pour acceder a la valeur contenu dans l'arbre de la forme index1|#|index2.....*/
function findTreeElement ( tree, value, resultPath )
{

	for ( var i in tree )
	{
		
		if ( expressionId.test ( i ) )
		{
			switch ( parseInt(i) )
			{
				case parseInt (value) :
					this.goodResultPath=resultPath;
				break;
				default : 
					var result = resultPath+"|#|"+i;
					findTreeElement ( tree[i], value, result  );
				break;
			}			
		}
	
	}
	
}


/* variable utilisée pour stocker le chemin du fichier KML sur lequel on est en trian de travailler */
// var tempPath;


/* tableau ou sont stocker les KML utilises de la forme arrayKML[kmlName] = networkLink */
var arrayKML = new Array ();
/* tableau ou sont stocker les KML utilises de la forme arrayKML[kmlName] = true or false ==> visible ou non*/
var arrayKML_Visibility = new Array ();


/*******************On enregistre les KML dans le tableau de categorie*****************************/

function enregistrerKML ( idCategorie, idKML, path, afficher )
{
			
	findTreeElement ( this.arrayCategories, idCategorie, "-1" );
	var result = this.goodResultPath;

	switch ( idCategorie )
	{
		case "-1" :
	
		/*Si c 'est la premiere fois que l'on rencontre un kml de cette categorie on cree le tableau associé */
			if ( !this.arrayCategories[ "noParent" ]["kml"] )
				this.arrayCategories[ "noParent" ]["kml"] = new Array ();


			this.arrayCategories[ "noParent" ]["kml"][idKML] = path;
		break;
		default :
			if ( result )
			{
			
				switch ( result )
				{
					case "-1" :
			
						if ( !this.arrayCategories[ idCategorie ] )
							this.arrayCategories[ idCategorie ] = new Array ();
						
						
						/*Si c 'est la premiere fois que l'on rencontre un kml de cette categorie on cree le tableau associé */
						if ( !this.arrayCategories[ idCategorie ]["kml"] )
							this.arrayCategories[ idCategorie ]["kml"] = new Array ();


						this.arrayCategories[ idCategorie ]["kml"][idKML]	 = path;
					
					break;
					default :
						var tabResult = result.split ( "|#|" );
						
						
						/*Si c 'est la premiere fois que l'on rencontre cet id on cree le tableau associé */
						if ( !this.arrayCategories[ [tabResult[1]] ][idCategorie] )
							this.arrayCategories[ [tabResult[1]] ][idCategorie]  = new Array ();
						
						/*Si c 'est la premiere fois que l'on rencontre un marker de cette categorie on cree le tableau associé */
						if ( !this.arrayCategories[ [tabResult[1]] ][idCategorie] ["kml"] )
							this.arrayCategories[ [tabResult[1]] ][idCategorie] ["kml"] = new Array ();

						this.arrayCategories[ [tabResult[1]] ][idCategorie]["kml"][idKML] = path;
						
					break;
					
				}
			}
			
		break;
	}
	
	// if  (idMap == 12 )	
	if ( afficher )
		loadKML ( path, idKML, false, idCategorie, '', false );
	// else
	// {
	// 
		// loadKML ( path );
	// }
}


/********************************************* change la visibilite des KML contenu dans un tableau **********************************************************************/
function changeVisibilityKML ( arrayKML, visibility, isCheckBox, position )
{
	
		
	for ( var id in arrayKML )
	{

		switch ( id )
		{
			case "kml" : 
		
				changeVisibilityKML ( arrayKML[id], visibility, isCheckBox, position );
			break;
			default : 
				if ( this.expressionId.test ( id ) )
				{	
					if ( is_array ( arrayKML[id] ) )
						changeVisibilityKML ( arrayKML[id], visibility, isCheckBox, position );
					else
						loadKML ( arrayKML[id], id, isCheckBox, '' , position );
				}	
			break;
			
		}

		
	}

}


/********************************************* change la visibilite des KML sur la map **********************************************************************/
function loadKML ( path, id, isCheckBox, idParent, position, flyToview )
{
	

	
	// this.tempPath = path;
	/*Si c'est google earth*/
	
	switch ( this.map.getCurrentMapType().getName() )
	{
		
		case "Earth" :

			this.map.getEarthInstance( function(ge) 
			{
					
				addKMLGoogleEarth (path, ge, id, isCheckBox, idParent, position, flyToview);
			
			}); 
		break;
		default :
			this.addKMLGooglePlan ( path );
		break;
	}
}

/*A DEVELOPPER*/

function addKMLGooglePlan( href ) 
{

	// var href = this.tempPath;
	
	var visible;

	//Si on a deja travailler avec ce kml, kmz
	if ( this.arrayKML[href] )
	{
	
	
		if( this.arrayKML_Visibility[href]  )
			visible=true;
		else
			visible=false;

			
		if ( visible )
		{
						
			this.map.removeOverlay ( this.arrayKML[href] );
			this.arrayKML_Visibility[href] = false;
		}
		else
		{

			this.map.addOverlay ( this.arrayKML[href] );
			this.arrayKML_Visibility[href] = true;
		}
		
		// endFrontLoading();
		
	}
	else
	{
		
		var xml = new GGeoXml ( href );
		this.map.addOverlay ( xml );
	
		this.arrayKML_Visibility[href] =  true;
		this.arrayKML[href] =  xml;
	
	}
			
} 	


function addKMLGoogleEarth(href, ge, id, isCheckBox, idParent, position, fly) 
{
	initFrontLoading( );

	var visible;

	
			
	//Si on a deja travailler avec ce kml, kmz
	if ( this.arrayKML[href] )
	{
	
		if ( isCheckBox &&  $("checkSB"+position+id))
		{
			
			if ( $("checkSB"+position+id).checked )
				visible = false;
			else
				visible = true;
		}
		else
		{
			if( this.arrayKML_Visibility[href]  )
				visible=true;
			else
				visible=false;

		}
	
			
		if ( visible )
		{
			ge.getFeatures().removeChild ( this.arrayKML[href] );
			this.arrayKML_Visibility[href] = false;
		}
		else
		{
			ge.getFeatures().appendChild ( this.arrayKML[href] );
			this.arrayKML_Visibility[href] = true;
		}
		
		endFrontLoading();
		
	}
	else
	{
	
		var link = ge.createLink('');
		
		link.setHref(href);

		var networkLink = ge.createNetworkLink('');
		
		
		try
		{
			networkLink.set(link, false, fly); // Sets the link, refreshVisibility, and flyToView.
		}
		catch ( err )
		{
			networkLink.set(link, false, true); 
		}

		
		this.arrayKML_Visibility[href] =  true;
		this.arrayKML[href] =  networkLink;
		ge.getFeatures().appendChild(networkLink);
		
	
		
		/* google.earth.fetchKml(ge, href, function(kmlObject) 
		{
			if (!kmlObject) 
			{
			  // show error
			  setTimeout(function() {
				alert('Error loading KML.');
			  }, 0);
			  return;
			}
			
	
			ge.getFeatures().appendChild(kmlObject);
			ge.getView().setAbstractView(kmlObject.getAbstractView());
			arrayKML[href] =  kmlObject;

		 }); */
	
	
		setTimeout ( "endFrontLoading()", 10000 );
	
	}
	
	
	

} 	

var exml;
var arrayParents = [];
/*Ajoute un kml a la map en utilisant EGEOXML */
function addKMLWithEGeoXml( href ) 
{

	this.exml = new EGeoXml( "exml", this.map, href, { preloadimages:true, nozoom:true, addmarker:addKMLWithEGeoXmlAddMarker } );
	exml.parse(); 
	// exml.show();
	GEvent.addListener(exml, "parsed", function() 
	{
		for ( var i in arrayParents )
		{
			if ( expressionId.test ( i ) )
				initClustering ( i );
		}
		
		initClustering ( -1 );	
		 // var mgr = new GMarkerManager(map); 
		 // mgr.addMarkers(exml.gmarkers,0,17);
	}); 
			
} 	

function addKMLWithEGeoXmlAddMarker ( marker, title, description, iconImage, idMarker, idCategorie)
{
	
	arrayParents[idCategorie] = idCategorie;
	enregistrerMarker ( idCategorie, idMarker, marker, true, description );

}








/* 




var g_treeIdObjectMap = null;

function buildTreeUI(kmlObject) {
  delete g_treeIdObjectMap;
  g_treeIdObjectMap = {};
  
  var treeData = {
    identifier: 'id',
    label: 'name',
    items: []
  };
  
  // walk the loaded KML object DOM
  walkKmlDom(kmlObject, function(context) {
    // generate a random, unique ID for this node (Dojo requires a unique ID
    // per each node)
    var nodeId = Number(new Date()).toString() + Math.round(Math.random() * 99999).toString();
    g_treeIdObjectMap[nodeId] = this;
    
    // create the tree node for this item
    var treeNodeData = {
      id: nodeId,
      name: (this.getName() ? this.getName() : '<' + this.getType() + '>'),
      type: this.getType(),
      checked: this.getVisibility(),
      children: []
    };
    
    // add the tree node to the tree data hierarchy 
    context.current.push(treeNodeData);
    
    // all actual KML child nodes will be added to this tree node's
    // children list
    context.child = treeNodeData.children;
  }, { rootContext: treeData.items });
  
  if (dijit.byId('tree'))
    dijit.byId('tree').destroy();
  
  // create the Dojo tree widget
  // and set its data to the hierarchy we just
  // built using walkKmlDom
  var treeDiv = document.createElement('div');
  treeDiv.style.height = '100%';
  dojo.byId('left').appendChild(treeDiv);
  
  var store = new dojo.data.ItemFileWriteStore({ data: treeData });
  
  var model = new dijit.tree.CheckboxForestStoreModel({
    store: store,
    labelAttr: 'name',
    typeAttr: 'type'
  });
  
  var tree = new dijit.CheckboxTree({
    id: 'tree',
    model: model
  }, treeDiv);
  
  // watch for changes in the 'checked' attribute and update feature visibility
  // accordingly
  dojo.connect(store, 'onSet', function(item, attribute, oldValue, newValue) {
    if (oldValue != newValue &&
        attribute == 'checked') {
      var kmlObject = g_treeIdObjectMap[store.getValue(item, 'id')];
      if (!kmlObject)
        return;
      
      kmlObject.setVisibility(newValue);
      
      if (newValue == true) {
        var c = kmlObject;
        while (c && 'setVisibility' in c) {
          c.setVisibility(newValue);
          c = c.getParentNode();
          //store.setValue(item, 'checked' 
        }
      }
    }
  });
  
  // when clicking a tree item, fly to it
  dojo.connect(tree, 'onClick', function(item) {
    if (item) {
      var kmlObject = g_treeIdObjectMap[store.getValue(item, 'id')];
      if (!kmlObject)
        return;
      
      flyToFeature(kmlObject);
    }
  });
  
  var oldGetIconClass = tree.getIconClass;
  tree.getIconClass = function(item, opened) {
    var cls = '';
    if (item) {
      var kmlObject = g_treeIdObjectMap[store.getValue(item, 'id')];
      if (kmlObject) {
        if ('getGeometry' in kmlObject && kmlObject.getGeometry()) {
          cls = kmlObject.getGeometry().getType();
        } else {
          cls = kmlObject.getType();
        }
      }
    }
    
    return cls + ' ' + oldGetIconClass.apply(tree, [item, opened]);
  };
  
  tree.getLabelClass = function(item, opened) {
    if (item && tree.model.mayHaveChildren(item)) {
      return 'folder';
    }
    
    return '';
  };
  
  expandTree();
}

function expandTree() {
  var tree = dijit.byId('tree');
  
  function expandChildNode(node) {
    dojo.forEach(node.getChildren(), function(c) { 
      tree._expandNode(c);
      expandChildNode(c);
    }, this);
  }
  
  expandChildNode(tree.rootNode);
}

function loadKml() {
  var url = dijit.byId('kml-url').getValue();
  
  google.earth.fetchKml(g_ge, url, function(kmlObject) {
    if (!kmlObject) {
      // show error
      setTimeout(function() {
        alert('Error loading KML.');
      }, 0);
      return;
    }
    
    if (g_kmlObject)
      g_ge.getFeatures().removeChild(g_kmlObject);
    
    g_kmlObject = kmlObject;
    g_ge.getFeatures().appendChild(g_kmlObject);
    flyToFeature(g_kmlObject);
    
    buildTreeUI(g_kmlObject);
  });
}

function flyToFeature(kmlFeature) {
  var aspectRatio = dojo.coords('center').w * 1.0 / dojo.coords('center').h;
  var lookAt = computeFitLookAt(g_ge, kmlFeature, aspectRatio);
  if (lookAt)
    g_ge.getView().setAbstractView(lookAt);
}

 */
/*Initialise le loader */
var listeIdCategoriesVisible ="";
var listeIdCategoriesInVisible ="";

/* sont stocke les id des modules de gestions de categories */
var tabGestionCategorie = new Array();

function changeVisibilityCategory ( id, changeCheck, idModule )
{

	this.listeIdCategoriesVisible = "";
	this.listeIdCategoriesInVisible = "";
	
	changeVisibilityCategoryTemp ( id, changeCheck, idModule );
	changeVisibilityMarkers ( this.listeIdCategoriesVisible.substr ( 0, this.listeIdCategoriesVisible.length-3 ), this.listeIdCategoriesInVisible.substr ( 0, this.listeIdCategoriesInVisible.length-3 ));
	


}








/*******************Affiche ou desaffiche les elements d'une categorie selon son ID*****************************/
function changeVisibilityCategoryTemp ( id, changeCheck, idModule )
{

	




	try
	{
	
		if ( $("checkSB_"+idModule+"_"+id).checked )
		{
			findTreeElement ( this.arrayCategories, id, "-1" );
			var result = this.goodResultPath;
			
			
			
			if ( changeCheck  )
				changeCheckBoxValues ( id, true, true, idModule );
				
				
			afficherDesafficherCategorie ( id, result, true, idModule );	
			
			

		}
		else
		{
			findTreeElement ( this.arrayCategories, id, "-1" );
			var result = this.goodResultPath;
			
			// try
			// {
				// $("checkUnCheck"+position).checked = false;
			// }
			// catch (err){}
			
			
			if ( changeCheck  )
				changeCheckBoxValues ( id, false, true, idModule );
				
			afficherDesafficherCategorie ( id, result, false, idModule );
		}
		
		
	
	}
	catch (err){}
	
	
	
	// if  (this.idMap== 70 )
	// {

	/***********************************TEST******************************************/
	
	for ( var i in this.arrayAllCategories )
	{
		if ( this.expressionId.test(i) )
		{

		
			if ( id=="all" )
			{ 
			
				try
				{/* Ne va changer la visibilite de la categorie seulement si celle si se trouve dans la sideBarre*/
					if ( $("checkUnCheck_"+idModule).checked )
					{
						$("checkSB_"+idModule+"_"+i).checked = true;
						this.listeIdCategoriesVisible += i+"|#|";
						
						changeCheckBoxValues ( i, true, true, idModule );
								
						findTreeElement ( this.arrayCategories, i, "-1" );
						var result = this.goodResultPath;	
						afficherDesafficherCategorie ( i, result, true, idModule );
							
					}
					else
					{
						$("checkSB_"+idModule+"_"+i).checked = false;
						changeCheckBoxValues ( i, false, true, idModule );
							
							
						findTreeElement ( this.arrayCategories, i, "-1" );
						var result = this.goodResultPath;	
						afficherDesafficherCategorie ( i, result, false, idModule );
					}

						
				}
				catch (err){ this.listeIdCategoriesVisible += i+"|#|";}
				
				
				
			}
			else
			{
					
				/* on va effectuer la recherche dans tous les modules */
				for ( var idGestionModule in tabGestionCategorie )
				{
					if ( expressionId.test ( idGestionModule ) )
					{			
						try
						{/* Ne va changer la visibilite de la categorie seulement si celle si se trouve dans la sideBarre*/
		
							if ( $("checkSB_"+idGestionModule+"_"+i).checked )
								this.listeIdCategoriesVisible += i+"|#|";
							else
								this.listeIdCategoriesInVisible += i+"|#|";
						}catch (err){ this.listeIdCategoriesVisible += i+"|#|";}
					}
						
				}
				
			
			
			}
			
			
		}
	
	}
					
	this.testAllcheckboxChecked ( idModule );
	/* }
	else
	{
for ( var i in this.arrayAllCategories )
	{
		if ( this.expressionId.test(i) )
		{

		
			if ( id=="all" )
			{ 
				try
				{/* Ne va changer la visibilite de la categorie seulement si celle si se trouve dans la sideBarre*
					if ( $("checkUnCheck_"+idModule).checked )
					{
						$("checkSB_"+idModule+"_"+i).checked = true;
						this.listeIdCategoriesVisible += i+"|#|";
						
						changeCheckBoxValues ( i, true, true, idModule );
							
						
						findTreeElement ( this.arrayCategories, i, "-1" );
						var result = this.goodResultPath;	
						afficherDesafficherCategorie ( i, result, true, idModule );
							
					}
					else
					{
						$("checkSB_"+idModule+"_"+i).checked = false;
						changeCheckBoxValues ( i, false, true, idModule );
							
							
						findTreeElement ( this.arrayCategories, i, "-1" );
						var result = this.goodResultPath;	
						afficherDesafficherCategorie ( i, result, false, idModule );
					}

						
				}
				catch (err){ }
			}
			else
			{
						
				try
				{/* Ne va changer la visibilite de la categorie seulement si celle si se trouve dans la sideBarre*
					
					if ( $("checkSB_"+idModule+"_"+i).checked )
						this.listeIdCategoriesVisible += i+"|#|";
					else
						this.listeIdCategoriesInVisible += i+"|#|";

							
				}
				catch (err){ }
			
			
			}
			
			
		}
	
	}
					
	this.testAllcheckboxChecked ( idModule );
	
} */
}


function afficherDesafficherCategorie ( id, result, visible, idModule )
{

	/*On change la visibilite des markers*/
	switch ( result )
	{
		case "-1" :
	
			if ( this.arrayCategories[id] )
			{
				// changeVisibilityMarkers ( id, this.arrayCategories[id], visible );
				changeVisibilityKML ( this.arrayCategories[id], visible, true, idModule );	
			}

		break;
		default :
			var tabResult = result.split ( "|#|" );
		
			if ( this.arrayCategories[ [tabResult[1]] ][id] )
			{
				// changeVisibilityMarkers ( id,this.arrayCategories[ [tabResult[1]] ][id], visible );
				changeVisibilityKML ( this.arrayCategories[ [tabResult[1]] ][id], visible, true, idModule );
			}
		break;
	}
							
}

/*Affiche ou desaffiche une categorie qui n'est pas dans une sidebar */
function changeVisibilityCategoryTempAlone ( id, visible )
{

	
	
		findTreeElement ( this.arrayCategories, id, "-1" );
		var result = this.goodResultPath;

		if ( visible )
			afficherDesafficherCategorie ( id,  result, false );
		else
			afficherDesafficherCategorie ( id,  result, true );

}




/******************* Permet de retracter ou non les sidebarres *****************************/
function retracterSBRight ( id, sens, value )
{
	var duree = 0.5;
	switch ( sens )
	{
		case "Right" :
			new Effect.Parallel(
			[
				new Effect.BlindRight( id ),
				new Effect.Morph("map", { style: 'right:'+value+'px;' })
			
			], 
			{
				duration: duree
			});
			
			
		break;
		
		case "Left" :
		
		
		
			new Effect.Parallel(
			[
				new Effect.BlindLeft( id ),
				new Effect.Morph("retractableRight_Left", { style: 'right:0px;' }),
				new Effect.Morph("map", { style: 'right:20px;' })
				
			], 
			{
				duration: duree
			});
			
			
		break;

	
	}
	


}


/******** Permet de tester les checkbox fils d'une categorie et check ou decheck ce de la categorie parent en consequence ************/
function changeCheckBoxValues ( idCategorie, visible, isCategorie, idModule )
{

	
	
		if ( isCategorie )
		{	
			findTreeElement ( this.arrayCategories, idCategorie, "-1" );
			var result = this.goodResultPath;

			switch ( result )
			{
				case "-1" :
					changeCheckBoxValueElement ( this.arrayCategories[idCategorie], visible, idModule );
				break;
				default :
					var tabResult = result.split ( "|#|" );
					changeCheckBoxValueElement ( this.arrayCategories[tabResult[1]][idCategorie], visible, idModule );
				break;
			}
			
		}
	
	


}

/********* check ou decheck tous les elements d'une categories ************************/
function changeCheckBoxValueElement ( liste, visible, idModule )
{
	
	for ( var i in liste )
	{
		if  ( is_array( liste[i] ) )
			changeCheckBoxValueElement ( liste[i], visible, idModule );
		
		if ( this.expressionId.test ( i ) )
		{
			try
			{	/* Les KML */
				$("checkSB_"+idModule+"_"+i).checked=visible;
			}
			catch ( err ){}
			
			// try
			// {	/* Les Markers */
				// $("checkSB_marker"+i).checked=visible;
			// }
			// catch ( err ){}
		}	
		
	}

}

function testAllcheckboxChecked ( idModule )
{
	var isChecked = true;

	for ( var i in this.arrayAllCategories )
	{
		if ( this.expressionId.test(i) )
		{
			try
			{/* Ne va changer la visibilite de la categorie seulement si celle si se trouve dans la sideBarre*/
				if ( !$("checkSB_"+idModule+"_"+i).checked )
					isChecked = false;
			}catch ( err ){}
			
		}
		
	}
	
	try
	{
		$("checkUnCheck_"+idModule).checked = isChecked;
	}catch ( err ){}

						
	
	
	
}

var centrerTweetMap = false;
var openIWTweetMap = false;

function twitterReload( kw, icon )
{
	var url = this.path+'/modules/mod08_twitter/include/ajax/ajax_chargerDernierTweet.php';


	var ajax = new Ajax.Request(
		url,
		{
			evalScripts: true, 
			asynchronous:true,
			parameters: { keyword:kw, iconUrl:icon },
			method:'post',
			onComplete:twitterReloadCallback
		});
}

/*On garde en memoire les dernieres coordonnées du marker pour eviter si c'est le meme tweet de le reafficher 2 fois*/
var lastLatLng;

/*echo $content."|#|".$iconUrl ."|#|".$keyword."|#|".$lat."|#|".$lng;*/
 function twitterReloadCallback (request)
 {
	var reponses = request.responseText.split("|#|");
	
	var texte = reponses[0];
	var icon = reponses[1];
	var kw = reponses[2];
	var lat = reponses[3];
	var lng = reponses[4];
 
 
	
	if ( this.lastLatLng != lat+","+lng )
	{
		var markerParameters =
		{
			iconUrl:icon,
			title:kw
		};
	
		var iWParameters =
		{
			click:true,
			type:"map",
			content: texte,
			isOpen:this.openIWTweetMap
		};
 
		var marker = createMarker (  lat, lng, markerParameters, iWParameters );

		placerMarker ( marker , {center:this.centrerTweetMap} );	
	
		this.lastLatLng = lat+","+lng;
	}
 
	setTimeout( function() { twitterReload( kw, icon ); }, 5000); 
	

 }
 
 
 function twitterReloadRadius( kw, latitude, longitude, radius )
{
	var url = this.path+'/modules/mod08_twitter/include/ajax/ajax_chargerDernierTweetRadius.php';


	var ajax = new Ajax.Request(
		url,
		{
			evalScripts: true, 
			asynchronous:true,
			parameters: { keyword:kw, lat:latitude, lng:longitude, r:radius },
			method:'post',
			onComplete:twitterReloadRadiusCallBack
		});
}


/*echo $content."|#|".$iconUrl ."|#|".$keyword."|#|".$lat."|#|".$lng;*/
 function twitterReloadRadiusCallBack (request)
 {
	var reponses = trim(request.responseText).split("|#|");
	
	var texte = reponses[0];
	var latTweet = reponses[1];
	var lngTweet = reponses[2];
	
	var kw = reponses[3];
	var lat = reponses[4];
	var lng = reponses[5];
 	var r = reponses[6];
 
	
	if ( this.lastLatLng != latTweet+","+lngTweet )
	{
		var markerParameters =
		{
			iconUrl:"http://www.mapize.com/generator/generatorSource/images_mapize/library/mapize_marker_twitter.png",
			title:kw
		};
	
		var iWParameters =
		{
			click:true,
			type:"map",
			content: texte,
			isOpen:this.openIWTweetMap
		};
 
		var marker = createMarker (  latTweet, lngTweet, markerParameters, iWParameters );

		placerMarker ( marker );	
	
	//	this.lastLatLng = latTweet+","+lngTweet;
	}
 
	setTimeout( function() { twitterReloadRadius( kw, lat, lng, r ); }, 5000); 
	

 }
 var markerClusterer = new Array ();
 var markerClustererParameters = new Array ();


function initClustering ( idCategorie )
{		
	// var zoom =  14;
	// var size = 50;
	// var style = -1;
	// zoom = zoom == -1 ? null : zoom;
	// size = size == -1 ? null : size;
	// style = style == "-1" ? null: parseInt(style, 10);
	
	if ( this.firstIconImage )
		this.firstIconImageTemp = this.firstIconImage;
	 
	if ( this.secondIconImage )
		this.secondIconImageTemp = this.secondIconImage;

	if ( this.thirdIconImage )
		this.thirdIconImageTemp = this.thirdIconImage;
	
	if ( this.clusterMarkerTitle )
		this.clusterMarkerTitleTemp = this.clusterMarkerTitle;
	
	this.markerClustererParameters[idCategorie] = 
	{
		firstIconImage:this.firstIconImageTemp,	
		secondIconImage:this.secondIconImageTemp, 
		thirdIconImage:this.thirdIconImageTemp, 
		clusterMarkerTitle:this.clusterMarkerTitleTemp
	};	

	// if ( this.idMap==44 )
	// {
		this.arrayCatClusteringTemp[idCategorie] = idCategorie;
	// }
	// else
		// this.refreshClustering ( idCategorie );		

}

/*raffraichit le clustering apres l'ajout ou la suppression de point */
/* function refreshClustering ( idCategorie )
{
	var arrayCategorieMarkersTemp;
	
	
	
	if ( idCategorie != "allMarkers" )
	{
		
		findTreeElement ( this.arrayCategories, idCategorie, "-1" );
		var result = this.goodResultPath;
		
		
							
		if ( result == "-1" || !result )
		{
			if (  this.arrayCategories[idCategorie] )
				arrayCategorieMarkersTemp = this.arrayCategories[idCategorie]["marker"];
		
		}
		else
		{
			if ( result )
			{
				var tabResult = result.split ( "|#|" );
				
				if (  this.arrayCategories[tabResult[1]][idCategorie] )
					arrayCategorieMarkersTemp = this.arrayCategories[tabResult[1]][idCategorie]["marker"];
			}
		}
		
		
	}
	else/*Clustering general *
	{
		this.allMarkers = new Array();
		this.getAllMarkers ( this.arrayCategories );
		arrayCategorieMarkersTemp = this.allMarkers;
	}
		
	/* On cree le tableau de marker *

	var markers = new Array();
	for ( var idMarker in arrayCategorieMarkersTemp )
	{
						
		if ( this.expressionId.test ( idMarker ) )
		{
			with ( arrayCategorieMarkersTemp[idMarker] )
			{
			
				if ( visible )
					markers.push ( marker );
				
			}
			
		}
	}
	

	
	if ( this.markerClusterer[idCategorie] )
		this.markerClusterer[idCategorie].clearMarkers();
	
	try
	{	
		this.markerClusterer[idCategorie] = new MarkerClusterer(this.map, markers, this.markerClustererParameters[idCategorie]);
	
	}
	catch ( err )
	{

	}

}
 */
/*raffraichit le clustering apres l'ajout ou la suppression de point */
function refreshClustering ( idCategorie )
{

	var arrayCategorieMarkersTemp;

	if ( idCategorie != "allMarkers" )
	{
	
		/*IdCategorie est donc un tableau qui contient tous les id des categories a traite*/
		for ( idCat in idCategorie )
		{
			if ( this.expressionId.test ( idCat ) || idCat==-1 )
			{
				findTreeElement ( this.arrayCategories, idCat, "-1" );
				var result = this.goodResultPath;
	
				if ( result == "-1" || !result )
				{	
					if (  this.arrayCategories[idCat] )
						redrawClustering ( this.arrayCategories[idCat]["marker"], idCat );
				}
				else
				{
					if ( result )
					{
						var tabResult = result.split ( "|#|" );
						
						if ( this.arrayCategories[tabResult[1]][idCat] )
							redrawClustering ( this.arrayCategories[tabResult[1]][idCat]["marker"], idCat );
							
					}
				}
			}
		}
	}
	// else/*Clustering general */
	// {
		// this.allMarkersWithClustering = new Array();
		// this.allMarkersWithoutClustering = new Array();
		// this.getAllMarkers ( this.arrayCategories );

		// if ( this.allMarkersWithClustering.length != 0 )
			// redrawClustering ( this.allMarkersWithClustering, idCategorie );
			
		// redrawMarkersWithoutClustering( this.allMarkersWithoutClustering, idCategorie );
				
		
		/*Il faut reafficher les markers pas dans le clustering*/
	// }	

}

// function redrawClustering ( markers, idCategorie )
// {
	// if  ( this.idMap == 44 )
	// {
		// redrawClustering2 ( markers, idCategorie )
	// }
	// else
	// {
	// var markersTemp = new Array();
	
	// for ( var idMarker in markers )
	// {
						
		// if ( this.expressionId.test ( idMarker ) )
		// {
			// with ( markers[idMarker] )
			// {
			
				// if ( visible )
					// markersTemp.push ( marker );
			
			// }
			
		// }
	// }
	

	
	// try
	// {	

		// if ( !this.markerClusterer[idCategorie] )
		// {
			// this.markerClusterer[idCategorie] =  new MarkerClusterer(this.map, markersTemp, this.markerClustererParameters[idCategorie]);
			
		// }
		// else
		// {
			// this.markerClusterer[idCategorie].clearMarkers();
			// this.markerClusterer[idCategorie].addMarkers ( markersTemp );
			
		// }
	
	// }
	// catch ( err ){ alert (err);}
	
// }

// }

function redrawClustering ( markers, idCategorie )
{
	var markersTemp = new Array();
	

	for ( var idMarker in markers )
	{
		if ( this.expressionId.test ( idMarker ) )
		{
			
			with ( markers[idMarker] )
			{
			
				if ( visible )
					markersTemp.push ( marker );
		

			}
			
		}
		
		
	}
	
	/*Expand Markers*/
	if ( isFront )
	{
		try
		{
			var markersTempLength = markersTemp.length -1;
		
			for ( var i= markersTempLength;  i>=0;  i-- )
				expandMarker( markersTemp[i], markersTemp, 15 );	
		}
		catch (err){}
	}

	
	try
	{	

		if ( !this.markerClusterer[idCategorie] )
		{
				
			
			this.markerClustererParameters[idCategorie]["markers"] = markersTemp;
			this.markerClusterer[idCategorie] = new ClusterMarker( map, this.markerClustererParameters[idCategorie]);

			
		}
		else
		{
			this.markerClusterer[idCategorie].removeMarkers();
			if ( markersTemp.length != 0 )
				this.markerClusterer[idCategorie].addMarkers ( markersTemp );
			
		}

		this.markerClusterer[idCategorie].refresh();
	}
	catch ( err ){ }
	

}




function redrawClusteringWithArray ( markersTemp, idCategorie )
{


	/*Expand Markers*/
	if ( isFront )
	{
		try
		{
			var markersTempLength = markersTemp.length -1;
		
			for ( var i= markersTempLength;  i>=0;  i-- )
				expandMarker( markersTemp[i], markersTemp, 15 );	
		}
		catch (err){}
	}

	
	try
	{	

		if ( !this.markerClusterer[idCategorie] )
		{
			this.markerClustererParameters[idCategorie]["markers"] = markersTemp;
			
			this.markerClusterer[idCategorie] = new ClusterMarker( map, this.markerClustererParameters[idCategorie]);
		}
		else
		{
			this.markerClusterer[idCategorie].removeMarkers();
			
		
		
			if ( markersTemp.length != 0 )
				this.markerClusterer[idCategorie].addMarkers ( markersTemp );
			
		}
	
		this.markerClusterer[idCategorie].refresh();
	}
	catch ( err ){ }
	

}
/*
	ClusterMarker Version 1.3.2
	
	A marker manager for the Google Maps API
	http://googlemapsapi.martinpearman.co.uk/clustermarker
	
	Copyright Martin Pearman 2008
	Last updated 29th September 2008

	This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

	You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
	
*/

function ClusterMarker($map, $options){
	this._map=$map;
	this._mapMarkers=[];
	this._iconBounds=[];
	this._clusterMarkers=[];
	this._eventListeners=[];
	if(typeof($options)==='undefined'){
		$options={};
	}
	this.borderPadding=($options.borderPadding)?$options.borderPadding:256;
	this.clusteringEnabled=($options.clusteringEnabled===false)?false:true;
	if($options.clusterMarkerClick){
		this.clusterMarkerClick=$options.clusterMarkerClick;
	}
	
/* 	if($options.clusterMarkerIcon){
		this.clusterMarkerIcon=$options.clusterMarkerIcon;
	}else{
		this.clusterMarkerIcon=new GIcon();
		this.clusterMarkerIcon.image='http://maps.google.com/mapfiles/arrow.png';
		this.clusterMarkerIcon.iconSize=new GSize(39, 34);
		this.clusterMarkerIcon.iconAnchor=new GPoint(9, 31);
		this.clusterMarkerIcon.infoWindowAnchor=new GPoint(9, 31);
		this.clusterMarkerIcon.shadow='http://www.google.com/intl/en_us/mapfiles/arrowshadow.png';
		this.clusterMarkerIcon.shadowSize=new GSize(39, 34);
		
		
	} */
	
	
	/* ADD BY JB */
	// if( $options.firstIconImage)
		this.firstIconImage=$options.firstIconImage;
	// else
		// this.firstIconImage = "http://chart.apis.google.com/chart?chf=bg,s,65432100&cht=it&chs=20x20&chco=27E800,27E800,000000&chx=FFFFFF&ext=.png";
	
	// if( $options.secondIconImage)
		this.secondIconImage=$options.secondIconImage;
	// else
		// this.secondIconImage = "http://chart.apis.google.com/chart?chf=bg,s,65432100&cht=it&chs=30x30&chco=FEAA00,FEAA00,000000&chx=FFFFFF&ext=.png";
	
	
	// if( $options.thirdIconImage)
		this.thirdIconImage=$options.thirdIconImage;
	// else
		// this.thirdIconImage = "http://chart.apis.google.com/chart?chf=bg,s,65432100&cht=it&chs=40x40&chco=B9121B,B9121B,000000&chx=FFFFFF&ext=.png";
	
	/*END  ADD BY JB */
	
	
	// modified code here
	this.clusterMarkerIcon=new GIcon();
	//	this.clusterMarkerIcon.image='';
	// this.clusterMarkerIcon.iconSize=new GSize(12, 20);
	this.clusterMarkerIcon.iconAnchor=new GPoint(6, 20);
	this.clusterMarkerIcon.infoWindowAnchor=new GPoint(6, 1);
	
	
	this.clusterMarkerTitle=($options.clusterMarkerTitle)?$options.clusterMarkerTitle:'Click to zoom in and see %count markers';
	if($options.fitMapMaxZoom){
		this.fitMapMaxZoom=$options.fitMapMaxZoom;
	}
	this.intersectPadding=($options.intersectPadding)?$options.intersectPadding:0;
	if($options.markers){
		this.addMarkers($options.markers);
	}
	GEvent.bind(this._map, 'moveend', this, this._moveEnd);
	GEvent.bind(this._map, 'zoomend', this, this._zoomEnd);
	GEvent.bind(this._map, 'maptypechanged', this, this._mapTypeChanged);
}

ClusterMarker.prototype.addMarkers=function($markers){
	var i;
	

	
	if(!$markers[0]){
		//	assume $markers is an associative array and convert to a numerically indexed array
		var $numArray=[];
		for(i in $markers){
			$numArray.push($markers[i]);
		}
		$markers=$numArray;
	}
	for(i=$markers.length-1; i>=0; i--){
		$markers[i]._isVisible=false;
		$markers[i]._isActive=false;
		$markers[i]._makeVisible=false;

	}
	this._mapMarkers=this._mapMarkers.concat($markers);
}; 

ClusterMarker.prototype._clusterMarker=function($clusterGroupIndexes){
	function $newClusterMarker($location, $icon, $title){
		return new GMarker($location, {icon:$icon, title:$title});
	}
	var $clusterGroupBounds=new GLatLngBounds(), i, $clusterMarker, $clusteredMarkers=[], $marker, $this=this, $mapMarkers=this._mapMarkers;
	for(i=$clusterGroupIndexes.length-1; i>=0; i--){
		$marker=$mapMarkers[$clusterGroupIndexes[i]];
		$marker.index=$clusterGroupIndexes[i];
		$clusterGroupBounds.extend($marker.getLatLng());
		$clusteredMarkers.push($marker);
	}
	
	// modified code here, simply define image property of cluster marker icon depending upon number of markers within cluster
	var myIcon=new GIcon(this.clusterMarkerIcon), markerCount=$clusterGroupIndexes.length;
	if (markerCount<10)
	{
		myIcon.image= this.firstIconImage+"&chl="+markerCount;
	} else if (markerCount<50) 
	{
		myIcon.image=this.secondIconImage+"&chl="+markerCount;
	} else {
		myIcon.image=this.thirdIconImage+"&chl="+markerCount;
	}
	
	// modified code here - myIcon now passed to $newClusterMarker instead of this.clusterMarkerIcon
	$clusterMarker=$newClusterMarker($clusterGroupBounds.getCenter(), myIcon, this.clusterMarkerTitle.replace(/%count/gi, $clusterGroupIndexes.length));
	
	// $clusterMarker=$newClusterMarker($clusterGroupBounds.getCenter(), this.clusterMarkerIcon, this.clusterMarkerTitle.replace(/%count/gi, $clusterGroupIndexes.length));
	$clusterMarker.clusterGroupBounds=$clusterGroupBounds;	//	only req'd for default cluster marker click action
	this._eventListeners.push(GEvent.addListener($clusterMarker, 'click', function(){
		$this.clusterMarkerClick({clusterMarker:$clusterMarker, clusteredMarkers:$clusteredMarkers });
	}));
	$clusterMarker._childIndexes=$clusterGroupIndexes;
	for(i=$clusterGroupIndexes.length-1; i>=0; i--){
		$mapMarkers[$clusterGroupIndexes[i]]._parentCluster=$clusterMarker;
	}
	return $clusterMarker;
};

ClusterMarker.prototype.clusterMarkerClick=function($args){
	this._map.setCenter($args.clusterMarker.getLatLng(), this._map.getBoundsZoomLevel($args.clusterMarker.clusterGroupBounds));
};

ClusterMarker.prototype._filterActiveMapMarkers=function(){
	var $borderPadding=this.borderPadding, $mapZoomLevel=this._map.getZoom(), $mapProjection=this._map.getCurrentMapType().getProjection(), $mapPointSw, $activeAreaPointSw, $activeAreaLatLngSw, $mapPointNe, $activeAreaPointNe, $activeAreaLatLngNe, $activeAreaBounds=this._map.getBounds(), i, $marker, $uncachedIconBoundsIndexes=[], $oldState, $mapMarkers=this._mapMarkers, $iconBounds=this._iconBounds;
	if($borderPadding){
		$mapPointSw=$mapProjection.fromLatLngToPixel($activeAreaBounds.getSouthWest(), $mapZoomLevel);
		$activeAreaPointSw=new GPoint($mapPointSw.x-$borderPadding, $mapPointSw.y+$borderPadding);
		$activeAreaLatLngSw=$mapProjection.fromPixelToLatLng($activeAreaPointSw, $mapZoomLevel);
		$mapPointNe=$mapProjection.fromLatLngToPixel($activeAreaBounds.getNorthEast(), $mapZoomLevel);
		$activeAreaPointNe=new GPoint($mapPointNe.x+$borderPadding, $mapPointNe.y-$borderPadding);
		$activeAreaLatLngNe=$mapProjection.fromPixelToLatLng($activeAreaPointNe, $mapZoomLevel);
		$activeAreaBounds.extend($activeAreaLatLngSw);
		$activeAreaBounds.extend($activeAreaLatLngNe);
	}
	this._activeMarkersChanged=false;
	if(typeof($iconBounds[$mapZoomLevel])==='undefined'){
		//	no iconBounds cached for this zoom level
		//	no need to check for existence of individual iconBounds elements
		this._iconBounds[$mapZoomLevel]=[];
		this._activeMarkersChanged=true;	//	force refresh(true) as zoomed to uncached zoom level
		
		for(i=$mapMarkers.length-1; i>=0; i--){
			$marker=$mapMarkers[i];
			$marker._isActive=$activeAreaBounds.containsLatLng($marker.getLatLng())?true:false;
			$marker._makeVisible=$marker._isActive;
			if($marker._isActive){
				$uncachedIconBoundsIndexes.push(i);
			}
	
		}
	}else{
		//	icondBounds array exists for this zoom level
		//	check for existence of individual iconBounds elements
	
		for(i=$mapMarkers.length-1; i>=0; i--){
			$marker=$mapMarkers[i];
			$oldState=$marker._isActive;
			$marker._isActive=$activeAreaBounds.containsLatLng($marker.getLatLng())?true:false;
			$marker._makeVisible=$marker._isActive;
			if(!this._activeMarkersChanged && $oldState!==$marker._isActive){
				this._activeMarkersChanged=true;
			}
			if($marker._isActive && typeof($iconBounds[$mapZoomLevel][i])==='undefined'){
				$uncachedIconBoundsIndexes.push(i);
			}
		}
		
	}
	return $uncachedIconBoundsIndexes;
	
};

ClusterMarker.prototype._filterIntersectingMapMarkers=function(){
	var $clusterGroup, i, j, $mapZoomLevel=this._map.getZoom(), $mapMarkers=this._mapMarkers, $iconBounds=this._iconBounds;
	for(i=$mapMarkers.length-1; i>0; i--)
	{
		if($mapMarkers[i]._makeVisible){
			$clusterGroup=[];
			for(j=i-1; j>=0; j--){
				if($mapMarkers[j]._makeVisible && $iconBounds[$mapZoomLevel][i].intersects($iconBounds[$mapZoomLevel][j])){
					$clusterGroup.push(j);
				}
			}
			if($clusterGroup.length!==0){
				$clusterGroup.push(i);
				for(j=$clusterGroup.length-1; j>=0; j--){
					$mapMarkers[$clusterGroup[j]]._makeVisible=false;
				}
				this._clusterMarkers.push(this._clusterMarker($clusterGroup));
			}
		}
	}
};

ClusterMarker.prototype.fitMapToMarkers=function(){
	var $mapMarkers=this._mapMarkers, $markersBounds=new GLatLngBounds(), i;
	for(i=$mapMarkers.length-1; i>=0; i--){
		$markersBounds.extend($mapMarkers[i].getLatLng());
	}
	var $fitMapToMarkersZoom=this._map.getBoundsZoomLevel($markersBounds);
		
	if(this.fitMapMaxZoom && $fitMapToMarkersZoom>this.fitMapMaxZoom){
		$fitMapToMarkersZoom=this.fitMapMaxZoom;
	}
	this._map.setCenter($markersBounds.getCenter(), $fitMapToMarkersZoom);
	
	try
	{
		this.refresh();
	}
	catch (err){};
};

ClusterMarker.prototype._mapTypeChanged=function(){
	try
	{
		this.refresh(true);
	}
	catch (err){};
};

ClusterMarker.prototype._moveEnd=function(){
	if(!this._cancelMoveEnd){
	try
	{
		this.refresh();
	}
	catch (err){};
	}else{
		this._cancelMoveEnd=false;
	}
};

ClusterMarker.prototype._preCacheIconBounds=function($indexes, $mapZoomLevel){
	var $mapProjection=this._map.getCurrentMapType().getProjection(), i, $marker, $iconSize, $iconAnchorPoint, $iconAnchorPointOffset, $iconBoundsPointSw, $iconBoundsPointNe, $iconBoundsLatLngSw, $iconBoundsLatLngNe, $intersectPadding=this.intersectPadding, $mapMarkers=this._mapMarkers;
	for(i=$indexes.length-1; i>=0; i--){
		$marker=$mapMarkers[$indexes[i]];
		$iconSize=$marker.getIcon().iconSize;
		$iconAnchorPoint=$mapProjection.fromLatLngToPixel($marker.getLatLng(), $mapZoomLevel);
		$iconAnchorPointOffset=$marker.getIcon().iconAnchor;
		$iconBoundsPointSw=new GPoint($iconAnchorPoint.x-$iconAnchorPointOffset.x-$intersectPadding, $iconAnchorPoint.y-$iconAnchorPointOffset.y+$iconSize.height+$intersectPadding);
		$iconBoundsPointNe=new GPoint($iconAnchorPoint.x-$iconAnchorPointOffset.x+$iconSize.width+$intersectPadding, $iconAnchorPoint.y-$iconAnchorPointOffset.y-$intersectPadding);
		$iconBoundsLatLngSw=$mapProjection.fromPixelToLatLng($iconBoundsPointSw, $mapZoomLevel);
		$iconBoundsLatLngNe=$mapProjection.fromPixelToLatLng($iconBoundsPointNe, $mapZoomLevel);
		this._iconBounds[$mapZoomLevel][$indexes[i]]=new GLatLngBounds($iconBoundsLatLngSw, $iconBoundsLatLngNe);
	}
};





ClusterMarker.prototype.refresh=function($forceFullRefresh)
{

	var i, $marker, $zoomLevel=this._map.getZoom(), $uncachedIconBoundsIndexes=this._filterActiveMapMarkers();
	
	if(this._activeMarkersChanged || $forceFullRefresh)
	{
		this._removeClusterMarkers();
		
		if(this.clusteringEnabled && $zoomLevel<this._map.getCurrentMapType().getMaximumResolution())
		{
			if($uncachedIconBoundsIndexes.length>0)
			{
				this._preCacheIconBounds($uncachedIconBoundsIndexes, $zoomLevel);
			}
			
			this._filterIntersectingMapMarkers();
		}
		
		// alert (this._clusterMarkers.length);
		
		for(i=this._clusterMarkers.length-1; i>=0; i--)
		{
			this._map.addOverlay(this._clusterMarkers[i]);
		}
		
		var arrayVisibleMarker = new Array ();
		
		for(i=this._mapMarkers.length-1; i>=0; i--)
		{
			$marker=this._mapMarkers[i];
			
			if(!$marker._isVisible && $marker._makeVisible)
			{
				this._map.addOverlay($marker);
				$marker._isVisible=true;
				/* ADD BY JB */
				//afficherSocialElements ( $marker.id  );
	
			}
			if($marker._isVisible && !$marker._makeVisible)
			{
				// arrayVisibleMarker.pop( $marker);
				this._map.removeOverlay($marker);
				$marker._isVisible=false;
				
				/* ADD BY JB */
				desafficherSocialElements ( $marker.id  );
				
			}
			
			
		}
		
		
		
		
		/*******************************expand marker*************************************/
		
		// for(a=lastGeventMouseOver.length-1;a>=0; a--)
		// {
			// GEvent.removeListener( lastGeventMouseOver[a] );
		// }
		
		// for(b=lastGeventMapClick.length-1;b>=0; b--)
		// {
			// GEvent.removeListener( lastGeventMapClick[b] );
		// }
		
		// for(c=lastGeventMapZoomEnd.length-1;c>=0; c--)
		// {
			// GEvent.removeListener( lastGeventMapZoomEnd[c] );
		// }
			
		
		// if ( map.getZoom() ==15 )
		// {
			// lastGeventMouseOver = new Array();
			// lastGeventMapClick = new Array();
			// lastGeventMapZoomEnd = new Array();
					
			// if ( isFront )
			// {	
			
		
				
				// for(v=arrayVisibleMarker.length-1; v>=0; v--)
				// {		
					// expandMarker( arrayVisibleMarker[v],arrayVisibleMarker,( map.getZoom() - 1) );	
				// }
				
			// }
		// }
		/*******************************fin expand marker*************************************/	
	}
	
};




ClusterMarker.prototype._removeClusterMarkers=function(){
	var i, j, $map=this._map, $eventListeners=this._eventListeners, $clusterMarkers=this._clusterMarkers, $childIndexes, $mapMarkers=this._mapMarkers;
	for(i=$clusterMarkers.length-1; i>=0; i--){
		$childIndexes=$clusterMarkers[i]._childIndexes;
		for(j=$childIndexes.length-1; j>=0; j--){
			delete $mapMarkers[$childIndexes[j]]._parentCluster;
		}
		$map.removeOverlay($clusterMarkers[i]);
	}
	for(i=$eventListeners.length-1; i>=0; i--){
		GEvent.removeListener($eventListeners[i]);
	}
	this._clusterMarkers=[];
	this._eventListeners=[];
};

ClusterMarker.prototype.removeMarkers=function(){
	var i, $mapMarkers=this._mapMarkers, $map=this._map;
	for(i=$mapMarkers.length-1; i>=0; i--){
		if($mapMarkers[i]._isVisible){
			
			$map.removeOverlay($mapMarkers[i]);
			
			/* ADD BY JB */
			desafficherSocialElements ( $mapMarkers[i].id  );
		}
		delete $mapMarkers[i]._isVisible;
		delete $mapMarkers[i]._isActive;
		delete $mapMarkers[i]._makeVisible;
	}
	this._removeClusterMarkers();
	this._mapMarkers=[];
	this._iconBounds=[];
};

ClusterMarker.prototype.triggerClick=function($index){
	var $marker=this._mapMarkers[$index];
	if($marker._isVisible){
		//	$marker is visible
		GEvent.trigger($marker, 'click');
	}
	else if($marker._isActive){
		//	$marker is clustered
		var $clusteredMarkersIndexes=$marker._parentCluster._childIndexes, $intersectDetected=true, $uncachedIconBoundsIndexes, i, $mapZoomLevel=this._map.getZoom(), $clusteredMarkerIndex, $iconBounds=this._iconBounds, $mapMaxZoomLevel=this._map.getCurrentMapType().getMaximumResolution();
		while($intersectDetected && $mapZoomLevel<$mapMaxZoomLevel){
			$intersectDetected=false;
			$mapZoomLevel++;
			if(typeof($iconBounds[$mapZoomLevel])==='undefined'){
				//	no iconBounds cached for this zoom level
				//	no need to check for existence of individual iconBounds elements
				$iconBounds[$mapZoomLevel]=[];
				// need to create cache for all clustered markers at $mapZoomLevel
				this._preCacheIconBounds($clusteredMarkersIndexes, $mapZoomLevel);
			}else{
				//	iconBounds array exists for this zoom level
				//	check for existence of individual iconBounds elements
				$uncachedIconBoundsIndexes=[];
				for(i=$clusteredMarkersIndexes.length-1; i>=0; i--){
					if(typeof($iconBounds[$mapZoomLevel][$clusteredMarkersIndexes[i]])==='undefined'){
						$uncachedIconBoundsIndexes.push($clusteredMarkersIndexes[i]);
					}
				}
				if($uncachedIconBoundsIndexes.length>=1){
					this._preCacheIconBounds($uncachedIconBoundsIndexes, $mapZoomLevel);
				}
			}
			for(i=$clusteredMarkersIndexes.length-1; i>=0; i--){
				$clusteredMarkerIndex=$clusteredMarkersIndexes[i];
				if($clusteredMarkerIndex!==$index && $iconBounds[$mapZoomLevel][$clusteredMarkerIndex].intersects($iconBounds[$mapZoomLevel][$index])){	
					$intersectDetected=true;
					break;
				}
			}
			
		};
		this._map.setCenter($marker.getLatLng(), $mapZoomLevel);
		this.triggerClick($index);
	}else{
		// $marker is not within active area (map bounds + border padding)
		this._map.setCenter($marker.getLatLng());
		this.triggerClick($index);
	}
};

ClusterMarker.prototype._zoomEnd=function(){
	this._cancelMoveEnd=true;
	
	try
	{
		this.refresh(true);
	}
	catch (err){};
};





/*********************************** Clustering inverse *****************************************/
var lastGeventMouseOver = new Array();
var lastGeventMapClick = new Array();
var lastGeventMapZoomEnd = new Array();

function expandMarker( marker, markers, zoom ) 
{

	var location = marker.getLatLng();
	
	
	marker.targeted=0;
	marker.startcoord=location;
	marker.openwindow=false;
	marker.line = null;
	marker.shifted = 0;

	var t_error = .0005;
	var shift = .001;
	var n_coord = marker.getLatLng().lat() + t_error;
	var s_coord = marker.getLatLng().lat() - t_error;
	var e_coord = marker.getLatLng().lng() + t_error;
	var w_coord = marker.getLatLng().lng() - t_error;
	marker.inBounds = new GLatLngBounds(new GLatLng(s_coord, w_coord), new GLatLng(n_coord, e_coord));


	marker.n_outer = marker.startcoord.lat()+shift;
	marker.s_outer = marker.startcoord.lat()-shift;
	marker.e_outer = marker.startcoord.lng()+shift;
	marker.w_outer = marker.startcoord.lng()-shift;
	marker.outBounds = null;

		
	GEvent.addListener(marker, "mouseover", function() 
	{	

		if (map.getZoom() >= zoom) 
		{
				var step = 0;
				for (x = 0; x < markers.length; x++) 
				{
				
					var target = markers[x].getLatLng();
			
			
					if ( marker.inBounds.containsLatLng(target)==true && markers[x].isHidden()==false) 
					{
						step++;
						markers[x].targeted=1;
						markers[x].outBounds = setOuterBounds( markers[x] );
					
				
					};
				};
				
				
				if (step == 1) 
				{
					marker.targeted = 0;
					marker.outBounds = null;
				};
				
				
				
				
				
			if (step > 1) 
			{
				
				
				if (!map.getInfoWindow().isHidden()) 
				{ 
					map.closeInfoWindow(); 
				}
				
				var tick = 1;
				var deg = (360 / (step));
				
				
				for (x = 0; x < markers.length; x++) 
				{
				
					
					if (markers[x].targeted==1 && markers[x].shifted==0) 
					{
						map.removeOverlay(markers[x]);
							
						var delta_lat = (shift +  shift*(Math.pow(2, (17 - map.getZoom())) - 1)) * Math.cos(((deg * tick) * Math.PI) / 180);
						var delta_lng = (shift +  shift*(Math.pow(2, (17 - map.getZoom())) - 1)) * Math.sin(((deg * tick) * Math.PI) / 180);
						var point_latlng = new GLatLng((markers[x].startcoord.lat() + (delta_lat * .15)), (markers[x].startcoord.lng() + (delta_lng * .15)));
						var new_lat = markers[x].getLatLng().lat() + delta_lat;
						var new_lng = markers[x].getLatLng().lng() + delta_lng; 
						
						// alert ( new_lat+"  "+new_lng );
						markers[x].setLatLng(new GLatLng(new_lat, new_lng));
						markers[x].importance=10;
						map.addOverlay(markers[x]);
						// markers[x].setImage(window.sharedFilesURL + 'markers/' + markers[x].iconsizeurl +'/'+ markers[x].iconcolorurl +'/'+ markers[x].iconnumurl + '.png');

						markers[x].line = new GPolyline([
						markers[x].startcoord,  
						markers[x].getLatLng()], 
						'#000000', 1, 1);
						
						map.addOverlay(markers[x].line);

						var linepointcolor = '#EA6109';
						
						if (markers[x].iconsizeurl=='small') 
						{
							linepointcolor='#EA6109';
						}
						
						markers[x].point = new GPolyline
						(
							[
								markers[x].startcoord,
								point_latlng
							],
							linepointcolor, 0.5, 1
						);
						
						map.addOverlay(markers[x].point);

						markers[x].shifted=1;
						tick++;
						
					};
				};	

			
			};
				
				
			GEvent.addListener(map, "click", function(overlay, latlng, overlaylatlng) 
			{
				
				for (x = 0; x < markers.length; x++) 
				{
				
					if ( latlng )
					{
						// alert ( markers[x].outBounds.containsLatLng(latlng)+"    "+latlng)
						if (markers[x].targeted==1 && markers[x].outBounds.containsLatLng(latlng)==false) 
						{
							if (!map.getInfoWindow().isHidden())
							{ 
								map.closeInfoWindow(); 
							}
							
							
							map.removeOverlay(markers[x].line);
							map.removeOverlay(markers[x].point);
							map.removeOverlay(markers[x]);
							markers[x].setLatLng(markers[x].startcoord);
							markers[x].targeted=0;
							markers[x].shifted=0;
							markers[x].importance = markers[x].startimport;
							map.addOverlay(markers[x]);
							// markers[x].setImage( window.sharedFilesURL + 'markers/' + markers[x].iconsizeurl +'/'+ markers[x].iconcolorurl +'/'+ markers[x].iconnumurl + '.png');
							
							if (markers[x].openwindow==true)
							{
								GEvent.trigger(markers[x], "click")
							};
							
							markers[x].openwindow=false;
						}
					}
				};	 
			});
				
				
			GEvent.addListener(map, "zoomend", function() 
			{
				try
				{
					for (x = 0; x < markers.length; x++) 
					{
			
						if (!map.getInfoWindow().isHidden())
						{ 
							map.closeInfoWindow(); 
						}
						
						
						map.removeOverlay(markers[x].line);
						map.removeOverlay(markers[x].point);
						map.removeOverlay(markers[x]);
						markers[x].setLatLng(markers[x].startcoord);
						markers[x].targeted=0;
						markers[x].shifted=0;
						markers[x].importance = markers[x].startimport;
						
						
						// map.addOverlay(markers[x]);
						// markers[x].setImage( window.sharedFilesURL + 'markers/' + markers[x].iconsizeurl +'/'+ markers[x].iconcolorurl +'/'+ markers[x].iconnumurl + '.png');
						
						if (markers[x].openwindow==true)
						{
							GEvent.trigger(markers[x], "click")
						};
						
						markers[x].openwindow=false;
				
					};	 
				}catch ( err ){ }
			});
		};	
	});
				
}	


function setOuterBounds(marker)
 {
	var n_outer = marker.startcoord.lat() + .5*((marker.n_outer - marker.s_outer + .00075) / Math.pow(2, -(17 - map.getZoom())));
	var s_outer = marker.startcoord.lat() - .5*((marker.n_outer - marker.s_outer) / Math.pow(2, -(17 - map.getZoom())));
	var e_outer = marker.startcoord.lng() + .5*((marker.e_outer - marker.w_outer + .00025) / Math.pow(2, -(17 - map.getZoom()))); 
	var w_outer = marker.startcoord.lng() - .5*((marker.e_outer - marker.w_outer + .00025) / Math.pow(2, -(17 - map.getZoom()))); 
	var newOuterBounds = new GLatLngBounds(new GLatLng(s_outer, w_outer), new GLatLng(n_outer, e_outer));
	
	return newOuterBounds;
	
}
	
		
	
	/***************************************Fin clustering inverse *******************************************/
	/*Tableau ou sont stocké les resultats de la recherche */

var arraySearch = new Array();
/* Lance la recherche */

var currentSearch = "";

/*Va lancer une recherche selon la valeur de du boutton radio */
function chercher ( id )
{

		if ( $("searchType1_"+id ) )
		{
			if ( $("searchType1_"+id).checked )
				lancerRecherche ( id );

		}
		
		if ( $("searchType2_"+id).checked )
			lancerRechercheAddresse ( id );

		
}


function lancerRecherche (  id, keyword ) 
{
	
	$("clearSearch_"+id).style.display = "block";


	this.arraySearch = new Array();
	
		 if ( !keyword )
			keyword= $F("searchEngine_"+id);
			
	this.currentSearch = keyword;
	 
	for ( var idGestionModule in tabGestionCategorie )
	{
		if ( expressionId.test ( idGestionModule ) )
		{
			changeVisibilityCategory ( "", true, idGestionModule );
		}
	}
	

}

function lancerRechercheAddresse ( id )
{
	/*Si c'est une adresse*/
	geocodeAdresse ( $F("searchEngine_"+id) );
	setTimeout("lancerRechercheAddresseCallBack ()", 1000 );

}

function lancerRechercheAddresseCallBack ()
{
	if ( geocodeLat && geocodeLng )
	{
		
		
		if ( this.map.getCurrentMapType().getName() =="Earth" )
		{
			this.map.getEarthInstance( function(ge) 
			{
				var zoom = gmapToGearthZoom(geocodeZoom);
				 var lookAt = ge.createLookAt('');
				  lookAt.set(geocodeLat, geocodeLng, 10, ge.ALTITUDE_RELATIVE_TO_GROUND, 20,50,  zoom );
				  ge.getView().setAbstractView(lookAt);  
			});
		}
		else
		{
			centrerMap ( "LatLng", new GLatLng ( geocodeLat, geocodeLng ), geocodeZoom );
		}
		
	}
	

	// var zoom = 18-Math.log(3.3*range/Math.sqrt(geocodeLat*geocodeLat+geocodeLng*geocodeLng))/Math.log(2);
	
	
	delete (geocodeLat);
	delete (geocodeLng);

}
	
function clearSearch ( id )
{
	$("clearSearch_"+id).style.display = "none";
	$("searchEngine_"+id).value = "";
	this.currentSearch = "";
	
	for ( var idGestionModule in tabGestionCategorie )
	{
		if ( expressionId.test ( idGestionModule ) )
		{
			changeVisibilityCategory ( "", true, idGestionModule );
		}
	}

}
/* function findWord ( tree, value )
{
	var markerTree;
	
	for ( var i in tree )
	{
			if ( this.idMap == 12 )
			{
				if ( $("checkSBRight"+i) )
					findWordWithAjax ( i, value );	
			}
			
			else
			{
		
		
		
		if ( expressionId.test ( i ) )
		{
			
			if ( tree[i]["marker"] )
			{
				markerTree = tree[i]["marker"];
				for ( var mark in markerTree )
				{
					if ( expressionId.test ( mark ) )
					{
						with ( markerTree[mark] )
						{
							/* On fait un test sur le titre *
							if ( marker.getTitle().toLowerCase().indexOf(value.toLowerCase()) != -1 )
								this.arraySearch[mark] = markerTree[mark];
							else
							{
								
								/* On fait un test sur le contenu *
								for ( var c in 	content )
								{
									if ( expressionId.test ( c ) )
									{
										if ( content[c].contentElem.innerHTML.toLowerCase().indexOf(value.toLowerCase()) != -1 )
											this.arraySearch[mark] = markerTree[mark];
									}
								}
							}	
								
						}
					}
				}
			}
			
			if ( $("checkSBRight"+i) )
			{
			
				if ( $("checkSBRight"+i).checked == true );	
					findWord ( tree[i], value );
			}
				
			}				
		}
	
	}
	
	
	
} */


// function findWordWithAjax ( value )
// {
		// var url = this.path+'/modules/mod13_search/include/ajax/ajax_findWord.php';
			
			
			
		// var params = 
				// { 	
					// idMap:this.idMap, 
					// keyword:value		
				// };				
			
			
			
			
		// var ajax = new Ajax.Request(
			// url,
			// {
				// method:'post',
				// parameters: params,	
				// onComplete:findWordWithAjaxCallBack
			// });


// }

// function findWordWithAjaxCallBack ( request )
// {
	// var idMarkers = request.responseText.split("|#|");
	
	// for ( var id in idMarkers )
	// {
		// if  ( this.expressionId.test(idMarkers[id]) )
			// this.arraySearch[idMarkers[id]] = this.allMarkers[idMarkers[id]];
	// }
	
	// for ( var i in this.arrayCategories )
	// {
		// if ( this.expressionId.test(i) )
		// {

			// if ( $("checkSBRight"+i) )
			// {
				// if ( $("checkSBRight"+i).checked == true )
					// changeVisibilityCategory ( i, "good", "Right" );
			// }
	
		// }
	
	 // }
// }





function reloadMarkersTable ( )
{
	var idP = $F ("parentCat");

	
	var url = this.path+'/modules/mod15_liste/include/ajax/ajax_reloadMarkers.php';
	
	var ajax;
	
			ajax = new Ajax.Request(
				url,
				{
					method:'post',
					parameters: { idMap:this.idMap, idParent:idP },
					onComplete:reloadMarkersTableCallBack
				});
	

}
	

function reloadMarkersTableCallBack ( request )
{
	$( "spreadSheetMarker").innerHTML = request.responseText;
}
/*Envoie un mail avec un lien  pour afficher la map seulement avec ce point*/
function partagerPoint ( id )
{

	var url = this.path+'/modules/mod16_pointPartage/include/ajax/ajax_sendInformations.php';

		
	var params = 
			{ 	
				idMarker:id,
				urlMap:this.urlMap,
				mailDestinataire:$F("emailDestinatairePartager_"+id),		
				nom:$F("nomPartager_"+id),	
				mail:$F("emailPartager_"+id),		
				message:$F("messagePartager_"+id)	
			};				
			
	var ajax = new Ajax.Request(
		url,
		{
			method:'post',
			parameters: params,	
			onComplete:partagerPointCallBack
		});
}
	

function partagerPointCallBack( request )
{
		var id_text = request.responseText.split ("|#|");
		$("partagerPointContainerReponse_"+id_text[0]).innerHTML = id_text[1];
} 
 function foursquareGetVenues( idMarker, kw, latitude, longitude, radius )
{
	var url = this.path+'/modules/mod21_foursquare/include/ajax/ajax_chargerVenuesRadius.php';


	var ajax = new Ajax.Request(
		url,
		{
			evalScripts: true, 
			asynchronous:true,
			parameters: { id:idMarker, keyword:kw, lat:latitude, lng:longitude, r:radius },
			method:'post',
			onComplete:foursquareGetVenuesCallBack
		});
}


 function foursquareGetVenuesCallBack (request)
 {
 
 	eval ( trim ( request.responseText ) );
	
 }


