/************************************************************************************/
/** Variables globales **************************************************************/
/** ********************************************************************************* */

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

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

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

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

// Positionnement initial sur bretagne
var _zoomInit = 8;
var _latInit = 48.2
var _longInit = -2.9

var _zoomMax = 15;

// Info-bulle
var _displayInfoForThisMarkerId = -1;

// autorise l'update sur event
var _allowUpdateMarkers = 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;
var _markermgrWikipedia = null;

// street view mode
var _streetViewMode = false;
var _streetViewClient = null;
var _streetViewMarker = null;

// marqueur de prévisualisation
var _markerPreview = null;

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

// Memorisation région courante selectionnée
var _currentSelectedRegionDept = 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 : 16,
	height : 22,
	primaryColor : '343397'
});
_iconMarkers[2] = MapIconMaker.createMarkerIcon({
	width : 16,
	height : 22,
	primaryColor : '3399FE'
});
_iconMarkers[3] = MapIconMaker.createMarkerIcon({
	width : 16,
	height : 22,
	primaryColor : '339833'
});
_iconMarkers[4] = MapIconMaker.createMarkerIcon({
	width : 16,
	height : 22,
	primaryColor : '99CB33'
});
_iconMarkers[5] = MapIconMaker.createMarkerIcon({
	width : 16,
	height : 22,
	primaryColor : 'FEFE33'
});
_iconMarkers[6] = MapIconMaker.createMarkerIcon({
	width : 16,
	height : 22,
	primaryColor : 'FE9933'
});
_iconMarkers[7] = MapIconMaker.createMarkerIcon({
	width : 16,
	height : 22,
	primaryColor : 'FC3301'
});
_iconMarkers[8] = MapIconMaker.createMarkerIcon({
	width : 16,
	height : 22,
	primaryColor : 'FC3365'
});
_iconMarkers[9] = MapIconMaker.createMarkerIcon({
	width : 16,
	height : 22,
	primaryColor : '970264'
});

//information icon
_iconMarkers[10] = new GIcon(G_DEFAULT_ICON);
_iconMarkers[10].image = "images/information-trans.png";
_iconMarkers[10].iconSize = new GSize(16,16);


// 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'
});


var _svIcon = new GIcon(G_DEFAULT_ICON);
_svIcon.image = "images/ylw-pushpin.png"; //ico-street.png"; //oeil.gif"; //ylw-pushpin.png";
//_svIcon.iconSize = new GSize(50,50);

// var tooltip = null;

var _modeListeFiche = "latest_fiches"; // ou "search";

function ajaxTrace(message) {

	// requete AJAX
	$.ajax({
		type : "GET",
		url : "ajaxTrace.php",
		data : "message=" + message,
		success : function(responseHtml) {
		}
	});
}


function pausecomp(millis)
{
  var date = new Date();
  var curDate = null;
  
  do { curDate = new Date(); }
  while(curDate-date < millis);
} 

// Gestion des affichages
function show(controlId) {
	document.getElementById(controlId).style.display = 'block';
}
function hide(controlId) {
	document.getElementById(controlId).style.display = 'none';
}

function showCurrentFiche() {
	show('panorama_current_fiche');
	hide('panorama_welcome');
	hide('panorama_streetview');
	_streetViewMarker.hide();
}
function hideCurrentFiche() {
	hide('panorama_current_fiche');
}
function showStreetView() {
	hide('panorama_current_fiche');
	hide('panorama_welcome');
	show('panorama_streetview');
	_streetViewMarker.show();
}
function hideStreetView() {
	hide('panorama_streetview');
}

function showWait() {
	show('waiting');
}
function hideWait() {
	hide('waiting');
}
function showMonCompte() {
	show('mon_compte');
	//hide('accueil');
	setEditMode(true);
}
function showAccueil() {
	hide('mon_compte');
	//show('accueil');
	setEditMode(false);
}
function showProposerFiche() {
	show('proposer_fiche');
}
function hideProposerFiche() {
	hide('proposer_fiche');
}

/*
 * Affiche le détail de la fiche donnée
 */
