//Carte
var _map = null;
var _geocoder = null;

//marqueur de saisie de fiche
var _customMarker = null;
var _editMode = false;

//Tableau contenant les marqueurs
var _arrMarkers = new Array();


//pour Bretagne
var _zoomInit = 10;
var _latInit = 47.603385
var _longInit = -2.8330993

var _zoomMax = 16;

//Info-bulle
var _displayInfoForThisMarkerId = -1;

//autorise l'update sur event
var _allowUpdate = true;

//Zone de chargement des fiches
var _zoneLoaded = false;
var _zoneLoadedDeltaFen = 0.5;
var _zoneLoadedXMIN = 0;
var _zoneLoadedXMAX = 0;
var _zoneLoadedYMIN = 0;
var _zoneLoadedYMAX = 0;


//street view
var _myPano = null;

//markeur manager
var _markermgr = null;

//street view mode
var _streetViewMode = false;

//marqueur de prÃ©visualisation
var _markerPreview = null;

//Cercle de selection et centre courant
var _selectedCircle = null;
var _currentPointSelected = null;
var _temporaryCircle = null;


//Icones des marqueurs
var _iconMarkers = Array();
//_iconMarkers[1] = new GIcon(G_DEFAULT_ICON);
//_iconMarkers[1].image = "images/marker_bleu_f.png";

//http://blog.pascal-martin.fr/post/4-Google-Maps-Marqueurs-fenetres-informations
//http://code.google.com/p/gmaps-utility-library/source/browse/trunk/
_iconMarkers[1] = MapIconMaker.createMarkerIcon({
    width: 18,
    height: 24,
    primaryColor: '343397'
});
_iconMarkers[2] = MapIconMaker.createMarkerIcon({
    width: 18,
    height: 24,
    primaryColor: '3399FE'
});
_iconMarkers[3] = MapIconMaker.createMarkerIcon({
    width: 18,
    height: 24,
    primaryColor: '339833'
});
_iconMarkers[4] = MapIconMaker.createMarkerIcon({
    width: 18,
    height: 24,
    primaryColor: '99CB33'
});
_iconMarkers[5] = MapIconMaker.createMarkerIcon({
    width: 18,
    height: 24,
    primaryColor: 'FEFE33'
});
_iconMarkers[6] = MapIconMaker.createMarkerIcon({
    width: 18,
    height: 24,
    primaryColor: 'FE9933'
});
_iconMarkers[7] = MapIconMaker.createMarkerIcon({
    width: 18,
    height: 24,
    primaryColor: 'FC3301'
});
_iconMarkers[8] = MapIconMaker.createMarkerIcon({
    width: 18,
    height: 24,
    primaryColor: 'FC3365'
});
_iconMarkers[9] = MapIconMaker.createMarkerIcon({
    width: 18,
    height: 24,
    primaryColor: '970264'
});


//Icone saisie
//var _userIcon = new GIcon(G_DEFAULT_ICON);
//_userIcon.image = "images/ylw-pushpin.png";
var _userIcon = MapIconMaker.createMarkerIcon({
    width: 100,
    height: 60,
    primaryColor: 'FFFFFF'
});



function drawCircle(center, radius, thickness, opacity, temporary) {
	
	
	if (!center) return;
	
	//Function created by Chris Haas
	var circleQuality = 5;			//1 is best but more points, 5 looks pretty good, too
	var M = Math.PI / 180;			//Create Radian conversion constant
	var L = _map.getBounds();		//Holds copy of map bounds for use below
	var sw = L.getSouthWest();
	var ne = L.getNorthEast();

	//The map is not completely square so this calculates the lat/lon ratio
	// this works because we create a square map
	var circleSquish = (ne.lng() - sw.lng()) / (ne.lat() - sw.lat());

	var points = [];							//Init Point Array
	//Loop through all degrees from 0 to 360
	for(var i=0; i<360; i+=circleQuality){
		var P = new GLatLng(
			center.lat() + (radius * Math.sin(i * M)),
			center.lng() + (radius * Math.cos(i * M)) * circleSquish
			);
		points.push(P);
	}
	points.push(points[0]);	// close the circle
	
	
	//Gestion du cercle onmouseover
	if (temporary == true) {		
		color='#FFFFFF';		
		if (_temporaryCircle) 
			_map.removeOverlay(_temporaryCircle);
		_temporaryCircle = new GPolyline(points, color, thickness, opacity)	
		_map.addOverlay(_temporaryCircle);		 
	}
	else //Gestion du cercle onclick
	{
		color='#0000FF';
		if (_selectedCircle) 
			_map.removeOverlay(_selectedCircle);
		_selectedCircle = new GPolyline(points, color, thickness, opacity)
		_map.addOverlay(_selectedCircle);
		_currentPointSelected = center;
	}
}


function drawSelectionCircle(point){
	drawCircle(point, 2000000 / (Math.pow(_map.getZoom(), 8)), 1, 1.0, false);
}

function drawTemporarySelectionCircle(point){
	drawCircle(point, 2000000 / (Math.pow(_map.getZoom(), 8)), 1, 1.0, true);
}


