var infoWindow;
var emajineMap = function(divmap)
{
	this.divmap = divmap;
	infoWindow = new google.maps.InfoWindow;
	this.map = new google.maps.Map(document.getElementById(divmap));
	this.map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
	this.map.setOptions({zoom:8});
	this.latlngbounds = new google.maps.LatLngBounds();
	this.nbMarkers = 0;
	this.editableMarkers = {};
	this.infowindows = [];
	this.pov = null;
	this.isStreetviewLoaded = false;
	this.currentEditSpot = null;
	this.currentEditSpotIsNew = false;

	google.maps.event.addListener(this.map, 'click', function() {
      infoWindow.close();
    });

    if (parent.googleMapBindEvents) {
		parent.googleMapBindEvents(this.map, google);
    }

	this.onInit();
};

emajineMap.prototype.onInit = function()
{
};

emajineMap.prototype.setInfowindowSize = function(infoWindow)
{
	if ($('.googleMapBulle').width() > 100) {
		// on considère qu'une css est correctement appliquée sinon
		// on applique une taille par défault
		return;
	}

	$('.googleMapBulle, .gm-style-iw').css({
		'width':'250px',
		'height':'150px',
		'overflow-x': 'hidden',
	});
};

emajineMap.prototype.setAddLocationIconUrl = function(iconUrl)
{
	this.addLocationIconUrl = iconUrl;
};

emajineMap.prototype.getAddLocationIconUrl = function()
{
	return this.addLocationIconUrl;
};

emajineMap.prototype.setSize = function(width, height)
{
	this.width  = width;
	this.height = height;
};

emajineMap.prototype.setPov = function(pov)
{
	this.pov  = pov;
};

emajineMap.prototype.setFormUrlSpotAdd = function(formUrl)
{
	this.formUrlSpotAdd = formUrl;
};

emajineMap.prototype.setFormUrlSpotEdit = function(formUrl)
{
	this.formUrlSpotEdit = formUrl;
};

emajineMap.prototype.setMarkerEditable = function(marker, spotId)
{
	var self = this;

	self.editableMarkers[spotId.toString()] = marker;

	google.maps.event.addListener(marker, 'click', function(event) {
		self.editMarker(spotId);
	});

	if (!self.latlngbounds.contains(marker.getPosition())) {
		self.latlngbounds.extend(marker.getPosition());
	}
};

emajineMap.prototype.editMarker = function(spotId)
{
	var self = this;
	$.getJSON('googlemap-json-' + spotId + '.html', function(data) {
		self.createFormPoint(self.editableMarkers[spotId.toString()], data, true);
	});
};

emajineMap.prototype.reverseGeoCode = function(address)
{
	var self = this;

	if (address == '') {
		if (parent) {
			parent.simpleAlert("Information", "<div class=\"pb20\">Vous devez renseigner le champ adresse</div>", "fermer");
		}
		return;
	}

	self.geocoder(address, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			self.map.setCenter(results[0].geometry.location);
			self.map.setZoom(15);
		} else if (parent) {
			parent.simpleAlert("Adresse inconnue", address, "fermer");
		}
	});
};

emajineMap.prototype.geocoder = function(address, callback)
{
	var geocoder = new google.maps.Geocoder();

	geocoder.geocode({'address': address}, callback );
};


emajineMap.prototype.manualGeoCode = function(callback)
{
	this.createFormPoint(this.map.getCenter(), {}, false, callback);
};

emajineMap.prototype.openMarker = function(marker)
{
	var position = marker.getPosition();
	this.setPoint(position.lat(), position.lng());
	this.setPointToCoord();
	google.maps.event.trigger(marker, 'click');
}

