
/**
 * Outil Xml
 *
 */
Xml = function() { };

Object.extend(Xml, {
  Parser: function(text) {
  	var parser;
    return Try.these(
      function() {
      	parser = new DOMParser();
				var doc = parser.parseFromString(text,'text/xml');
				return doc;
      },
			function() {
				parser = new ActiveXObject('Microsoft.XMLDOM');
				parser.async = 'false';
				parser.loadXML(text);
				return parser;
			}
    ) || false;
  }
});


/**
 * Conteneur
 *
 */
Ruche = { };

/**
 * Manipulation de la carte
 *
 */
RucheDevel = Class.create();


Object.extend(RucheDevel.prototype, {
	gmap: { },
	status: { },
	info: { },
	infospot: { },
	icons: { },

	bounds: { },
	layers: [ ],

	//mymarkers: { },

	


	loadGMap: function(container) {
		if (GBrowserIsCompatible()) {
			var map = new GMap2( container );
			Event.observe(window, 'unload', function() { GUnload(); }, false);
			return map;
		}
	},

	initGMap: function(params) {
		var mt = this.gmap.getMapTypes();
		for (var i=0; i<mt.length; i++) {
			mt[i].getMinimumResolution = function() { return 11; }
			mt[i].getMaximumResolution = function() { return 17; }
		}
		this.gmap.addControl(new GLargeMapControl());
		this.gmap.addControl(new GMapTypeControl());
		this.gmap.setCenter(new GLatLng(params.mapCenter.lat,params.mapCenter.lng), params.mapZoom );
		this.gmap.enableScrollWheelZoom();
	},

	initIcons: function(prefix) {
		var tpl = new GIcon();
		tpl.iconSize = new GSize(19, 19);
		tpl.iconAnchor = new GPoint(0, 0);
		tpl.image = prefix + 'trans.png';
		tpl.dragCrossImage = prefix + 'cross.png';
		tpl.dragCrossSize = new GSize(19,19);
		tpl.dragCrossAnchor = new GPoint(9,9);
		tpl.maxHeight = 19;
		tpl.infoWindowAnchor= new GPoint(0,0);

		Object.extend(this.icons, {
			C : new GIcon( tpl, prefix + 'C.png'),
			N : new GIcon( tpl, prefix + 'N.png'),
			P : new GIcon( tpl, prefix + 'P.png'),
			S : new GIcon( tpl, prefix + 'S.png')
		});
	},

	
	loadMarkers: function (map) {
		//Element.update(this.info,"");
		this.gmap.clearOverlays();
		var strLayers = this.layers.compact().flatten();
		var url = this.markersUrl + '?' + "layers="+ strLayers;
		//Element.update(this.status, 'Chargement des marqueurs:<br /><a href="'+ url+'">' + url + '</a>');
		var target = this;
		new Ajax.Request(url,
			{ method: 'get',
				onSuccess: function (transport,json) {
					var markersArray = [ ];
					var doc = new Xml.Parser(transport.responseText).documentElement;
					var mymarkers = doc.getElementsByTagName('marker');
										for (var i = 0; i < mymarkers.length; i++) {
						xml = mymarkers[i];
						marker = target.makeMarker( {
							id: xml.getAttribute('id'),
							stype: xml.getAttribute('stype'),
							label: xml.getAttribute('label'),
							lat: parseFloat(xml.getAttribute('lat')),
							lng: parseFloat(xml.getAttribute('lng')),
							draggable: parseInt(xml.getAttribute('draggable'))
						});
						
						markersArray.push(marker);
						
					}
					
					if(typeof(cluster)==='undefined'){
						cluster=new ClusterMarker(map, { markers:markersArray } );
						cluster.clusterMarkerTitle='Cliquez pour voir les %count membres';
						cluster.intersectPadding=5;
					}else{
						
						cluster.addMarkers(markersArray);
					}
					
					cluster.refresh(true);
					
					//	enables the large map control centre button to return the map to initial view
					map.savePosition();	
				
					//	add an HtmlControl to enable toggling of the ClusterMarker cluster function
					var html='<div class="menu_map" style="position: absolute; top: 20px; left: 211px;"><img src="/media/puce_cluster.jpg" width="20" height="20" align="absmiddle"> Regroupement des points : <input type="checkbox" checked="checked" onclick="target.toggleClustering()" /></div>';
					var control=new HtmlControl(html);
					map.addControl(control, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7)));
					
				}
		
		});


	},

	loadLayers: function(layers) {
		this.layers = layers;
		this.loadMarkers(this.gmap, this.markersUrl);
	},
	
	markerXmlKeys: ['id','stype','label','lat','lng'],
	markerFromXml: function(xml) {
		var res = { };
		this.markerXmlKeys.each( function(k) { res.k = xml.getAttribute(k); } );
		res.lat = parseFloat(res.lat);
		res.lng = parseFloat(res.lng);
		return res;
	},

	makeMarker: function(spot) {
		spot.title = spot.label;
		var marker = new GMarker(new GLatLng(spot.lat, spot.lng), {
			icon: this.icons[spot.stype], draggable: spot.draggable, title: spot.title
		});
		marker.spot_id = spot.id;
		marker.stype = spot.stype;

		/*var target = this;
		GEvent.addListener(marker, 'dragend', function() {
			var point = marker.getPoint();
			new Ajax.Updater($('Inscript') , target.updateUrl ,{
					method: 'get', parameters: { id: marker.spot_id, lat: point.lat(), lng: point.lng() }
				});
			}
		);*/

		// this.gmap.addOverlay(marker);
		return marker;
	},
	
	
	clearMap: function() {
		this.gmap.clearOverlays();
		cluster.refresh(true);
	},
	
	updateInfo: function(marker) {
		new Ajax.Updater(this.info, this.detailsUrl, {
			method: 'get', parameters: { id: marker.spot_id }
		});
	},
	
	detailspot: function(marker) {
		etatZoom = TestZoom();
		new Ajax.Updater(this.info, this.detailspotUrl, {
			parameters: { id: marker.spot_id },
			onCreate: function(transport){
				if(etatZoom === false){
					toggleMenu();
				}else{
					openLoadZ();
				}
			},
			onComplete: function(transport){ 
				if(etatZoom === false){
					toggleMenu();
					OpenZoom();
				}else{
					closeLoadZ();
				}
			},
			evalScripts: true
		});
	},
	
	/*detailspotext: function(marker,lati,longi) {
		
		var point = new GLatLng(lati,longi);
		this.gmap.panTo(point);
		this.gmap.setZoom(15);
		
		new Ajax.Updater(this.info, this.detailspotUrl, {
			method: 'get', parameters: { id: marker },
			onComplete: function(transport){ 
				new Effect.BlindDown($('info'), {duration:.3})
			},
			evalScripts: true
		});
	},*/
	
	recupLatLng: function(marker) {
			var point = marker.getPoint();
			this.gmap.panTo(new GLatLng(point.lat(),point.lng()));
	},
	
	panOver: function(lati,longi) {
			this.gmap.panTo(new GLatLng(lati,longi));
			parent.$('cible').show();
	},
	
	
	LogZoom: function(marker,lati,longi) {
		var nivZoom = this.gmap.getZoom();
		if (nivZoom < 17){
			this.gmap.zoomIn();
		} else {
			this.gmap.setZoom(17);
		}
		this.gmap.panTo(new GLatLng(lati,longi));
		
	},
	
	zoomIn: function(){
		this.gmap.zoomIn();
	},
	
	toggleClustering: function() {
		cluster.clusteringEnabled=!cluster.clusteringEnabled;
		cluster.refresh(true);	//	true required to force a full update of the markers - otherwise the update would occur next time that the map is zoomed or the active markers change
	},
	
	
	
	initialize: function(params) {
		this.pointeuse = 0;
		
		this.status = params.statusElement;
		this.info = params.infoElement;
		//Element.update(this.status, "Initialisation");
		this.gmap = this.loadGMap(params.mapElement);
		this.initGMap(params);
		this.initIcons(params.markersPrefix);
		this.prefixe = params.markerPrefix;
		this.markersUrl = params.markersUrl;
		///this.loadMarkers(this.gmap, this.markersUrl);
		//new Insertion.Bottom(this.status, "<br />Prêt");

		this.detailsUrl = params.detailsUrl;
		this.updateUrl = params.updateUrl;
		
		this.detailspotUrl = params.detailspotUrl;
		
		this.markersArray = [ ];
		
		target = this;

		
		GEvent.addListener(this.gmap, "click", function(marker) {
			if (marker) {
				target.recupLatLng(marker);

				target.detailspot(marker);
				
			} else {
				this.closeInfoWindow();
				
			}
		});
		
		
		
		GEvent.addListener( this.gmap, 'dragstart', function() { 
				this.closeInfoWindow();
				new Effect.BlindUp($('info'), {duration:.3});
			}
		);
		
		

		GEvent.addListener(this.gmap, "dragend", function() {
			//bounds = this.getBounds();
			cluster.refresh(true);
		});
		
		
		
		///////////////////// Ecouteurs DOM

	}


});