/*
 * Chargement de la carte
 */
function loadMap(){

    //Sort si deja chargee
    if (_map != null) {
        return;
    }
    
    //showWait();
    
    //trace du client
    ajaxTrace(navigator.userAgent);
    //alert(navigator.appName);
    //alert(navigator.appVersion)
    
    //initialise la carte
    /////////////////////
    if (GBrowserIsCompatible()) {
        _map = new GMap2(document.getElementById("map"));
        _map.setCenter(new GLatLng(_latInit, _longInit), _zoomInit);
        ajaxTrace("loadMap");
    }
    else {
        alert("Navigateur non compatible GoogleMaps! Utilisez Internet Explorer ou FireFox");
        ajaxTrace("loadMap: ERROR");
        
        //hideWait();
        return;
    }
    
    //Define control on the map
    ///////////////////////////
    _map.enableDoubleClickZoom();
    _map.enableContinuousZoom();
	_map.enableScrollWheelZoom();
    //_map.addControl(new GOverviewMapControl());
    //_map.addControl(new GLargeMapControl());
    //_map.addControl(new ExtLargeMapControl({type : "small"}));
	
	var extLargeMapControl1 = new ExtLargeMapControl(); //{type : "small"});
    _map.addControl(extLargeMapControl1);
	
   // _map.addControl(new GMapTypeControl(true));
    
    
    _map.addMapType(G_PHYSICAL_MAP);
    _map.setMapType(G_PHYSICAL_MAP); //G_PHYSICAL_MAP);
    //G_PHYSICAL_MAP.getMinimumResolution = function () { return 10 };
    //G_NORMAL_MAP.getMinimumResolution = function () { return 10 };
    
    //Create geocoder for adress search
    ///////////////////////////////////
    _geocoder = new GClientGeocoder();
    
    
    //marker manager
    _markermgr = new MarkerManager(_map);
    
	
	
	
	
	
	//crÃ©e le marquer de prÃ©visualisation	
	/*var iconMarker = MapIconMaker.createMarkerIcon({
	    width: 40,
	    height: 40,
	    primaryColor: '343397'
	});	 
	iconMarker.image = "images/eskapadia_carte_france_tourisme.jpg";	
    var mkrOptions = {
        title: "prev",
        icon: iconMarker,
        clickable: true
    };
    _markerPreview=new GMarker(_map.getCenter(), mkrOptions);
	
	_map.addOverlay(_markerPreview);*/
    
	
	
	
	
	
	
    //Add click callback for adding a marker    
    /*GEvent.addListener(_map, "click", myfunctionCB);
     function myfunctionCB(marker, point){
     }*/
    //Add zoom capture function
    ///////////////////////////
    GEvent.addListener(_map, "zoomend", myfunctionCB2);
    function myfunctionCB2(marker, point){
     
	 	//reinit
		document.getElementById('trop_de_fiches').style.display='none';
	 
		//si on monte en zoom et que l'on est en edition
		if ((_map.getZoom() >= 12)&&(_editMode==true)){
			_map.setMapType(G_NORMAL_MAP);
		}			        
		//si on monte en zoom et que l'on est en mode navigation
        else if ((_map.getZoom() >= 15)&&(_editMode==false)) {
		 	_map.setMapType(G_SATELLITE_MAP);
		 }
		 else{
		 	  //alert('zoomend');
       		 _map.setMapType(G_PHYSICAL_MAP);
		 }
		
		
        if (_allowUpdate) {
            checkForUpdate();
        }
        
        //reaffiche le marqueur d'edition
        if (_editMode) {
        
            //recentrer sur customMarker
            _customMarker.show();
            _map.setCenter(_customMarker.getPoint());
        }
        
		
		//Gestion du cercle de selection			 
		drawSelectionCircle(_currentPointSelected);
		
        //trace
        ajaxTrace("zoomend:" + _map.getZoom());
        
        //alert('zoomend-finish');
    }
    
    //Event MoveEnd ////////////////////////////////////    
    GEvent.addListener(_map, "moveend", myfunctionCB3);
    function myfunctionCB3(marker, point){
    
		//reinit
		document.getElementById('trop_de_fiches').style.display='none';

	
        if (_allowUpdate) {
            checkForUpdate();
        }
        
        //alert('moveend');        
        //ajaxTrace("moveend");
    }
    
    
    //cr?er le marqueur edition
    ///////////////////////////
    _customMarker = new GMarker(_map.getCenter(), {
        clickable: false,
        draggable: true,
        icon: _userIcon
    });
    
    _map.addOverlay(_customMarker);
    _customMarker.hide();
    
    //evennement de recuperation de la position
    GEvent.addListener(_customMarker, "dragend", function(point){
    
        //renseignement des coordonn?es sur la fiche
        if (document.getElementById("tbxLongitude")) 
            document.getElementById("tbxLongitude").value = point.x;
        if (document.getElementById("tbxLatitude")) 
            document.getElementById("tbxLatitude").value = point.y;
    });
    
    //hideWait();
    
    
    
    
    //Initialisation Street view 	
    ////////////////////////////
    
    document.getElementById('panorama').style.display = 'block';
    
    _myPano = new GStreetviewPanorama(document.getElementById("panorama")); //, panoramaOptions);	
    GEvent.addListener(_myPano, "error", handleNoFlash);
        
    //overlay streetview
    _ovlStreetView = new GStreetviewOverlay();
 	//fenwayPark = new GLatLng(48.6584278, -4.3907546); //cote bretonne
	fenwayPark = new GLatLng(48.8577975, 2.2951984); //tour eiffel	
    _myPano.setLocationAndPOV(fenwayPark);
        
    if (_streetViewMode == true) {
        _map.addOverlay(_ovlStreetView);
    }    
    
    GEvent.addListener(_map, "click", myfunctionClick);
    function myfunctionClick(marker, latlng){
    
        if (_streetViewMode == false) 
            return;
        
        document.getElementById('panorama').style.display = 'block';
        
       /* if (marker) {
        	
			//GME: parfois une erreur!!!
								
            var id = marker.getTitle();
            //alert('marker='+id);
            
            $.ajax({
                type: "POST",
                url: "getInfosFicheSV.php",
                data: "id=" + id,
                success: function(responseHtml){
                    var divImg = document.getElementById("panorama");
                    divImg.innerHTML = responseHtml;
                }
            });
        }
        else {*/
        
            fenwayPark = new GLatLng(latlng.y, latlng.x);
            //myPOV = {yaw:370.64659986187695,pitch:-20};
            _myPano.setLocationAndPOV(fenwayPark); //, myPOV);			
	   //}
    }
    
    function handleNoFlash(errorCode){
        //GME: document.getElementById('panorama').style.display='none';
    
    
        /*GME: 	    
        
         if (errorCode == FLASH_UNAVAILABLE) {
        
         alert("Error: Flash doesn't appear to be supported by your browser");
        
         return;
        
         }
        
         */
        
    }
    
}

