/**
 * create marker for google map 
 *
 * @author ngrandgirard@agenceinteractive.com
 *
 * @version 1.0 - 2009-08-25
 *
 * Use mootools 1.2
 */

var GMarkers = new Class({
	
	Implements: [Events, Options],
	
	/**
	 * Options
	 *
	 */
	options : {
		oIcon: {
			sIconPath	: '',
			sIconSize	: new Array(),
			sIconAnchor	: new Array()
		}
	},
	
	
	/**
	 * Constructor
	 *
	 */
	initialize: function( options ) {
		
		// set option
		this.setOptions(options);
		
		// set Geocoder
		this.GClientGeocoder = new GClientGeocoder();
		
		// set icon object
		this.oIcon = this.options.oIcon;
		
		this.aData = new Array();
	},
	
	// traduit un item en marquer google map
	createMarker: function ( aData, oMap, sTplTip )
	{
		var customIcon = this.initCustomTip();
		
		this.aData = aData;
		
		if( aData.latitude == '' && aData.longitude == '' ) {
			this.initMarkerByAddress( customIcon, oMap, sTplTip );
		} else {
			this.initMarkerByGPS( customIcon, oMap, sTplTip );			
		}
	},
	
	initCustomTip: function ()
	{
		//type du marqueur
		var customIcon = new GIcon();
		
		customIcon.image = this.oIcon.sIconPath;
		customIcon.iconSize = new GSize(
			this.oIcon.sIconSize[0], 
			this.oIcon.sIconSize[1]
		);
		customIcon.iconAnchor = new GPoint(
			this.oIcon.sIconAnchor[0], 
			this.oIcon.sIconAnchor[1]
		);
		
		return customIcon;
	},
	
	initMarkerByGPS: function ( customIcon, oMap, sTplTip )
	{
		this.marker = new GMarker(new GLatLng(this.aData.latitude, this.aData.longitude), { 
			icon: customIcon
		});
		
		//info window
		var aData = this.aData;
		var oPoint = this.marker.getPoint();
		
		GEvent.addListener(this.marker, "click", function(coordinates) {
			
			oMap.panTo(
				new GLatLng( aData.latitude, aData.longitude )
			);
			
			var hash = new Hash( aData.htmlInfos );
						
			var oHTMLRequest = new Request({
				url:sTplTip,
				method:'post',
				onComplete: function(response){
					
					var div = new Element('div');
					div.set('id', 'tipGMap');
					div.set('style', 'position:absolute');					
					div.set('html', response);
					
					div.style.top = (oMap.fromLatLngToDivPixel(oPoint).y) + 'px';
					div.style.left = (oMap.fromLatLngToDivPixel(oPoint).x) + 'px';
					
					if( $('tipGMap') != null )
						$('tipGMap').parentNode.removeChild($('tipGMap'));
					
					oMap.getPane(G_MAP_FLOAT_PANE).appendChild(div);
										
				}
			});
			
			oHTMLRequest.send(hash.toQueryString());
					
		});
		
		this.fireEvent('OnCompleteCreated', [this.marker]);
	},
	
	initMarkerByAddress: function ( customIcon, oMap, sTplTip )
	{
		this.GClientGeocoder.getLatLng( this.aData.commune, function(point){
			if( point != null )
			{
				this.aData.longitude = point.x;
				this.aData.latitude = point.y;	
				
				this.initMarkerByGPS( customIcon, oMap, sTplTip );
			}
		}.bind(this));
	}
		
});