emajineMap.prototype.createFormPoint = function(coordOrMarker, values, isEdit, callback)
{
	var self       = this,
		isPaned    = false,
		width      = Math.round(this.width * 0.7, 0),
		infowindow = null;

	// créer ou modifie le point
	if (isEdit) {
		var marker = coordOrMarker;
		var coord  = marker.getPosition();
		marker.setDraggable(true);
		marker.setCursor('move');
	} else {
		var coord  = coordOrMarker;
		var	marker = new google.maps.Marker({
			map: self.map,
			position: coord,
			icon: self.getAddLocationIconUrl(),
			draggable: true,
			cursor: 'move'
		});
	}

	var hidingInfo = google.maps.event.addListener(marker, 'dragstart', function(event) {
		infowindow.close();
	});

	var reCenter = google.maps.event.addListener(marker, 'dragend', function(event) {
		infowindow.open(self.map, marker);
		self.setInfowindowSize(infowindow);
	});

	// créer l'infobulle
	infowindow = new google.maps.InfoWindow({
			maxWidth: width
		}),
		content    =
		'<div id="contentSpot">' +
			'<div id="spotMainPanel">' +
				'<span id="spotIconCurrent" style="float:right"></span>' +
				'<p>'+
					'<label for="spotName">Nom :</label>' +
					'<input id="spotName" type="text">'+
				'</p>' +
				'<p>'+
					'<label for="spotDesc">Description : <a href="#">Édition avancée</a></label>' +
					'<textarea id="spotDesc" cols="25" rows="3"></textarea>' +
				'</p>' +
				'<p class="txtcenter">' +
					'<a href="#" id="spotBtnValid">Valider</a> ' +
					'<a href="#" id="spotBtnCancel">Annuler</a>' +
				'</p>' +
			'</div>' +
		'</div>';


	// repositionne le point pour faire place à l'infobulle
	if (!isEdit) {
		google.maps.event.addListener(this.map, 'center_changed', function()
		{
			setTimeout(function() {
				if (!isPaned) {
					self.map.panBy(0, -40);
					isPaned = true;
				}
			}, 1000);
		});
	}

	// action sur l'infobulle
	google.maps.event.addListener(infowindow, 'domready', function()
	{
		var content     = $('#contentSpot'),
			nom         = $('#spotName', content),
			desc        = $('#spotDesc', content),
			ckeLink     = $('label a', desc.parent()),
			iconCurrent = $('#spotIconCurrent', content),
			mainPanel   = $('#spotMainPanel', content),
			btnValid    = $('#spotBtnValid', content),
			btnCancel   = $('#spotBtnCancel', content),
			advanced    = parent.window.jQuery('#marquerIconSelector', parent.window.document),
			url         = (isEdit) ? self.formUrlSpotEdit : self.formUrlSpotAdd;

		advanced.hide();

		// rempli le formulaire avec les valeurs
		// sauf l'icone qui est chargée plus loin
		if (isEdit) {
			nom.val(values.nom);
			desc.val(values.description);
			url = url.replace('{spotId}', values.id);
		}

		// switch de layer dans l'infobulle
		var togglePanel = function(type) {

			advanced.toggle();

			if (type == 'icon') {
				$('#divimarquer', advanced).show();
				$('#divdescriptionspot', advanced).hide();
				advanced.addClass('panelIconSelector').removeClass('panelCkEditor');
			} else if (type == 'cke') {
				$('#divimarquer', advanced).hide();
				$('#divdescriptionspot', advanced).show().find('.fck_preview').hide();
				advanced.addClass('panelCkEditor').removeClass('panelIconSelector');
			} else {

			}

			return false;
		};

		// ferme l'infobulle
		var cancel = function() {

			advanced.hide();

			infowindow.close();
			infowindow.setMap(null);

			if (isEdit) {
				marker.setDraggable(false);
				marker.setCursor('normal');
				marker.setPosition(coord);
				self.map.setCenter(coord);
			} else {
				marker.setMap(null);
			}

			self.currentEditSpot = null;

			// appelle la callback si elle existe
			if (typeof callback == 'function') {
				callback();
			}

			return false;
		};

		// post le formulaire
		var valid = function() {
			var inputIcon   = $('#div_imarquer_selector .radio:checked', advanced).val(),
				inputCustom = $('#custom_imarquer', advanced).val(),
				coord       = marker.getPosition();

			var data = {
				'icon': (inputCustom != '') ? inputCustom : inputIcon,
				'spot': coord.lat() + '|' + coord.lng(),
				'nom': nom.val(),
				'descriptionSpot': desc.val()
			};

			if (data.nom == '') {
				if (typeof parent.simpleAlert == 'function') {
					parent.simpleAlert("Information",
						"Veuillez entrer un nom",
						"fermer");
					return false;
				}
			} else {
				// création ou mise à jour de spot
				$.post(url, data, function() {
					if (parent && parent.window != window) {
						var activeLayer = parent.window.jQuery('#iframe_contener', parent.window.document).parent().find('.active_tab a');
						activeLayer.trigger('click');
					}
				});
				return cancel();
			}
		};

		iconCurrent.click(function() { togglePanel('icon'); });
		ckeLink.click(function() { togglePanel('cke'); });
		btnValid.click(valid);
		btnCancel.click(cancel);
		google.maps.event.addListener(infowindow, 'closeclick', cancel);

		// charge le selecteur d'icon via ajax
		// see: mods\Emajine_Ressources_Center_Spot::makeForm();
		advanced.load(url, function()
		{
			$('#divspot', advanced).remove();
			$('#divnom', advanced).remove();
			$('#divdescriptionspot label', advanced).remove();

			$('a.closeBox', advanced).unbind('click').click(function(e)
			{
				e.preventDefault();
				e.stopPropagation();

				var inputIcon   = $('#div_imarquer_selector .radio:checked', advanced),
					inputCustom = $('#custom_imarquer', advanced);

				if (inputCustom.val() != '') {
					var icon = inputCustom.parent().find('.icon img').first();
				} else {
					var icon = inputIcon.parent().find('img');
				}

				iconCurrent.children().remove();
				iconCurrent.append(icon.clone());

				parent.window.CKEDITOR.instances['descriptionspot'].updateElement();
				desc.val($('#descriptionspot', advanced).val());

				togglePanel();
			}).appendTo($('a.closeBox', advanced).closest('.wrap'));

			var antiDoubleAction = true;

			$('.pin', advanced).click(function() {
				if (!antiDoubleAction) {
					$('.delete', advanced).trigger('click');
					$('a.closeBox', advanced).trigger('click');
				}
				antiDoubleAction = ! antiDoubleAction;
			});

			var c = $('div.formw', advanced).children();
			iconCurrent.append(c.first().find('img').clone());
			c.first().remove();
			c.show();
		});
	});

	// centre la carte sur le point et affiche l'infobulle (et masque les autres)
	self.closeAllInfowindow();
	self.map.setCenter(coord);
	infowindow.setContent(content);
	infowindow.open(this.map, marker);
	self.infowindows.push(infowindow);
	self.setInfowindowSize(infowindow);

	// supprime l'edition précédante non validée si il y en a une
	if (self.currentEditSpot != null && self.currentEditSpotIsNew) {
		// supprime le spot précédent
		self.currentEditSpot.setMap(null);
	}

	// enregistre l'édition courante
	self.currentEditSpot = marker;
	self.currentEditSpotIsNew = !isEdit;
};