/*
 * localisation d'adresse
 */
function localiser(adresse, cp, ville){

    //adresse ? rechercher
    var adr1 = adresse + ' ' + cp + ' ' + ville;
    
    //position du marqueur par d?faut
    var pointRes = _map.getCenter();
    _customMarker.show();
    _customMarker.setPoint(pointRes);
    _map.setCenter(pointRes);
    
    
    //recherche de lieu  
    if (_geocoder) {
    
        _geocoder.getLatLng(adr1, function(point){
        
            if (!point) {
                alert("Cette adresse est introuvable! \nMerci de positionner manuellement la bulle blanche.");
            }
            else {
            
                //born? en france
                if ((point.x > -5.5) & (point.x < 9) & (point.y > 41.9) & (point.y < 51.3)) {
                
                    //position du marqueur
                    _map.setZoom(_zoomMax);
                    pointRes = point;
                    
                    //alert(pointRes.x);
                    
                    //renseignement des coordonn?es sur la fiche
                    if (document.getElementById("tbxLongitude")) 
                        document.getElementById("tbxLongitude").value = point.x;
                    if (document.getElementById("tbxLatitude")) 
                        document.getElementById("tbxLatitude").value = point.y;
                    
                    //affichage du marqueur
                    _customMarker.show();
                    _customMarker.setPoint(pointRes);
                    _map.setCenter(pointRes);
                    
                    alert("Votre adresse a ete localisee. Verifiez qu'elle correspond bien au lieu souhaite, \net si ce n'est pas le cas, deplacez la bulle blanche.");
                    
                }
                else {
                    alert("Cette adresse n'est pas en France! \nMerci de positionner manuellement la bulle blanche.");
                }
            }
        });
    }
    else {
        alert("Cette adresse est introuvable! \nMerci de positionner manuellement la bulle blanche.");
    }
    
}


/*
 * M?thode d'entr?e de la mise ? jour des marqueurs
 */
function checkForUpdate(){


    //Si les mises ? jour sont bloqu?es (optim)
    //on sort
    if (_allowUpdate == false) {
        return false;
    }
    
    //Si on depasse la zone ou si rien de charge	 
    var lim = _map.getBounds();
    var pointSW = lim.getSouthWest();
    var pointNE = lim.getNorthEast();
    
    var lat1 = pointSW.y;
    var long1 = pointSW.x;
    var lat2 = pointNE.y;
    var long2 = pointNE.x;
    if ((_zoneLoaded == false) ||
    (long1 < _zoneLoadedXMIN) ||
    (long2 > _zoneLoadedXMAX) ||
    (lat1 < _zoneLoadedYMIN) ||
    (lat2 > _zoneLoadedYMAX)) {
    
        //on charge les points pour la zone de vue courante
        updatePoints();
    }
    else {
        return false;
    }
    
}


/*
 * Mise ? jour des points affich?s
 */