function showDetailsFiche(fiche_id) {

	// requete AJAX pour afficher la description
	$.ajax({
		type : "POST",
		url : "getDetailsFicheDesc.php",
		data : "id=" + fiche_id,
		success : function(responseHtml) {

			// actualisation du panneau
			var pnlView = document.getElementById("current_fiche_description");
			pnlView.innerHTML = responseHtml;

			// Ajout d'une info ficheId pour l'ajout de commentaire si
			// nécessaire
			var fieldCommentId = document.getElementById('commentFicheId');
			if (fieldCommentId)
				fieldCommentId.innerHTML = fiche_id;

			// reinitialisation de la shadowbox
			Shadowbox.init({
				skipSetup : true
			});
			Shadowbox.setup();

			// affiche la fenêtre
			showCurrentFiche();
		}
	});

}

/*
 * ajout d'un commentaire
 */
function addComment() {

	// Récupération des données
	var ficheId = document.getElementById('commentFicheId').innerHTML;
	var comment = document.getElementById('tbxFrontCommentaire').value;

	// requete AJAX pour afficher la fiche
	$
			.ajax({
				type : "POST",
				url : "addComment.php",
				data : "ficheId=" + ficheId + "&comment=" + comment,
				success : function(responseHtml) {

					if (responseHtml == "ERROR") {
						alert('une erreur est survenue! Merci de contacter le support Eskapadia \npar le lien "signaler une erreur" en bas de la page.');
					} else {
						// Rafraichit la page
						showDetailsFiche(ficheId);
					}
				}
			});

}

/*
 * Trace un cercle (sélection de fiche)
 */
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);
		updateOverviewTarget();
		ajaxTrace("loadMap");
	} else {
		alert("Navigateur non compatible GoogleMaps! Utilisez Internet Explorer, FireFox ou Google Chrome");
		ajaxTrace("loadMap: ERROR");
		// hideWait();
		return;
	}

	// Définit les controles
	// /////////////////////////
	_map.enableDoubleClickZoom();
	_map.enableContinuousZoom();
	_map.enableScrollWheelZoom();
	
	// _map.addControl(new GOverviewMapControl());
	// _map.addControl(new GLargeMapControl();
	// _map.addControl(new ExtLargeMapControl({type : "small"}));
	_map.setUIToDefault();

	//_map.addControl(new GSmallMapControl());
	/*var extLargeMapControl = new ExtLargeMapControl();
	_map.addControl(extLargeMapControl);*/
	// _map.addControl(new GMapTypeControl(true));

	_map.addMapType(G_PHYSICAL_MAP);
	_map.setMapType(G_PHYSICAL_MAP);
	// G_PHYSICAL_MAP.getMinimumResolution = function () { return 10 };
	// G_NORMAL_MAP.getMinimumResolution = function () { return 10 };

	// geocoder
	_geocoder = new GClientGeocoder();

	// marker manager
	_markermgr = new MarkerManager(_map);
	_markermgrWikipedia = new MarkerManager(_map);

	// evenements sur la carte
	GEvent.addListener(_map, "zoomend", eventMapZoomEnd);
	GEvent.addListener(_map, "moveend", eventMapMoveEnd);
	GEvent.addListener(_map, "dragend", eventMapDragEnd);
	GEvent.addListener(_map, "click", eventMapClick);

	// crée 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;
    });


	// crée le marqueur street view
	_streetViewMarker = new GMarker(_map.getCenter(), {
		clickable : false,
		draggable : false,
		icon : _svIcon
	});
	_map.addOverlay(_streetViewMarker);
	_streetViewMarker.hide();
	
	
	// Initialisation Street view
	initStreetView();

	// hideWait();
}

/*
 * Evenement ZoomEnd sur la carte
 */
function eventMapZoomEnd(marker, point) {

	// reinitialisation
	document.getElementById('trop_de_fiches').style.display = 'none';

	// si on monte en zoom et que l'on est en mode 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);
	}

	// mise à jour des marqueurs
	if (_allowUpdateMarkers) {
		checkForUpdateMarkers();
	}

	// reaffiche le marqueur d'edition
	if (_editMode) {

		// recentrer sur customMarker
		_customMarker.show();
		_map.setCenter(_customMarker.getPoint());
	}

	// active le street view en fonction du zoom
	if (_map.getZoom() >= 13) {
		if (_streetViewMode == false)
			activateStreetView();
	} else {
		if (_streetViewMode == true)
			desactivateStreetView();
	}

	// Gestion du cercle de selection
	drawSelectionCircle(_currentPointSelected);

  // meteo
  loadMeteo();

	// trace
	// ajaxTrace("zoomend:" + _map.getZoom());
}

