$(document).ready(function() {
	if($('#googlemap').exist()) {
		$('#main div.results').hide();
		initMapSearch();
		$('#main div.results').show();
	} else if($('#mini_googlemap').exist()) {
		initMapShow();
	}
});

function initMapSearch() {
	if(!window.GBrowserIsCompatible || !GBrowserIsCompatible()) {
	   return this;
	}
	var googlemap = new GMap2(document.getElementById('googlemap'));
	googlemap.addControl(new GLargeMapControl3D);
	googlemap.addControl(new GHierarchicalMapTypeControl);
	
	var geocoder = new GClientGeocoder();
	geocoder.setBaseCountryCode('fr');
	geocoder.getLatLng('77400 Lagny-Sur-Marne', function(coord) {
		googlemap.setCenter(coord, 14);
	});

	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);

	$.getJSON('/search/markers?' + remove_accent($('#ajax_query_string').text()), null,
		function(json) {
			$.each(json, function(i, item) {
				geocoder.getLatLng(item.address, function (coord) {
					var letter = String.fromCharCode("A".charCodeAt(0) + i);
					var letteredIcon = new GIcon(baseIcon);
					letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
					var marker = new GMarker(coord, { title: item.title, icon: letteredIcon });
					var window = function () {
						marker.openInfoWindowHtml(item.tab);
					};
					GEvent.addListener(marker, "click", window);
					googlemap.addOverlay(marker);
					$('#' + item.slug).click(function () {
						$('.result_selected').removeClass('result_selected');
						$('#' + item.slug).addClass('result_selected');
						marker.openInfoWindowHtml(item.tab);
					});
				});
			});
	});
}

function initMapShow() {
	if(!window.GBrowserIsCompatible || !GBrowserIsCompatible()) {
	   return this;
	}
	var googlemap = new GMap2(document.getElementById('mini_googlemap'));
	var geocoder = new GClientGeocoder();
	geocoder.setBaseCountryCode('fr');
	address_to_mark = $.trim($('#main div.content div.patch span.address').text());
	var reg = new RegExp('\n', 'g');
	address_to_mark = address_to_mark.replace(reg, ' ');
	geocoder.getLatLng(remove_accent(address_to_mark), function (coord){
		googlemap.setCenter(coord, 15);
		var title = $('#main div.content div.patch h1').text();
		var marker = new GMarker(coord, { title: title });
		googlemap.addOverlay(marker);
	});
}