function updatePoints(){

    //empeche plusieurs MAJ simultanee (qui ne devrait pas se produire en fait)
    _allowUpdate = false;
    
    
    //alert("updatePOINTS");
    
    //sablier
    showWait();
    
    var bound = _map.getBounds();
    var pointSW = bound.getSouthWest();
    var pointNE = bound.getNorthEast();
    var lat1 = pointSW.y;
    var long1 = pointSW.x;
    var lat2 = pointNE.y;
    var long2 = pointNE.x;
    
    //zone chargee
    _zoneLoadedXMAX = long2 + (long2 - long1) * _zoneLoadedDeltaFen;
    _zoneLoadedXMIN = long1 - (long2 - long1) * _zoneLoadedDeltaFen;
    _zoneLoadedYMAX = lat2 + (lat2 - lat1) * _zoneLoadedDeltaFen;
    _zoneLoadedYMIN = lat1 - (lat2 - lat1) * _zoneLoadedDeltaFen;
    
    //nettoyage total des marqueurs
    clearAllMarkers();
    
	
	//VÃ©rifier les rubriques cochÃ©es
	chktype1 = document.getElementById('chktype1').checked;
	chktype2 = document.getElementById('chktype2').checked;
	chktype3 = document.getElementById('chktype3').checked;
	chktype4 = document.getElementById('chktype4').checked;
	chktype5 = document.getElementById('chktype5').checked;
	chktype6 = document.getElementById('chktype6').checked;
	chktype7 = document.getElementById('chktype7').checked;
	 
	
	//GME: TEST
	//_map.addOverlay(_markerPreview);
	
    //ferme les eventuels infos ouvertes
    //_map.closeInfoWindow();
    
    //DEBUG: polylignes   
    /*var point1 = new GLatLng(lat2, long1);
     var point2 = new GLatLng(lat2, long2);
     var point3 = new GLatLng(lat1, long2);
     var point4 = new GLatLng(lat1, long1);
     var polyline1 = new GPolyline([point1, point2, point3, point4, point1], "#FF0000", 1);
     _map.addOverlay(polyline1);
     
     var point1b = new GLatLng(_zoneLoadedYMAX, _zoneLoadedXMIN);
     var point2b = new GLatLng(_zoneLoadedYMAX, _zoneLoadedXMAX);
     var point3b = new GLatLng(_zoneLoadedYMIN, _zoneLoadedXMAX);
     var point4b = new GLatLng(_zoneLoadedYMIN, _zoneLoadedXMIN);
     var polyline2 = new GPolyline([point1b, point2b, point3b, point4b, point1b], "#0000FF", 1);
     _map.addOverlay(polyline2);*/
    if (_editMode) 
        _customMarker.show();
    
	
	/*
	$.ajax({
	  url: 'getPoints.php',
	  async: false,
	  dataType: 'json',
	  data: "minLatA="+_zoneLoadedYMIN+"&maxLatA=_"+_zoneLoadedYMAX+
	  		"&minLongA="+_zoneLoadedXMIN+"&maxLongA="+_zoneLoadedXMAX,
	  success: function (json) {
	     //alert('NB FICHES='+json.points.length);
        
        //Gestion trop forte densit? de points
        if (json.points.length > 150) {
            //clearAllMarkers();
            //alert("Il existe trop de fiches dans cette zone, veuillez zoomer avec le bouton '+'");
            
            _map.openInfoWindowHtml(_map.getCenter(), "<b>Il y a trop de fiche dans cette zone. </b><br/>Veuillez <a href=\"#\" onclick=\"_map.setZoom(_map.getZoom()+1); return false;\">zoomer</a> sur la carte.");
            
            _zoneLoaded = false;
        }
        else {
        
            //LA ZONE EST CHARGEE
            _zoneLoaded = true;
            
            //Pour chaque fiche r?cup?r?e    
            var i;
            for (i = 0; i < json.points.length; i++) {
            
                //Cr?er le marqueur
                var point = new GLatLng(json.points[i].la, json.points[i].lo);
                var type = json.points[i].tp;
                var idMarker = json.points[i].id;
                var intitule = json.points[i].intitule;
				
                //ajoute ce marqueur
                //ajouterMarker(point, idMarker, type);                			
                var customMarker = creerMarker(point, idMarker, type, intitule);
                
                //Stocke du marqueur dans un tableau              
                _arrMarkers[idMarker] = customMarker;
                
                //Ajoute le marqueur sur la map
                //_map.addOverlay(customMarker);                
                _markermgr.addMarker(customMarker, 3);
                
            }
            
            _markermgr.refresh();
            
            //Affiche l'info bulle pour un markeur donn?
            ////////////////////////////////////////////
            if (_displayInfoForThisMarkerId != -1) {
                showInfoBulle(_displayInfoForThisMarkerId);
            }
            
        }
        
        hideWait();
        
        _allowUpdate = true;
		 
		 
	  }
	});
	*/
	
	
	/*$.ajax({
	  url: 'getPoints.php',
	  async: false,
	  dataType: 'json',
	  data: "minLatA="+_zoneLoadedYMIN+"&maxLatA=_"+_zoneLoadedYMAX+
	  		"&minLongA="+_zoneLoadedXMIN+"&maxLongA="+_zoneLoadedXMAX+
			"&chktype1="+chktype1+
			"&chktype2="+chktype2+
			"&chktype3="+chktype3+
			"&chktype4="+chktype4+
			"&chktype5="+chktype5+
			"&chktype6="+chktype6+
			"&chktype7="+chktype7,	
       error : function(XMLHttpRequest, textStatus, errorThrown){
			alert('erreur: updatePoints');
		},		
	   success: function (jsonObj, textStatus) {
	      alert('OK1');
		  alert(jsonObj.points.length);
	  },
	  
	 });*/
	
	/*
	jQuery.ajax({
		url : "getPoints.php",
		dataType : 'json',
		cache : false,
		succcess : function(jsonObj, textStatus){
			alert('ok2');
		},
		error : function(XMLHttpRequest, textStatus, errorThrown){
			alert('erreur2');
		},
		async : false
	});
		 */
 
 
    //Va chercher les points ? ajouter 
    //////////////////////////////////
    /*$.getJSON("getPoints.php", {		
        "minLatA": _zoneLoadedYMIN,
        "maxLatA": _zoneLoadedYMAX,
        "minLongA": _zoneLoadedXMIN,
        "maxLongA": _zoneLoadedXMAX,
		"chktype1": chktype1,
		"chktype2": chktype2,
		"chktype3": chktype3,
		"chktype4": chktype4,
		"chktype5": chktype5,
		"chktype6": chktype6,
		"chktype7": chktype7		
    }, function(json){*/
	
	
	$.ajax({
	  url: 'getPoints.php',
	  async: false,
	  dataType: 'json',
	  data: "minLatA="+_zoneLoadedYMIN+"&maxLatA="+_zoneLoadedYMAX+
	  		"&minLongA="+_zoneLoadedXMIN+"&maxLongA="+_zoneLoadedXMAX+
			"&chktype1="+chktype1+
			"&chktype2="+chktype2+
			"&chktype3="+chktype3+
			"&chktype4="+chktype4+
			"&chktype5="+chktype5+
			"&chktype6="+chktype6+
			"&chktype7="+chktype7,	
       error : function(XMLHttpRequest, textStatus, errorThrown){
			alert('erreur: updatePoints');
		},		
	   success: function(json){
	    	//alert('success');
			
	   	//alert('NB FICHES='+json.points.length);
					
			//Gestion trop forte densit? de points
			if (json.points.length > 120) {
				//clearAllMarkers();
				//alert("Il existe trop de fiches dans cette zone, veuillez zoomer avec le bouton '+'");            						
				//_map.openInfoWindowHtml(_map.getCenter(), "<b>Il y a trop de fiche dans cette zone. </b><br/>Veuillez <a href=\"#\" onclick=\"_map.setZoom(_map.getZoom()+1); return false;\">zoomer</a> sur la carte.");            
				document.getElementById('trop_de_fiches').style.display = 'block';
				
				_zoneLoaded = false;
			}
			else {
			
				//LA ZONE EST CHARGEE
				_zoneLoaded = true;
				
				//Pour chaque fiche r?cup?r?e    
				var i;
				for (i = 0; i < json.points.length; i++) {
				
					//Cr?er le marqueur
					var point = new GLatLng(json.points[i].la, json.points[i].lo);
					var type = json.points[i].tp;
					var idMarker = json.points[i].id;
					var intitule = json.points[i].intitule;
					
					//ajoute ce marqueur
					//ajouterMarker(point, idMarker, type);                			
					var customMarker = creerMarker(point, idMarker, type, intitule);
					
					//Stocke du marqueur dans un tableau              
					_arrMarkers[idMarker] = customMarker;
					
					//Ajoute le marqueur sur la map
					//_map.addOverlay(customMarker);                
					_markermgr.addMarker(customMarker, 3);
					
				}
				
				_markermgr.refresh();
				
				//Affiche l'info bulle pour un markeur donn?
				//Emule un click pour un marqueur donne
				////////////////////////////////////////////
				if (_displayInfoForThisMarkerId != -1) {
					//showInfoBulle(_displayInfoForThisMarkerId);
					clicEmulation(_displayInfoForThisMarkerId);
				}
				
			}
			
			//hideWait();
			
			//_allowUpdate = true;
			
		//});
		}});
 
 	hideWait();
	
	_allowUpdate = true;
 	//alert('synchrone');    
}