/*
 * Evenement MoveEnd sur la carte
 */
function eventMapMoveEnd(marker, point) {

	// reinit
	document.getElementById('trop_de_fiches').style.display = 'none';

	if (_allowUpdateMarkers) {
		checkForUpdateMarkers();
	}

	// mise à jour du pointeur de l'overview
	updateOverviewTarget();
	
	// meteo
  //GME: TEMPO : loadMeteo();
}

/*
 * Evenement DragEnd sur la carte
 */
function eventMapDragEnd(marker, 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;
		
	// meteo
  //GME: TEMPO : loadMeteo();	
}

/*
 * Evenement Clic sur la carte
 */
function eventMapClick(marker, latlng) {

	// cas de sortie
	if (latlng == null)
		return;
	if (!_streetViewMode)
		return;

	// Nouveau point de vue
	_streetViewClient.getNearestPanoramaLatLng(latlng, function(newPoint) {
		if (newPoint != null) {

			// Point de vue		 
		  _myPano.remove(); 
			_myPano.setLocationAndPOV(newPoint);
			 	
			//met à jour la position du pointeur streetview
			//_streetViewMarker.show();
			_streetViewMarker.setLatLng(newPoint);		
			
			//AZE;
			//pausecomp(4000);
			 
			
			// Affiche la vue streetview
			showStreetView();

		}
	});
}

/*
 * Initialisation du composant StreeView
 */
function initStreetView() {

	// cas de sortie
	if ((_myPano) && (_ovlStreetView))
		return;

	// client
	_streetViewClient = new GStreetviewClient();

	// création de l'element streetview
	_myPano = new GStreetviewPanorama(document
			.getElementById("panorama_streetview")); // , panoramaOptions);
	// GEvent.addListener(_myPano, "error", handleNoFlash);

	
	
	
	// Création de l'overlay
	_ovlStreetView = new GStreetviewOverlay();

	// function handleNoFlash(errorCode) {
	// alert("Error: Votre navigateur n'est pas compatible avec ce site.
	// Utilisez Google Chrome, Internet Explorer ou Firefox.");
	// return;
	// }
}

/*
 * Met à jour la target d'overview
 */
function updateOverviewTarget() {
	var latMin = 40.7;
	var latMax = 51;
	var longMin = -7;
	var longMax = 10.4;
	var imgX = 170;
	var imgY = 150;

	var offX = (_map.getCenter().x - longMin) / (longMax - longMin) * imgX;
	var offY = -(_map.getCenter().y - latMax) / (latMax - latMin) * imgY;

	// déplacement du pointeur
	document.getElementById('pointer_map').style.left = offX + "px";
	document.getElementById('pointer_map').style.top = offY + "px";

}

/*
 * Déplace la carte sur un point
 */
function goToPoint(lat, lon) {
	_map.setCenter(new GLatLng(lat, lon));
}

/*
 * Récupère les coordonnées de l'overview et se déplace en fonction sur la carte
 */
