$(function()
{
	$(document).data('clouds',$('body').data('clouds')+1);


	// trouver la carte
	var gmap = $("#gmap"); if ( !gmap.length ) return;
	var list = $("#list");
	var form = $('form.search:eq(0)'); // le formulaire utilisé pour le rechargement !


	try
	{
		// La carte google
		var map = new google.maps.Map( gmap.get(0), {
			zoom: 5
			,center: new google.maps.LatLng( 46.7, 2.5 )
			,scrollwheel: false
			,draggable: true
			,mapTypeId: google.maps.MapTypeId.ROADMAP
			,mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }
			,disableDoubleClickZoom: !list.length
		});

		google.maps.event.addListenerOnce( map, 'idle', function()
		{
			$(document).data('clouds',$(document).data('clouds')-1).trigger('clouds');
		});

		var geocoder = new google.maps.Geocoder;

		// autocomplete pour les coordonnées
		var geoTimer;
		$("#g").keyup(function()
		{
			var input = $(this);
			clearTimeout( geoTimer );
			if ( input.val().length > 2 )
			{
				input.css({background:'url("/images/ajax-loader.gif") no-repeat right center'});
				geoTimer = setTimeout(function()
				{
					geocoder.geocode({ address: input.val(), region: 'FR', language:'fr' }, function( result, status )
					{
						if ( status == 'OK' )
						{
							$("#c").val( result[0].geometry.location.lat()+','+result[0].geometry.location.lng() );
						}
						input.css({background: 'white'});
					})
				},500);
			}
		});



		if ( !list.length )
		{
			gmap.attr('title','Double-cliquez sur la carte pour lancer la recherche autour de ce point');
			google.maps.event.addListener( map, 'click', function( evt )
			{
				$('#c').val( evt.latLng.lat()+','+evt.latLng.lng() );
				form.submit();
			});

			return;
		}


		var fitBounds = true;    // recentrage de la carte automatique ?
		var enableAjax = false;  // ajax est autorisé ?
		var markers = [];        // marqueurs présents sur la carte (pour suppression)
		var winTimer;            // timer de fermeture de infoWindow
		var infoWindow = $("<div></div>").attr('id','infoWindow').appendTo('body')
			.bind('mouseout', function() { winTimer = setTimeout( function() { infoWindow.fadeOut(); }, 1000 ) } )
			.bind('mouseover', function() { clearTimeout( winTimer ) } );


		var me = false; // le marqueur de ma position
		var c = $("#c").val()
		if ( c.length && c.indexOf(',')>0 )
		{
			var l = c.split(',');
			me = new google.maps.Marker({
				map: map
				,position: new google.maps.LatLng( parseFloat(l[0]), parseFloat(l[1]) )
				,icon: new google.maps.MarkerImage("/images/theme-spring/gmapmarker_me.png", new google.maps.Size(10,10), new google.maps.Point(3,3) )
				,title: 'Centre géographique de votre recherche'
				,cursor: 'help'
			});

			delete l;
		}
		delete c;


		// Ajout des marqueurs reçu via JSON
		var addItems = function( items )
		{
			// nettoyage des marqueurs actuels
			while ( marker = markers.pop() )
			{
				google.maps.event.clearInstanceListeners( marker );
				marker.setMap( null );
				delete marker;
			}

			// Recentrage de la carte (une fois seulement, et uniquement sur les marqueurs visibles)
			if ( fitBounds )
			{
				var bounds = new google.maps.LatLngBounds();
				if ( me ) bounds.extend( me.getPosition() );
				$.each( items, function( i, item )
				{
					if ( item.visible )
					{
						bounds.extend( new google.maps.LatLng( item.latitude, item.longitude ) );
					}
				});
				var n = bounds.getNorthEast().lat();
				var e = bounds.getNorthEast().lng();
				var s = bounds.getSouthWest().lat();
				var w = bounds.getSouthWest().lng();
				if ( Math.abs( n - s ) + Math.abs( e - w ) < 0.025 )
				{
					map.setCenter( bounds.getCenter() );
					map.setZoom( 15 );
				}
				else
				{
					map.fitBounds( bounds );
				}
				fitBounds = false; // plus de recentrage
				google.maps.event.addListenerOnce( map, 'idle', function() { enableAjax = true; } ); // ok pour ajaxReload après le recentrage...
			}

			// les deux types de marqueurs
			var iconHidden = new google.maps.MarkerImage("/images/theme-spring/gmapmarker_small.png", new google.maps.Size(10,10), new google.maps.Point(3,3) );
			var iconVisible = new google.maps.MarkerImage("/images/theme-spring/gmapmarker.png", new google.maps.Size(32,32), new google.maps.Point(0,0) );

			$.each( items, function( i, item )
			{
				// création du marqueur
				var marker = new google.maps.Marker({
					map: map
					,position: new google.maps.LatLng( item.latitude, item.longitude )
					,clickable: true
					,icon: item.visible ? iconVisible : iconHidden
					,title: item.name
					,zIndex: i+1
				});

				// au click, chargement de l'info
				google.maps.event.addListener(marker, 'click', function( evt )
				{
					// positionnement de l'infoWindow
					var t = $(evt.target);
					var o = t.offset();
					var position = { top: o.top + t.height() ,left: o.left + t.width() }
					// ne pas toucher les bords !
					if ( position.left + infoWindow.outerWidth() > document.width ) position.left = o.left - infoWindow.outerWidth();

					infoWindow.hide().css(position).load( item.url, function() { infoWindow.show(); } );
				});

				// ajout du marqueur à la liste
				markers.push( marker );
			});
		}


		// rechargement  de la liste des marqueurs via JSON
		var ajaxReload = function()
		{
			if (!enableAjax) return false; // pas autorisé ? ciao

			// construire la requête à partir du formulaire en ajoutant les nouvelles coordonnées
			var request = form.serialize()+'&c='+map.getCenter().lat()+','+map.getCenter().lng();

			// chargement !
			list.css({backgroundColor:'#eee'},'slow').load( form.attr('action'), request, function()
			{
				$(this).stop().css({backgroundColor:'#fff'});

				$.get( form.attr('data-json'), request, function( results )
				{
					if ( results.length ) addItems( results );
				}, 'json' );

			});
		}


		// init de la carte
		$.get( form.attr('data-json'), form.serialize(), function( results )
		{
			if ( !results.length ) return;

			addItems( results );

			// dragging => ajaxReload
			google.maps.event.addListener( map, 'center_changed', ajaxReload );
			google.maps.event.addListener( map, 'dragstart', function(){ enableAjax = false; } );
			google.maps.event.addListener( map, 'dragend', function(){ enableAjax = true; ajaxReload(); } );
		}, 'json' );
	}
	catch(e)
	{
		// échec, on cache la carte (firefox 2)
		gmap.hide();
	}

});

/*
 * Encode une coordonnée en base 62 avec une précision au 10000000ème !
 *
function( n )
{
	var a=n<0?'-':'',
	A='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
	l=A.length,d;
	n=Math.abs(Math.round(n*10000000));
	while(n){a+=A.charAt(d=n%l);n-=d;n/=l;}
	return a;
}
*/