emajineMap.prototype.setNewMarkerPosition = function(event, url)
{
	var position = event.latLng;
	url += '&lat=' + position.lat() + '&lng=' + position.lng();
	$.get(url);
}

emajineMap.prototype.closeAllInfowindow = function()
{
	var i;
	for (i in this.infowindows) {
		if (this.infowindows[i]) {
			this.infowindows[i].close();
			this.infowindows[i].setMap(null);
			this.infowindows[i] = null;
		}
	}
};

// initialise les points du centre
emajineMap.prototype.setPoint = function(latitude, longitude)
{
	this.point = new google.maps.LatLng(latitude, longitude);
	// le centre de la carte (qui n'est pas un spot,
	// ne doit pas être utiliser pour centrer sur les spots)
	//this.latlngbounds.extend(this.point);
};

emajineMap.prototype.setPointToUserLocation = function()
{
	var self = this;
	if(navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {
			self.setPoint(position.coords.latitude, position.coords.longitude);
			self.setPointToCoord();
		}, function() {
			// no geolocatisation
		});
	} else {
		// no geolocatisation
	}
};

emajineMap.prototype.setPointToCoord = function()
{
	this.setCenter();
};

emajineMap.prototype.setPointToSpot = function()
{
	this.setCenter(true);
};

// initialise le zoom
emajineMap.prototype.setZoom = function(zoom)
{
	this.zoom = zoom;
	this.map.setOptions({zoom: zoom});
};