//GMN: 
/*function ajouterMarker(point, idPoint, iType){
 var iconMarker = _iconMarkers[iType];
 var mkrOptions = {
 title: idPoint,
 icon: iconMarker,
 clickable: true
 };
 
 var customMarker = new GMarker(point, mkrOptions);
 
 //Stocke du marqueur dans un tableau
 _arrMarkers[idPoint] = customMarker;
 
 //Ajoute le marqueur sur la map
 _map.addOverlay(customMarker);
 
 
 //Event clic ////////////////////////////////////
 GEvent.addListener(customMarker, "click", function(){
 
 //alert('GMN:OK');
 var id = customMarker.getTitle();
 
 //requete AJAX pour afficher la fiche dans l'info bulle
 ///////////////////////////////////////////////////////
 $.ajax({
 type: "GET",
 url: "getInfosFiche.php",
 data: "id=" + id,
 success: function(responseHtml){
 
 customMarker.openInfoWindowHtml(responseHtml);
 
 //new selected marker
 //_selectedMarker = marker;
 }
 });
 
 });
 
 }*/
/*function createMarkerOverview(){
 var iconMarker = _iconMarkers[1];
 var mkrOptions = {
 title: idPoint,
 icon: iconMarker,
 clickable: true
 };
 var marker = new GMarker(point, mkrOptions);
 
 }*/