function setPositionFromOverview(event) {

	var offX = (event.layerX) ? event.layerX : event.offsetX;
	var offY = (event.layerY) ? event.layerY : event.offsetY;

	// déplacement du pointeur
	document.getElementById('pointer_map').style.left = offX + "px";
	document.getElementById('pointer_map').style.top = offY + "px";

	// traduction des coordonn�es
	var latMin = 40.7;
	var latMax = 51;
	var longMin = -7;
	var longMax = 10.4;

	var imgX = 170;
	var imgY = 150;

	var longitude = longMin + (offX / imgX) * (longMax - longMin);
	var latitude = latMax - (offY / imgY) * (latMax - latMin);

	// repositionnement de la carto
	setZoom(8);
	goToPoint(latitude, longitude);
}

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

	// adresse a 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 checkForUpdateMarkers() {

	// Si les mises a jour sont en cours, on sort
	if (!_allowUpdateMarkers) {
		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 affiches
 */
function updatePoints() {
 
	// empeche plusieurs MAJ simultanee (qui ne devrait pas se produire en fait)
	_allowUpdateMarkers = false;

	// 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;

	if (_editMode)
		_customMarker.show();

	// Va chercher les points à ajouter
	// ////////////////////////////////
	
	$
			.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,
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					alert('erreur1: updatePoints' + errorThrown);

					// rétablissement état initial
					hideWait();
					_allowUpdateMarkers = true;

				},
				success : function(json) {

					// Gestion trop forte densite de points
					if (json.points.length > 250) {

						document.getElementById('trop_de_fiches').style.display = 'block';
						_zoneLoaded = false;

					} else {

						// LA ZONE EST CHARGEE
						_zoneLoaded = true;

						// Pour chaque fiche recuperee
						var i;
						for (i = 0; i < json.points.length; i++) {

							// Creer 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);

							// Stockage 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);
						}

					}

					// rétablissement état initial
					hideWait();
					_allowUpdateMarkers = true;

				} // fin success
			});
}

/*
 * Creation d'un marqueur
 */
function creerMarker(point, idPoint, iType, intitule) {

	// Création du marqueur
	var iconMarker = _iconMarkers[iType];
	var mkrOptions = {
		title : idPoint + "_" + intitule,
		icon : iconMarker,
		clickable : true
	};
	var marker = new GMarker(point, mkrOptions);

	// Evenements sur le marqueur
	GEvent.addListener(marker, "mouseover", eventMarkerMouseOver);
	GEvent.addListener(marker, "mouseout", eventMarkerMouseOut);
	GEvent.addListener(marker, "click", eventMarkerClic);

	return marker;
}

/*
 * Creation d'un marqueur wikipedia
 */
function creerMarkerWikipedia(point, idPoint, intitule, wikipediaUrl) {

	// Création du marqueur
	var iconMarker = _iconMarkers[10];
	var mkrOptions = {
		title : intitule,
		icon : iconMarker,
		clickable : true
	};
	var marker = new GMarker(point, mkrOptions);

	// Evenements sur le marqueur
	//GEvent.addListener(marker, "mouseover", eventMarkerMouseOver);
	//GEvent.addListener(marker, "mouseout", eventMarkerMouseOut);
	GEvent.addListener(marker, "click", eventMarkerWikipediaClic);
	
	
	

	return marker;
}




/*
 * Evenement MouseOver sur le marqueur
 */
function eventMarkerMouseOver(point) {

	var marker = this;

	// récupération de l'id
	elem = marker.getTitle().split('_');
	var fiche_id = elem[0];

	// 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 : 130,
		height : 80,
		primaryColor : '343397'
	});
	iconMarker.image = "data/images/f" + fiche_id + "_c0_p1_min.jpg";
	var mkrOptions = {
		title : "title...",
		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);

}

/*
 * Evenement MouseOut sur le marqueur
 */
function eventMarkerMouseOut(point) {
	if (_markerPreview != null)
		_map.removeOverlay(_markerPreview);
	if (_temporaryCircle != null)
		_map.removeOverlay(_temporaryCircle);
}

/*
 * Evenement Clic sur le marqueur
 */
function eventMarkerClic(point) {

	var marker = this;

	// 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());

	// affiche le detail
	showDetailsFiche(fiche_id);

	// Si l'on est en mode edition (mon compte), on l'ouvre
	/*
	 * if
	 * ((document.getElementById('panorama_current_fiche').style.display=='block') ||
	 * (_editMode==true)) { showDetailsFiche(fiche_id); }
	 */

}


/*
 * Evenement Clic sur le marqueur
 */
function eventMarkerWikipediaClic(point) {
  //alert('TODO marqueur wikipedia')  
  window.open ('http://fr.wikipedia.org/wiki/Bretagne', 'nom_interne_de_la_fenetre', config='height=300, width=750, toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, directories=no, status=no')
}

/*
 * Recherche multi critères
 */