// creation du point centrale
emajineMap.prototype.setCenter = function(ignorePoint)
{
	if (ignorePoint || typeof this.point === 'undefined') {
		if (this.nbMarkers < 2) {
			this.map.setCenter(this.latlngbounds.getCenter(), this.zoom ? this.zoom : 1);
		} else {
			var maxZoom = this.map.getZoom();
			this.map.fitBounds(this.latlngbounds);
			// si tous les marqueurs sont trop proche le niveau de zoom de la carte est
			// considéré comme le niveau de zoom maximum.
			if (this.map.getZoom() > maxZoom) {
				this.map.setZoom(maxZoom);
			}
		}
	} else {
		this.map.setCenter(this.point, this.zoom ? this.zoom : 8);
	}
};

emajineMap.prototype.setType = function(type) {
	this.map.setMapTypeId(type);
};

emajineMap.prototype.setStreetview = function(callback) {

	if (this.isStreetviewLoaded) {
		this.map.getStreetView().setVisible(true);
		if (callback) callback(true);
		return;
	}

	var self     = this;
		zoom     = this.map.getZoom(),
		stview   = new google.maps.StreetViewService(),
		pano     = this.map.getStreetView(),
		status   = null;

	this.isStreetviewLoaded = true;

	stview.getPanoramaByLocation(this.map.getCenter(), 50, function(panoInfo, status)
	{
		if (status == google.maps.StreetViewStatus.OK) {
			pano.setPosition(panoInfo.location.latLng);
			pano.setZoom((zoom >= 1 && zoom <= 5) ? zoom : 3);
			var	pov = self.pov.split('|');
			pano.setPov({heading:parseFloat(pov[0], 10), pitch:parseFloat(pov[1], 10)});
			pano.setVisible(true);
			if (callback) callback(true);
			google.maps.event.addListener(pano, 'closeclick', function() {
				self.setZoom(23);
			});
		} else {
			self.isStreetviewLoaded = false;
			if (parent.alertStreetViewImpossible) {
				parent.alertStreetViewImpossible();
	  		}
			if (callback) callback(false);
		}
	});
};

// Fixe les controles
// @deprecated
emajineMap.prototype.setControl = function(control)
{
	return false;
};

emajineMap.prototype.setZoomControl = function(control)
{
	var options = {};
	options.zoomControl = true;
	this.map.setOptions(options);
};

emajineMap.prototype.setOptions = function(options)
{
	this.map.setOptions(options);
};

emajineMap.prototype.setGoogleBar = function(bool)
{
	// Déprécié et supprimé en e-majine 1.9
};

emajineMap.prototype.setDefaultControl = function()
{
	this.map.setOptions({keyboardShortcuts: true});
};

emajineMap.prototype.addTrafficLayer = function()
{
	this.trafficLayer = new google.maps.TrafficLayer();
	this.trafficLayer.setMap(this.map);
};

emajineMap.prototype.addTransitLayer = function()
{
	this.transitLayer = new google.maps.TransitLayer();
	this.transitLayer.setMap(this.map);
};

emajineMap.prototype.addWeatherLayer = function()
{
	// supprimé en API 3.22
};

emajineMap.prototype.addBikeLayer = function()
{
	this.bikeLayer = new google.maps.BicyclingLayer();
	this.bikeLayer.setMap(this.map);
};

emajineMap.prototype.addKmlLayer = function(file)
{
	this.kmlLayer = new google.maps.KmlLayer({url: file});
	this.kmlLayer.setMap(this.map);
};

