//
// Store Locator:
//

var map;
var markers = [];
var markers_index = 0;
var reenable_updates = false;
var slmapmarkers_req_id = 0;

function enable_updates() {

	ome.log('re-enable updates');
	// signal to moveend method that it can re-enable markers update:
	reenable_updates = true; // because moveend is called after this function
}

var slUpdateMarkers = function(with_autozoom) {

	if (!map) return;

	var current_zoom_level = map.getZoom();
	//ome.log('map zoom level: '+current_zoom_level);

	var b = map.getBounds();
	//ome.log('map bounds: '+b);

	if (current_zoom_level > 1) {
		$('#map_sw').val(b.getSouthWest().toUrlValue());
		$('#map_ne').val(b.getNorthEast().toUrlValue());
	} else {
		$('#map_sw').val('-90.0,-180.0');
		$('#map_ne').val('90.0,180.0');
	}

	jQuery.post(
		'index.php?eID=slmapmarkers&reqid=' + ++slmapmarkers_req_id,
		$('#mapfsl').serialize(),
		function(data) {

			if (data.reqid != slmapmarkers_req_id) {
				ome.log('ignore late ajax response reqid='+data.reqid);
				return;
			}
			
			var box = null;

			var d = data.total;

			$('#t3_count_stores').html(d+' ');

			map.clearOverlays();

			jQuery.each(
				data.stores,
				function(indexInArray, obj) {

					//ome.log('store lat,lng: '+obj.lat+', '+obj.lng);
					var ll = new GLatLng(obj.lat, obj.lng);

					if (box == null) {
						box = new GLatLngBounds(ll, ll);
					} else {
						box.extend(ll);
					}

					var ico = new GIcon();

					ico.image = obj.st>0 ?
									'/fileadmin/templates/theme/images/pin-boutique.png' :
									'/fileadmin/templates/theme/images/pin-store.png';

					ico.iconSize = new GSize(26, 28);
					ico.iconAnchor = new GPoint(13, 28);
					ico.infoWindowAnchor = new GPoint(13, 28);

					markers[markers_index] = new GMarker(ll, { icon: ico });
					markers[markers_index].html_info = obj.info;
					markers[markers_index].zoom_in = obj.info instanceof Array;

					map.addOverlay(markers[markers_index]);

					GEvent.addListener(markers[markers_index], 'click',
						function() {
							//ome.log('marker click');
							if (this.zoom_in) {
								if (map.getZoom() < 19) {
									var ll = this.html_info;
									slZoomIn(ll[0],ll[1],ll[2],ll[3]);
								}
							} else {
								//ome.log('open info window');
								reenable_updates = false;
								map.enable_markers_update = false;
								this.openInfoWindowHtml(
									this.html_info, {
										onOpenFn:enable_updates()
									}
								);
							}
						}
					);

					markers_index++;
				}
			); // each

			if (with_autozoom && (box != null)) {

				if (map.getZoom() >= 2) {

					map.enable_markers_update = false;

					map.setCenter(box.getCenter());

					var zoom_level = map.getBoundsZoomLevel(box);
					ome.log('autozoom to level '+zoom_level+' for box '+box);
					map.setZoom(zoom_level);
				}
			}

			map.enable_markers_update = true;

		},
		'json'
	);
} // slUpdateMarkers()


slZoomIn = function(sw_lat, sw_lng, ne_lat, ne_lng) {

	map.closeInfoWindow();

	map.enable_markers_update = false;

	var box = new GLatLngBounds(new GLatLng(sw_lat, sw_lng), new GLatLng(ne_lat, ne_lng));
	map.setCenter(box.getCenter());

	var zoom_level = map.getBoundsZoomLevel(box);
	//ome.log('zoom in to level '+zoom_level+' for box '+box);
	map.setZoom(zoom_level);

	slUpdateMarkers(false);
}


$(document).ready(function() {

	// Note: We can not use the "changeE event in IE because this event does not bubble up.
	//       Therefore, we need to use the "click" event.

	var store_locator = $('#mapfsl');
	if (store_locator.length) {		//TODO: test encore utile?
		if (document.getElementById('storelocator')) {
			$('#maprb01').click(function(){
				$('#slst').val('c');	// search type is CRITERIA
				slUpdateMarkers(false);
			});
			$('#maprb02').click(function(){
				$('#slst').val('c');	// search type is CRITERIA
				slUpdateMarkers(false);
			});

			$('#mapsellwatches').click(function(){
				$('#slst').val('c');	// search type is CRITERIA
				slUpdateMarkers(false);
			});
			$('#mapsellleather').click(function(){
				$('#slst').val('c');	// search type is CRITERIA
				slUpdateMarkers(false);
			});
			$('#mapselljewellery').click(function(){
				$('#slst').val('c');	// search type is CRITERIA
				slUpdateMarkers(false);
			});
		}
		if (document.getElementById('servicelocator')) {
			$('#maprb03').click(function(){
				$('#slscoucout').val('c');	// search type is CRITERIA
				slUpdateMarkers(false);
			});
			$('#maprb04').click(function(){
				$('#slst').val('c');	// search type is CRITERIA
				slUpdateMarkers(false);
			});
		}
	} // if

	$('#t3_btshow').click(function(){

		jQuery.post(
			'index.php?eID=slmapstores',
			$('#mapfsl').serialize(),
			function(data) {
				$('#t3_stores').html(data);
			},
			'html'
		);

		return false;
	});

	if (GBrowserIsCompatible()) {

		map = new GMap2(document.getElementById("google-map-container"));

		// custom properties:
		map.enable_markers_update = true;

		GEvent.addListener(map, 'load', function() {
			slUpdateMarkers(true);
		});
		map.setMapType(G_NORMAL_MAP);
		map.setCenter(new GLatLng(31, 25), 1);
		map.setUIToDefault();

		// moveend is called when zooming too
		GEvent.addListener(map, 'moveend', function() {
			//ome.log('map moveend; map center='+map.getCenter());
			if (this.enable_markers_update) {
				slUpdateMarkers(false);
			}
			if (reenable_updates) {
				this.enable_markers_update = true;
			}
			reenable_updates = false;
		});

		//Note: it is not necessary to trigger this event on
		//zoomend as moveend is automatically triggerd by zoomend.
		// moveend is called when zooming too
		GEvent.addListener(map, 'zoomend', function(oldLevel, newLevel) {
			if (oldLevel != newLevel) reenable_updates = true;
		});

		GEvent.addListener(map, 'infowindowopen', function() {
			map.enable_markers_update = false;
		});

		GEvent.addListener(map, 'infowindowclose', function() {
			map.enable_markers_update = true;
		});

	}

});

$(document).unload(function() {
	GUnload()
});