function searchMulti() {

	showWait();
	
	// Mise à jour de la liste des fiches
	updateListeFiches();
 	
	// Mise à jour de la carte

	// lieu de recherche (prioritaire)
	var nomLieu = document.getElementById('critere_nomlieu').value;
 
	// si region/dept ==> on dézoom
	var regiondept = document.getElementById('select_regiondept').value;
	var regiondeptFiltered = '';
	var posSeparator = regiondept.indexOf(':');	
	if (posSeparator != -1)
		regiondeptFiltered = regiondept.substring(0, posSeparator);


	if (regiondeptFiltered != _currentSelectedRegionDept) {
		// dézoomer
		_map.setZoom(_zoomInit);
	}
	_currentSelectedRegionDept = regiondeptFiltered;

	var addressToSearch = '';
	if (nomLieu) {
		addressToSearch = nomLieu;
	} else {
		addressToSearch = regiondeptFiltered;
	}
 
 	
	// recherche de lieu google map
	// ////////////////////////////
	if (_geocoder) {

		_geocoder.getLatLng(addressToSearch, function(point) {
			//if (!point) {
				// alert("Cette adresse est introuvable!");
		//		hideWait();
	//		} else {

				// borne en france
				//		& (point.y < 51.3)) {
//
					// empeche la mise a jour pendant les actions de
					// positionnement
					_allowUpdateMarkers = false; // optim

					// GME: ?adjustZoom();
					//if (unZoom)
						//_map.setZoom(_zoomInit);

					if (point) _map.setCenter(point);

					// Mise a jour controlee
					_allowUpdateMarkers = true;
					updatePoints();
					 
				//}else{	
					//Hors france : pas de mise à jour des points
					//_map.setCenter(point);
					//hideWait();
				//}
			//}
		});
	}
	
	//hideWait();
}

/*
 * Positionne le curseur a une adresse donnée et recherche des fiches
 */
function DEPRECATED_search(address, unZoom) {

	// alert("function search");

	if (address == "") {
		alert("Veuillez saisir un ou plusieurs mots-cles de recherche.\nPar exemple: camping 35, auberge tarn, ...\n\n");
		return;
	}

	// Décodage éventuel dans le cas régions/départements
	// var initialAddress = address;
	var posSeparator = address.indexOf(':');
	if (posSeparator != -1)
		address = address.substring(0, posSeparator);

	// 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; } }); }
	 */

	// GME: à gérer
	// if (_editMode == false)
	// requete AJAX : Mise à jour de la liste des fiches
	// //////////////////////////////////////////////////
	updateListeFiches();


	// 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
					_allowUpdateMarkers = false; // optim

					// GME: ?adjustZoom();

					if (unZoom)
						_map.setZoom(_zoomInit);

					_map.setCenter(point);

					// Mise a jour controlee
					_allowUpdateMarkers = true;

					// alert('_allowUpdateMarkers='+_allowUpdateMarkers);
					// checkForUpdateMarkers(); //GME: a voir pb asynchrone
					updatePoints();

					// GME: test
					/*
					 * for (elem in _arrMarkers) { // récupération de l'id elem =
					 * marker.getTitle().split('_'); var fiche_id = elem[0]; }
					 */

				}
			}
		});
	}

}

/*
 * 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
				_allowUpdateMarkers = 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.setZoom(_zoomMax);
					_map.setCenter(new GLatLng(lat, lng));
					// _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
				_allowUpdateMarkers = true;

				// alert('_allowUpdateMarkers BEFORE'+_allowUpdateMarkers);

				var status = checkForUpdateMarkers();

				// info bulle affich?e, m?me sans mise ? jour effective
				// if (status == false) {
				// if (_displayInfoForThisMarkerId != -1) {
				// clicEmulation(_displayInfoForThisMarkerId);
				// }
				// }
			}

			// affiche le d�tail de la fiche
			showDetailsFiche(fiche_id);

			// 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);
}

function setZoom(nivZoom) {
	_map.setZoom(nivZoom);
}

/*
 * Passage en mode edition
 */
function setEditMode(value) {
	
	//alert('setEditMode');
	
	_editMode = value;

	if (_editMode) {
		_customMarker.setPoint(_map.getCenter());
		_customMarker.show();

		// masquer la liste des fiches
		//hide('liste_fiches');

		
		// Modification du menu
		//show('sous_menu2');
		//hide('sous_menu1');

	} else {
		_customMarker.hide();

		// afficher la liste des fiches
		//show('liste_fiches');

	
		// Modification du menu
		//show('sous_menu1');
		//hide('sous_menu2');

	}
	// alert('change mode edition: '+value);

}