/* 
 * Cr?ation d'un marqueur GoogleMaps
 */
function creerMarker(point, idPoint, iType, intitule){

   var iconMarker = _iconMarkers[iType];
	
    var mkrOptions = {
        title: idPoint+"_"+intitule,
        icon: iconMarker,
        clickable: true
    };
    var marker = new GMarker(point, mkrOptions);
       
	//mouseover click
	GEvent.addListener(marker, "mouseover", function(point){
		
		//affecter l'image idPoint;
		
		//rÃ©cupÃ©ration de l'id
		elem = marker.getTitle().split('_');		
		var fiche_id = elem[0];
		 
		
		//GME: essai dÃ©calage pixel avec projection
		var sw = _map.getCurrentMapType().getProjection().fromLatLngToPixel(point,_map.getZoom()); 
        //alert( sw ); 		
		sw.x=sw.x+70;
		//sw.y=sw.y+110;
		sw.y=sw.y+5;
		pointToDisplay = _map.getCurrentMapType().getProjection().fromPixelToLatLng(sw,_map.getZoom());

		
		
		//GME: A OPTIMISER
		//crÃ©e le marquer de prÃ©visualisation	
		
		 var iconMarker = MapIconMaker.createMarkerIcon({
		    width: 96,
		    height: 60,
		    primaryColor: '343397'
		});	 
		iconMarker.image = "data/images/f"+fiche_id+"_c0_p1_min.jpg";	
	    var mkrOptions = {
	        title: "camping toto...",
	        icon: iconMarker,
	        clickable: true
	    }; 
		 
		 //GME: Trouver un ratio par rapport au zoom !!!!!!!!!!!!!!!!
		//var npt = new GLatLng(point.lat()-0.5/_map.getZoom(), point.lng());	
		
		if (_markerPreview!=null) _map.removeOverlay(_markerPreview);		
	    _markerPreview=new GMarker(pointToDisplay, mkrOptions);						
		_map.addOverlay(_markerPreview);
		
		//markerPreview.setImage("data/images/f"+fiche_id+"_c0_p1.jpg");		 
		//_markerPreview.setLatLng(point);
		
		//Dessine le cercle de selection	
		drawTemporarySelectionCircle(point);
		
	});
	
	
	//mouseout click
	GEvent.addListener(marker, "mouseout", function(point){
		if (_markerPreview!=null) _map.removeOverlay(_markerPreview);		
		if (_temporaryCircle!=null) _map.removeOverlay(_temporaryCircle);				 
	});
	
    //Event clic ////////////////////////////////////    
	//GEvent.addListener(marker, "click", clicReaction);
	
    GEvent.addListener(marker, "click", function(){
    		 
		clicReaction(marker);
	/*
	
        //rien en mode Street view
        if (_streetViewMode == true) 
            return;
        
		//rÃ©cupÃ©ration de l'id
		elem = marker.getTitle().split('_');		
		var fiche_id = elem[0];
		
        
        //trace l'action
        //ajaxTrace("Infos fiche "+id);     
        

		//Dessine le cercle de selection	
		drawSelectionCircle(marker.getPoint());
		 
		
		 //requete AJAX pour afficher le menu
    	$.ajax({
	        type: "POST",
	        url: "getPreviewFiche.php",
	        data: "id=" + fiche_id + "&nocache=false",
	        success: function(responseHtml){
	            var pnlView = document.getElementById("preview_fiche");
	            pnlView.innerHTML = responseHtml;
				
				
				//dessiner le cercle!
				//marker.getPoint();
	        }
    	});
	
		
        //requete AJAX pour afficher la fiche dans l'info bulle        
       // $.ajax({
       //     type: "POST",
       //     url: "getInfosFiche.php",
       //     data: "id=" + id,
       //     success: function(responseHtml){
       //         marker.openInfoWindowHtml(responseHtml);
                
				
				
        //    }
        //});
		
		*/
        
    });
    
    /*GEvent.addListener(marker, "click", function(){
     var id = marker.getTitle();
     showDetailsFiche(id,false);
     });*/
    return marker;
}