emajineMap.prototype.switchKmlLayer = function(file)
{
	if (this.kmlLayer) {
		this.kmlLayer.setMap(null);
		this.kmlLayer = null;
	}
	this.addKmlLayer(file);
}

/******************************************************************************
 * LIVE *
******************************************************************************/

emajineMap.prototype.liveMapMode = function(value, callback)
{
	if (value == 'GM_MapMode_Street') {
		this.setStreetview(callback);
	} else {
		this.map.getStreetView().setVisible(false);
	}
};

emajineMap.prototype.liveType = function(value)
{
	switch(value) {
		case 'GM_Map_Normal'    : this.map.setMapTypeId(google.maps.MapTypeId.ROADMAP);   break;
		case 'GM_Map_Hybrid'    : this.map.setMapTypeId(google.maps.MapTypeId.HYBRID);    break;
		case 'GM_Map_Satellite' : this.map.setMapTypeId(google.maps.MapTypeId.SATELLITE); break;
		case 'GM_Map_Physical'  : this.map.setMapTypeId(google.maps.MapTypeId.TERRAIN);   break;
	}
};

emajineMap.prototype.liveCenter = function(value)
{
	switch (value) {
		case 'GM_MapCenter_Spot'  : this.setPointToSpot();         break;
		case 'GM_MapCenter_User'  : this.setPointToUserLocation(); break;
		case 'GM_MapCenter_Coord' : this.setPointToCoord();        break;
	}
};

emajineMap.prototype.liveZoom = function(value)
{
	this.map.setZoom(parseInt(value, 10));
};

emajineMap.prototype.liveStreetviewControl = function(value)
{
	this.map.setOptions({'streetViewControl': value});
};

emajineMap.prototype.liveZoomControl = function(value)
{
	// Supprimé en API 3.22
};

emajineMap.prototype.livePanControl = function(value)
{
	// Supprimé en API 3.22
};

emajineMap.prototype.liveScaleControl = function(value)
{
	this.map.setOptions({'scaleControl': value});
};

emajineMap.prototype.liveMapTypeControl = function(value)
{
	switch(value) {
		case 'GM_MapTypeControl_Default'       : value = google.maps.MapTypeControlStyle.DEFAULT;        break;
		case 'GM_MapTypeControl_DropDownMenu'  : value = google.maps.MapTypeControlStyle.DROPDOWN_MENU;  break;
		case 'GM_MapTypeControl_HorizontalBar' : value = google.maps.MapTypeControlStyle.HORIZONTAL_BAR; break;
	}
	this.map.setOptions({'mapTypeControlOptions': {'style': value}});
};

emajineMap.prototype.liveOverviewControl = function(value)
{
	// Supprimé en API 3.22
};

emajineMap.prototype.liveTraficLayer = function(value)
{
	if (value) {
		this.addTrafficLayer();
	} else {
		this.trafficLayer.setMap(null);
	}
};

emajineMap.prototype.liveBuswayLayer = function(value)
{
	if (value) {
		this.addTransitLayer();
	} else {
		this.transitLayer.setMap(null);
	}
};

emajineMap.prototype.liveMeteoLayer = function(value)
{
	// Supprimé en API 3.22
};

emajineMap.prototype.liveBicycleLayer = function(value)
{
	if (value) {
		this.addBikeLayer();
	} else {
		this.bikeLayer.setMap(null);
	}
};

emajineMap.prototype.liveKmlLayer = function(value)
{
	if (!value) {
		this.kmlLayer.setMap(null);
		this.kmlLayer = null;
	}
};
/******************************************************************************/


//initialisation de l'image du marker
emajineMap.prototype.setIcon = function(icon)
{
	this.tinyIcon = false;
	if (icon) {
		this.tinyIcon = {};
		this.tinyIcon.url = icon;
	}
};