function mycarousel_itemLoadCallback(carousel, state) {
	for ( var i = carousel.first; i <= carousel.last; i++) {
		if (carousel.has(i)) {
			continue;
		}

		if (i > mycarousel_itemList.length) {
			break;
		}

		carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[i - 1]));
	}
};

function removeAndAnimate(obj, i) {

	var e = obj.get(i);
	// var d = obj.dimension(e);
	// if (i < obj.first) obj.list.css(obj.lt, $jc.intval(obj.list.css(obj.lt))
	// + d + 'px');

	e.remove();
	/*
	 * obj.options.size--;
	 * 
	 * var di = obj.options.visible != null ? Math.ceil(obj.clipping() /
	 * obj.options.visible) : null; var li = obj.list.children('li'); var self =
	 * obj;
	 * 
	 * if (li.size() > 0) { var wh = 0, i = obj.options.offset;
	 * li.each(function() { self.format(obj, i++); wh += self.dimension(obj,
	 * di); });
	 * 
	 * obj.list.css(obj.wh, wh + 'px'); }
	 */

	obj.scroll(0, true);
	obj.buttons();

}


/*
 * is_init=true ==> affichage latest_update
 */
function updateListeFiches(latest_fiches) {

	//showWait(); GME: spécialiser le sablier par items
	
	// Décodage éventuel dans le cas régions/départements
	var regiondept = document.getElementById('select_regiondept').value;
	 
	// 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 <= 6; 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;

	$.ajax({
		type : "POST",
		url : "getListeFiches.php",
		data : rubriquesExclues + "&type=multicriteres" + "&region_dept= "
				+ regiondept + "&latest_fiches=" + latest_fiches,
		success : function(responseHtml) {

			// remplissage des UL/LI
			var pnlView = document.getElementById("liste_fiches");
			// var pnlView = document.getElementById("mycarousel");
			pnlView.innerHTML = responseHtml;

			// reconstruction du carousel
			$('.first-and-second-carousel').jcarousel({
				vertical : true,
				scroll : 2
			});

			//hideWait();
		}
	});
 
}


function loadMeteo() {

  //GME: pour l'instant problème avec google weather France
  //GME: pour l'instant problème avec google weather France
  //GME: pour l'instant problème avec google weather France
  return;

  if (_map.getZoom() < 9) {
      document.getElementById('divmeteo').style.display = "none";
      return;
  }
  else{
      document.getElementById('divmeteo').style.display = "block";
  }

  var longi = _map.getCenter().x;
  var lati = _map.getCenter().y; 
    
             
  // requete AJAX
	$.ajax({
		type : "GET",
		url : "weather.php", 
		dataType : 'json',		
		data : "latitude=" + lati + "&longitude="+ longi,
		error : function(XMLHttpRequest, textStatus, errorThrown) {
					alert('erreur1: meteo' + errorThrown);
				},
		success : function(json) {
		  //alert(json);
		  alert('RECUP METEO JSON');
		
		  //alert("Conditions="+ json.current.condition + "  Temperature=" + json.current.temp + "Icon=" + json.current.icon);
		  
		  document.getElementById('iconmeteo').src = "http://www.google.com/ig/images/weather/"+json.current.icon;
		  document.getElementById('iconmeteo0').src = "http://www.google.com/ig/images/weather/"+json.prev0.icon;
		  document.getElementById('iconmeteo1').src = "http://www.google.com/ig/images/weather/"+json.prev1.icon;
		  document.getElementById('iconmeteo2').src = "http://www.google.com/ig/images/weather/"+json.prev2.icon;
		  
		  document.getElementById('indicmeteo').innerHTML = "<br/>"+json.current.temp+"°";
		  document.getElementById('indicmeteo0').innerHTML = json.prev0.day + "<br/>"+json.prev0.low+"°" + "<br/>"+json.prev0.high+"°";;
		  document.getElementById('indicmeteo1').innerHTML = json.prev1.day + "<br/>"+json.prev1.low+"°" +"<br/>"+json.prev1.high+"°";
		  document.getElementById('indicmeteo2').innerHTML = json.prev2.day + "<br/>"+json.prev2.low+"°" +"<br/>"+json.prev2.high+"°";
		  
		  
		  //alert(responsHtml);
		}
	});
    
        /*
  
     $.ajax({
				url : url_geonames,
				async : false,
				dataType : 'html',
				data : "lweather=,,," + lati + ","
						+ longi,
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					alert('erreur1: updatePoints' + errorThrown);
 
				},
				success : function(json) {
				  alert(json);
         }
                 
        
     });  */
  //http://www.google.com/ig/api?weather=,,,4550000,-7358300


}