function clicReaction(marker){
	  
		//rien en mode Street view
        if (_streetViewMode == true) 
            return;
        
		//rÃ©cupÃ©ration de l'id
		elem = marker.getTitle().split('_');		
		var fiche_id = elem[0];
		
        
        //trace l'action
        //ajaxTrace("Infos fiche "+id);     
        

		//Dessine le cercle de selection	
		drawSelectionCircle(marker.getPoint());
		 
		
		 //requete AJAX pour afficher le menu
    	$.ajax({
	        type: "POST",
	        url: "getPreviewFiche.php",
	        data: "id=" + fiche_id + "&nocache=false",
	        success: function(responseHtml){
	            var pnlView = document.getElementById("preview_fiche");
	            pnlView.innerHTML = responseHtml;
				
				
				//dessiner le cercle!
				//marker.getPoint();
	        }
    	});

		 
		//Si le panneau détail fiche est ouvert, on le met à jour
		//Si l'on est en mode edition (mon compte), on l'ouvre
		if ((document.getElementById('current_fiche_win').style.display=='block')
			|| (_editMode==true))
		{
			showDetailsFiche(fiche_id,false);
		}
	
}

/*
 * Positionne le curseur Ã  une adresse donnÃ©e
 * et recherche des fiches
 */
function searchQuoiOu(quoi, ou){

    if ((quoi == "") && (ou == "")) {
        alert("Veuillez saisir un ou plusieurs mots-cles de recherche.");
        return;
    }
    
    //affiche les points
    if (_allowUpdate) {
        checkForUpdate();
    }
    
    //requete AJAX : recherche de fiche  
    ///////////////////////////////////
    if (_editMode == false) {

		updateListeFiches();
     
        //ouvrir l'onglet
        //startLoadingResults();
        //showPnlRes();
        
        /*$.ajax({
            type: "POST",
            url: "getResultatsQuoiOu.php",
            data: "quoi=" + quoi + "&ou=" + ou,
            success: function(responseHtml){
            
                var divResult = document.getElementById("inner_resultats");
                divResult.innerHTML = responseHtml;
                
                //sablier
                endLoadingResults();
            }
        });*/
    }
    
    
    //recherche de lieu google map
    //////////////////////////////
    if (_geocoder) {
    
        _geocoder.getLatLng(ou, function(point){
            if (!point) {
                //alert("Cette adresse est introuvable!");
            }
            else {
            
                //born? en france
                if ((point.x > -5.5) & (point.x < 9) & (point.y > 41.9) & (point.y < 51.3)) {
                
                    //empeche la mise ? jour pendant les actions de positionnement
                    _allowUpdate = false; //optim
                    adjustZoom();
                    _map.setCenter(point);
                    
                    //Mise a jour controlee
                    _allowUpdate = true;
                    
                    //alert('_allowUpdate='+_allowUpdate);
                    //checkForUpdate(); //GME: a voir pb asynchrone
                    updatePoints();
                    
                }
            }
        });
    }
    
    
}


/*
 * Positionne le curseur ? une adresse donn?e
 * et recherche des fiches
 */
function search(address){

    //alert('search');
    
    if (address == "") {
        alert("Veuillez saisir un ou plusieurs mots-cles de recherche.\nPar exemple: camping 35, auberge tarn, ...\n\n");
        return;
    }
    
    
    //requete AJAX : recherche de fiche  
    ///////////////////////////////////
    if (_editMode == false) {
    
        $.ajax({
            type: "POST",
            url: "getResultats.php",
            data: "search=" + address,
            success: function(responseHtml){
            
                //ouvrir l'onglet
                showPnlRes();
                
                var divResult = document.getElementById("inner_resultats");
                divResult.innerHTML = responseHtml;
            }
        });
        
    }
    
    
    //recherche de lieu google map
    //////////////////////////////
    if (_geocoder) {
    
        _geocoder.getLatLng(address, function(point){
            if (!point) {
                //alert("Cette adresse est introuvable!");
            }
            else {
            
                //born? en france
                if ((point.x > -5.5) & (point.x < 9) & (point.y > 41.9) & (point.y < 51.3)) {
                
                    //empeche la mise ? jour pendant les actions de positionnement
                    _allowUpdate = false; //optim
                    adjustZoom();
                    _map.setCenter(point);
                    
                    //Mise a jour controlee
                    _allowUpdate = true;
                    
                    //alert('_allowUpdate='+_allowUpdate);
                    //checkForUpdate(); //GME: a voir pb asynchrone
                    updatePoints();
                    
                }
            }
        });
    }
    
}

/*
 * Nettoie tous les marqueurs
 */
function clearAllMarkers(){

    //alert("clearAllMarkers");	 
    if (_markermgr) 
        _markermgr.clearMarkers();
    
    
    //retire les marqueurs 
    /*   _map.clearOverlays();*/
    delete _arrMarkers;
    _arrMarkers = new Array();
    
    //ajoute syst?matiquement le marqueur d'edition
    /*    _map.addOverlay(_customMarker);
    
     _customMarker.hide();
    
     */
    
}

/*
 * Se positionne sur une fiche
 */