// Creation d'un point
emajineMap.prototype.getMarker = function (latitude, longitude, icon)
{
	var marker = new google.maps.Marker();
	marker.setMap(this.map);
	if (this.tinyIcon) {
		marker.setIcon(this.tinyIcon);
	}
	if (icon !== '') {
		marker.setIcon(icon);
	}

	latitude  = parseFloat(latitude);
	longitude = parseFloat(longitude);

	if (!isNaN(latitude) && !isNaN(longitude)) {
		var point = new google.maps.LatLng(latitude, longitude);
		marker.setPosition(point);
		if (!this.latlngbounds.contains(point)) {
			this.latlngbounds.extend(point);
		}
	}
	return marker;
};

//Decrepated
emajineMap.prototype.getLabeledMarker = function (latitude,longitude,label)
{
	var point = new google.maps.LatLng(latitude, longitude);
	if (!this.latlngbounds.contains(point)) {
		this.latlngbounds.extend(point);
	}
	return new StyledMarker({styleIcon: new StyledIcon(StyledIconTypes.MARKER,{text:label}), position: point, map: this.map, icon: this.tinyIcon});
};

//Ajout du layer sur le marker (infobulle)
emajineMap.prototype.setMarker = function (marker,url) {
	var self = this;
	if(url) {
		google.maps.event.addListener(marker, "click", function () {
			marker = this;
			var coord = marker.getPosition();
			infoWindow.setContent('<div id="gMapWindowContent" class="googleMapBulle">Please wait...</div>');
			infoWindow.open(this.map, marker);
			google.maps.event.clearListeners(infoWindow, 'domready');
			google.maps.event.addListener(infoWindow, 'domready', function() {
				displayFileContent(url, 'gMapWindowContent', function() {
					self.setInfowindowSize(infoWindow);
				});
			});
		});
	}
	if (!this.latlngbounds.contains(marker.getPosition())) {
		this.latlngbounds.extend(marker.getPosition());
	}
	this.nbMarkers ++;
};

// layer pour afficher les coordonnées.
emajineMap.prototype.afficheCoord = function (marker){
	var coord = marker.getLatLng();
	var coord1 = coord.lat();
	var coord2 = coord.lng();
	var info = '<span style="font-size:small;"><strong>Coordonnées :</strong> <br />Latitude : '+coord1+'<br />Longitude : '+coord2+'</span>';
	infoWindow.setContent(info);
	infoWindow.open(this.map, marker);
	self.setInfowindowSize(infoWindow);
};

//Itineraire :
emajineMap.prototype.getDirection = function (divdirection)
{
	document.getElementById(divdirection).innerHTML = '';
	this.gdir = new google.maps.DirectionsService();
	this.directionsDisplay = new google.maps.DirectionsRenderer({
		'map': this.map,
		'preserveViewport': true,
		'draggable': true
    });
	this.directionsDisplay.setPanel(document.getElementById(divdirection));

	var directionsDisplay = this.directionsDisplay;
	google.maps.event.addListener(this.directionsDisplay, 'directions_changed',
		function() {
			currentDirections = directionsDisplay.getDirections();
	});

};

emajineMap.prototype.setDirections = function (fromAddress, toAddress, locale)
{
    var request = {
        origin: fromAddress,
        destination: toAddress,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    var direction = this.directionsDisplay;
    var map = this.map;
    this.gdir.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			direction.setDirections(response);
			map.fitBounds(response.routes[0].bounds);
		}
    });
};

emajineMap.prototype.loadJsonSpots = function(url)
{
	var latlngbounds = this.latlngbounds;
	var defaultZoomLevel = this.zoom ? this.zoom : 1;
	var emajineMap = this;
	var map = this.map;
	var centerPoint = this.point;
	var nbSpot = this.nbMarkers
	$.get(url, function(datas) {
		datas = eval(datas);
		var len = datas.length;
		if (len>0) {
			for (var i = 0; i < len;i++) {
				if (typeof datas[i] != 'undefined') {
					emajineMap.setIcon(datas[i].icon);
					var m = emajineMap.getMarker(datas[i].latitude, datas[i].longitude, datas[i].icon);
					emajineMap.setMarker(m, datas[i].uri);
					nbSpot ++;
				}
			}
		}
		emajineMap.setPointToSpot();
		return;
	});
};