//GME: fonction test
function loadGeonames() {

    var longi = _map.getCenter().x;
    var lati = _map.getCenter().y; 
    var radius = 20;
    var url_geonames = "http://api.geonames.org/findNearbyWikipediaJSON";
        
    var bound = _map.getBounds();
	  var pointSW = bound.getSouthWest();
	  var pointNE = bound.getNorthEast();
	  var sud = pointSW.y;
	  var ouest = pointSW.x;
	  var nord = pointNE.y;
	  var est = pointNE.x;
    
    //BOUND BOX
    //http://api.geonames.org/wikipediaBoundingBox?north=48.8&south=47.2&east=-1.9&west=-4.5&username=eskapadia
    
    //http://api.geonames.org/citiesJSON?north=48.8&south=47.2&east=-1.9&west=-4.5&lang=fr&username=eskapadia
    //http://api.geonames.org/cities?north=48.8&south=47.2&east=-1.9&west=-4.5&lang=fr&username=eskapadia
    
    //lat=48.247179&lng=-1.729072&username=eskapadia&lang=fr&radius=5
       
    url_geonames = "http://api.geonames.org/wikipediaBoundingBoxJSON";
       
       
    $.ajax({
				url : url_geonames,
				async : false,
				dataType : 'json',
				/*data : "lat=" + lati + "&lng="
						+ longi + "&username=eskapadia&lang=fr&" + radius
						+ "&radius=" + radius,*/						
				data : "north="+nord+"&south="+sud+"&east="+est+"&west="+ouest+"&lang=fr&username=eskapadia",
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					alert('erreur1: updatePoints' + errorThrown);
 
				},
				success : function(json) {
             
            //alert(json.geonames);
                  
            //RANK > 20      
                  
            //alert("NBPOINTS="+json.geonames.length);
                              
            //var strg="";
                             
            //Creation des wiki marqueurs                  
            var i;
					  for (i = 0; i < json.geonames.length; i++) {

              //ne prend que les villes
              if (json.geonames[i].feature != "city") continue;
    
              //ne prend que les rank élevés
              //if (json.geonames[i].rank >= 80) continue;
 
							// Creer le marqueur
							//strg = strg + json.geonames[i].title +  +  json.geonames[i].lng;
							
							point = new GLatLng(json.geonames[i].lat,json.geonames[i].lng);
							idMarker = 100000+i;							
							intitule =  json.geonames[i].title; // + json.geonames[i].rank; //title;
							
							wikipediaURL = json.geonames[i].wikipediaUrl;
							
							// ajoute ce marqueur
							// ajouterMarker(point, idMarker, type);
							var newMarker = creerMarkerWikipedia(point, idMarker,
									intitule),wikipediaURL;

							// Stockage du marqueur dans un tableau
							//_arrMarkerswikipedia[idMarker] = newMarker;

							// Ajoute le marqueur sur la map
							// _map.addOverlay(customMarker);
							_markermgr.addMarker(newMarker, 3);    
                       
							
						} 
            //alert(strg); 
            _markermgrWikipedia.refresh();
              
        }
     });
			 
}

function initLoad() {

	// GME: TEMPO
	updateListeFiches(false); 
	loadMap();
	updatePoints();

	// GME:
	// activateStreetView();

	// lightbox
	// $('#panorama_welcome_texte a').lightBox();

	// Retrait du splash screen
	$('#splashscreen').fadeOut("slow");

}

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

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


window.onresize = function(event) {
	
	//redimensionne le street view
	if (_myPano) _myPano.checkResize();	
}