function goToFiche(fiche_id){


    //sablier
    showWait();
    
    //requete AJAX pour recuperer la position et y aller
    /////////////////////////////////////////////////////
    $.ajax({
        type: "POST",
        url: "getCoordFiche.php",
        data: "id=" + fiche_id,
        success: function(response){
        
            if (response == "") {
                alert("fiche non trouvee.");
            }
            else {
            
            
                //empeche la mise ? jour pendant les actions de positionnement
                _allowUpdate = false; //optim
                //recupere la position lat/long			
                res = response.split(":");
                lat = res[0] / 1000000;
                lng = res[1] / 1000000;
                
                //stocke l'id pour affichage de l'info
               //GME: NON PLUS DINFOS BULLE _displayInfoForThisMarkerId = fiche_id;
                
                //niveau de zoom plus pr?cis en mode ?dition
                if (_editMode) {
                    _map.setZoom(_zoomMax);
                    _map.setCenter(new GLatLng(lat, lng));
                    
                    _customMarker.setPoint(new GLatLng(lat, lng));
                    _customMarker.show();
                }
                else {
                    //plus necessaire: adjustZoom();
                    _map.panTo(new GLatLng(lat, lng));
					
					//Dessine le cercle de selection	
					//drawSelectionCircle(new GLatLng(lat, lng));						 
					
					_displayInfoForThisMarkerId = fiche_id;
					
					//gÃ©nÃ¨re un clic sur la fiche !!!!!!!
					//var myMarker = _arrMarkers[fiche_id];
					 
					//alert(myMarker);
					//GEvent.trigger(myMarker, "click");
					
                }               
                
                //Mise ? jour controlee
                _allowUpdate = true;
                
                //alert('_allowUpdate BEFORE'+_allowUpdate);
                
                var status = checkForUpdate();
                
                //info bulle affich?e, m?me sans mise ? jour effective
                if (status == false) {
                    if (_displayInfoForThisMarkerId != -1) {
                        clicEmulation(_displayInfoForThisMarkerId);
                    }
                }				
            }
            
            //fin sablier
            hideWait();
            
        }
    });
    
}



function clicEmulation(fiche_id){

	var myMarker = _arrMarkers[fiche_id];    
    if (myMarker) {    
        GEvent.trigger(myMarker, "click");
        //GEvent.trigger(myMarker, "mouseover");
        
        //raz
        _displayInfoForThisMarkerId = -1;
    }
    else {
        //nothing
    }    

}



function adjustZoom(){
    var current_zoom = _map.getZoom();
    if (current_zoom <= _zoomInit) 
        _map.setZoom(9);
}




/*
 * Passage en mode edition
 */
function setEditMode(value){
    _editMode = value;
    
    if (_editMode) {
        _customMarker.setPoint(_map.getCenter());
        _customMarker.show();
		
		//masquer la liste des fiches
		hide('liste_fiches');
		
		//extenstion de la map
		document.getElementById('center').style.top='125px';
		
		//Modification du menu
		show('sous_menu2');
		hide('sous_menu1');
		
    }
    else {
        _customMarker.hide();
						
		//afficher la liste des fiches
		show('liste_fiches');		
		
		//reduction de la map
		document.getElementById('center').style.top='286px';	
		
		//Modification du menu
		show('sous_menu1');
		hide('sous_menu2');
			
    }
    //alert('change mode edition: '+value);

}

/*
 * type= latest_fiches, promos, on_map, search
 */
function updateListeFiches(){
	
	 
	//cases cochÃ©es des rubriques
	var arrChk = Array();
	arrChk[1] = document.getElementById('chktype1').checked;
	arrChk[2] = document.getElementById('chktype2').checked;
	arrChk[3] = document.getElementById('chktype3').checked;
	arrChk[4] = document.getElementById('chktype4').checked;
	arrChk[5] = document.getElementById('chktype5').checked;
	arrChk[6] = document.getElementById('chktype6').checked;
	arrChk[7] = document.getElementById('chktype7').checked;	 	
	rubriquesExclues = "rubriques_exclues=";  
	for (iTyp=1; iTyp<=7; iTyp++){
		if (arrChk[iTyp]==false){ 		
			if (rubriquesExclues != "rubriques_exclues=") 
				rubriquesExclues = rubriquesExclues + ",";			
			rubriquesExclues = rubriquesExclues + iTyp;
		}		
	}

	//case promo cochÃ©e ou dÃ©cochÃ©e
	//var filterPromos = document.getElementById('chkpromos').checked;

	//parametres de recherche
	var quoi=document.getElementById('search_quoi').value;
	var ou=document.getElementById('search_ou').value;

	//Onglet actif du menu
	//idenfitie par la var globale _modeListeFiche
		
	//requete AJAX  
    $.ajax({
        type: "POST",
        url: "getListeFiches.php",
        data: rubriquesExclues+"&type="+_modeListeFiche+"&quoi="+quoi+"&ou="+ou,
        success: function(responseHtml){
            var pnlView = document.getElementById("inner_liste_fiches");
            pnlView.innerHTML = responseHtml;
        }
    });	 
}
 

function initLoad(){
	
	//vide les champs de recherche
	document.getElementById('search_quoi').value="";
	document.getElementById('search_ou').value="";
	
	updateListeFiches("latest_fiches"); 
	loadMap(); 
	updatePoints();
}

function activateStreetView(){
	_streetViewMode = true;
	if (_map) {
		_map.addOverlay(_ovlStreetView);
	}
}

function desactivateStreetView(){
	_streetViewMode = false;
	if (_map) {
		_map.removeOverlay(_ovlStreetView);
	}	
}