var map, fieldId, mod, fieldHidden, fieldHtml, defCoord, _coord, _info, marker, mapOptions;
function loadFieldMap(fieldID, mode)
{
	fieldId = fieldID;
	mod = mode;
	fieldHidden = document.getElementById(fieldId + 'idhidden');
	fieldHtml = document.getElementById(fieldId+'span');
	defCoord = document.getElementById(fieldId+'idhidden').value;
	_coord='';// coordonnées sous la forme "latitude|longitude"
	_info='';//  coordonnées sous la forme "Latitude : latitude Longitude : longitude"
	mapOptions=new Array();

	if (mod=='address') {
		initGeocoder(fieldId);
	} else if(mod=='map') {
		initMap(defCoord);
	} else {
		initMap(defCoord);
		initGeocoder(fieldId, map);
	}
	mapOptions["map"]= map;
	return mapOptions;
}
function initGeocoder(fieldId, map)
{
	var geo = document.getElementById("search" + fieldId);
	geo.onclick = function()
	{
		var geocoder = new google.maps.Geocoder();
		var address = document.getElementById("adresse" + fieldId).value;
		if (address != '') {
			geocoder.geocode({'address': address}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					updateCoord(results[0].geometry.location);
					if (typeof map !== 'undefined') {
						initMarker(results[0].geometry.location);
					}
				} else {
					alert(address + " _not_found_");
				}
			});
		}else{
			alert("_vous_devez_renseigner_le_champ_adresse_");
			document.getElementById("adresse" + fieldId).focus();
		}
	}
}
function updateCoord(location)
{
	var lat = location.lat();
	var lng = location.lng();
	_coord = lat + '|' + lng;
	_info = "Latitude"+' : '+lat+" Longitude"+' : '+lng;
	updateFieldsMap(_coord, _info)
}

function displayFileContent(url, divID, onLoaded)
{
	$.get(url, function(data) {
		$('#' + divID).html(data);
		if (typeof onLoaded == 'function') {
			onLoaded();
		}
	});
}
function updateFieldsMap(coordhidden, coordhtml)
{
	if(fieldHidden) fieldHidden.value=coordhidden;
	if(fieldHtml) fieldHtml.innerHTML=coordhtml;
}

function initMap(defCoord)
{
	map = new google.maps.Map(document.getElementById("map" + fieldId));
	if(defCoord){
		defCoord = defCoord.split('|');
		var defPt = new google.maps.LatLng(defCoord[0], defCoord[1]);
		updateCoord(defPt);
		initMarker(defPt);
	}else{
		//fixe le centre de la carte sur Paris
		map.setCenter(new google.maps.LatLng(46.80851951372989, 2.180614471435547), 5);
	}

	map.setZoom(5);
	map.setMapTypeId(google.maps.MapTypeId.ROADMAP);

	//affiche la barre latérale de navigation et le button [plan|satellite|mixte]
	var options = {};
	options.zoomControl           = true;
	options.zoomControlOptions    = {style: google.maps.ZoomControlStyle.DEFAULT};
	options.mapTypeControl        = true;
	options.mapTypeControlOptions = {style: google.maps.MapTypeControlStyle.DEFAULT};
	options.keyboardShortcuts     = true;
	map.setOptions(options);

	google.maps.event.addListener(map, "click", function(point) {
		updateCoord(point.latLng);
		initMarker(point.latLng);
	});
}

function initMarker(location)
{
	map.setCenter(location);
	if (typeof marker !== 'undefined') {
		marker.setMap(null);
	}
	marker = new google.maps.Marker({
		map: map,
		draggable: true,
		position: location
	});
	google.maps.event.addListener(marker, 'dragend', function() {
		updateCoord(marker.getPosition());
		map.setCenter(marker.getPosition());
	});
}

function initGmapContentIziMedia()
{
	checkboxBeautiful();
}
