// On déclare la classe GoogleMapHelper
var GoogleMapHelper = Class.create();

// On définit les méthodes et propriétés de la classe (initialize joue le role de constructeur)
// C'est dans le constructeur qu'on déclare les propriétés de la classe.
GoogleMapHelper.prototype = {	
	
	   // constructeur
	   initialize: function(mapoption) {
		this.mapoption = mapoption;				// sauvegarde les options	
		this.icons=Array();					  			// pour la liste des icones		   					
		this.points=Array();								// pour la definition des points
		this.markers = Array();							// pour le stockage des points
		this.trajet = null;									// pour un module de calcul de trajet	  	  		   					
		this.resolv = null;								// pour un module de resolution d'adress	  
	   },
	   
	   // load intialisation
	   install: function() {
	
		// crée la map
	      if (GBrowserIsCompatible() &&$(this.mapoption.id)!=null ) 
	        this.createMap();
     		else return(false);
	      
	      // centre la map
	       	center=(this.mapoption.center!=null)?this.mapoption.center: [46.182058947,3.1587839126,16];	    
	       	if (this.mapoption.typemap!=null)   	
		 	 			this.map.setCenter(new GLatLng(center[0], center[1]), center[2],this.mapoption.typemap);	
		 	 else      this.map.setCenter(new GLatLng(center[0], center[1]), center[2]);	

		// zoom la map 
		if (this.mapoption.zoom!=null)   	
			  this.map.setZoom(this.mapoption.zoom);	
		 	        
        	if (this.mapoption.overview!=null && this.mapoption.overview==true)	// overview	
        		this.map.addControl(new GOverviewMapControl());
		 		
        	if (this.mapoption.scale!=null && this.mapoption.scale==true)  // scale  control
        		this.map.addControl(new GScaleControl());   
		
        	if (this.mapoption.maptypecontrol!=null && this.mapoption.maptypecontrol==true)  // map type  control
             	this.map.addControl(new GMapTypeControl());      
		
        	if (this.mapoption.smallmapcontrol!=null && this.mapoption.smallmapcontrol==true)  // small map   control
		  	this.map.addControl(new GSmallMapControl()); 

        	if (this.mapoption.largemapcontrol!=null && this.mapoption.largemapcontrol==true)  // small map   control
		  	this.map.addControl(new GLargeMapControl()); 	  	
		  	
		this.makePoint();	//maintenant que la carte est créée, on peut rajouter les points	  	
		
		if (this.trajet != null)	// prepare le formulaire et div affichant un trajet
			this.prepareTrajet();   

		if (this.resolv != null)	// prepare l'outil de resolution d'adresse
			this.prepareResolv();   					 			
	   },
	   
	   createMap : function(maptype)
	    {
     			this.map = new GMap2($(this.mapoption.id),maptype);
     			    
     			 // callback sur le changement de zoom pour mettre a jour un input
    	   		if (this.mapoption.inputCoordId!=null  && $(this.mapoption.inputCoordId)!=null && this.mapoption.inputCoordId[3]!=null)  
    	   		{ 
  	   			 var mapoption = this.mapoption;
 	    			GEvent.addListener(this.map , "zoomend", 	function(oldlevel,newlevel)	
 	    					{ 
 	    						 formname	= mapoption.inputCoordId[0];
							zoom	= mapoption.inputCoordId[3];    	   			 	    	   			 		    						
 	    						$(formname)[zoom].value = newlevel;		}	);        	   			 	
			}     		    	
	    },
	  
	  createIcon : function(iconoptions) {
			var icon = new GIcon();
			icon.image = iconoptions.link;
			icon.iconSize = new GSize(iconoptions.width, iconoptions.height);
			icon.iconAnchor = new GPoint(6, 20);
			icon.infoWindowAnchor = new GPoint(5, 1);
        return icon;
      },
      
	  addIcon :  function (iconoptions) {	  	
	  	if (iconoptions!=null && iconoptions.length>0)
	  	for (var i=0; i<iconoptions.length; i++)
	  	  {  			
			this.icons.push({ 'name' : iconoptions[i].name, 'icone' : this.createIcon(iconoptions[i]) } ); 
		 }
	},
		 
	addPoint : 		function (options) 	{		
		if (options!=null && options.length>0)
	  	for (var i=0; i<options.length; i++)		
			this.points.push(options[i]);	
		},
			
	addTrajet: 	function (options) 	{	this.trajet=options;				},
	addResolv:	function (options)	{	this.resolv=options;			},
	
	createMarker : function(point,options,bulle) {
        var marker = new GMarker(point,options);
        if (bulle!=null)
        	GEvent.addListener(marker, "click", function() {	marker.openInfoWindowHtml(bulle);});
        return marker;
      },
	
	iconeExist : function (name)
	  {
	  	var icone=null;
	  	
	  	for (var j=0; j<this.icons.length; j++)
	  		 if (this.icons[j].name==name)		   	
	  	  		icone=this.icons[j].icone;

		return(icone);
	  },
	  
	makePoint : function () {		

		this.bounds = new GLatLngBounds;  	// pour calculer un centrage automatique
		
	  	for (var i=0; i<this.points.length; i++)
	  	  {	  	  	
	  	  	icone = this.iconeExist(this.points[i].icone);

			//alert(this.points[i].draggable+' '+this.points[i].latitude+' '+this.points[i].longitude+'('+icone+')');

	  	  	if (icone!=null)
	  	  	  {	  	  	  	
				point = new GLatLng(this.points[i].latitude, this.points[i].longitude);
	   			marker =  this.createMarker(point,{'draggable': this.points[i].draggable, 'icon': icone, 'title': this.points[i].title },this.points[i].bulle ) ;

				// mise a jour d'input contenant les coordonnées d'un marker
    	   			if (i==0 && this.mapoption.inputCoordId!=null  && $(this.mapoption.inputCoordId)!=null)  
    	   			 { 
    	   			 	var mapoption = this.mapoption;
    	   			 	formname	= this.mapoption.inputCoordId[0];
    	   			 	latname 	= this.mapoption.inputCoordId[1];
    	   			 	lgtname	= this.mapoption.inputCoordId[2];
    	   			 	    	   			 	
 	    				GEvent.addListener(marker , "dragend", 	function()	{        
        			 							$(formname)[latname].value = this .getPoint().lat()  ;		
        			 							$(formname)[lgtname].value = this .getPoint().lng()  ;			}	);    
				}
         
    	      		this.map.addOverlay(marker);
	      		this.markers.push(marker);
	      		this.bounds.extend(point);
	   	 	 }	
	   	 }  
	   	 
        if (this.mapoption.autocenter!=null && this.mapoption.autocenter==true)  // autocenter
			this.autoCenter();             	   	 
	} ,
	
	autoCenter : function() {
		
		if (this.markers!=null && this.markers.length>1)
		  {
			this.map.setZoom(this.map.getBoundsZoomLevel(this.bounds));
			this.map.setCenter(this.bounds.getCenter());  
		  }    
	},
	
  	prepareTrajet : function() {
  	  				  				 	
  	  	var trajet = this.trajet;
  	  	var map = this.map;
  	  	
  		if (trajet.formId!=null && $(trajet.formId)!=null)
  		  {
				Event.observe($(trajet.formId), 'submit', function(event) { 			
			 					
				 from		=  $(trajet.formId)['from'];
				 to  		=  $(trajet.formId)['to'];
 				 locale	=  $(trajet.formId)['locale'];
			 								 		
  				if (trajet.divtrajetId!=null && $(trajet.divtrajetId)!=null && from!=null && to!=null && locale!=null)
  				  {
       				$(trajet.divtrajetId).style.position='relative';
					$(trajet.divtrajetId).style.visibility='visible';
 				 	var gdir = new GDirections(map, $(trajet.divtrajetId));
 				 	 GEvent.addListener(gdir, "error", function() { alert('Impossible de géolocaliser cette adresse'); });
      			 	gdir.load("from: " + $(from).getValue() + " to: " + $(to).getValue(),    { "locale": $(locale).getValue() });
      			}
      			else alert('La génération de trajet est impossible :  définition html manquante '); 
				Event.stop(event);	
			});	 
		} 	
    },
    	prepareResolv : function() {

  	var resolv		= this.resolv;   		
  	var map 		= this.map;               						
  	var markers 	= this.markers;
 			
	if (resolv.inputId!=null && $(resolv.inputId)!=null && resolv.actionId!=null && $(resolv.actionId)!=null )
	  {
		Event.observe($(resolv.actionId), 'click', function(event) { 	
	
   			var geocoder = new GClientGeocoder();
      		if (geocoder) 
      			{
    	     				geocoder.getLatLng($(resolv.inputId).getValue() ,
          				function(point) {
	            			if (!point) { alert($(resolv.inputId).getValue() + " not found");  } 
	            			else {
             							if (resolv.pointnum!=null && markers[resolv.pointnum]!=null ) 
             							   {
              							   	    markers[resolv.pointnum].setLatLng(new GLatLng(point.lat(), point.lng())) ;     
              							   	    GEvent.trigger(markers[resolv.pointnum], "dragend"); 
             							   }		
             							map.setCenter(point);             							   				
            						}
          					});
      			}
      			
      			Event.stop(event);	
             });
       }
    },
    
 ajaxLoadCvsPoints : function (fileUrl,opt_options){
 
  	var opts = opt_options||{};
  	var color = opts.color||'#ff0000';
  	var weight = (opts.weight!=null)?opts.weight:2;
  	var opa = opts.liOpa||0.8;
	var fillColor = opts.fillColor||color;
	var t = this;
	var map = this.map;
 	var points= t.points =  Array();
     
 	 var process = function(datas){
 	 	  
   		lines  = datas.split('\n');   		
   		for (i=0; i<lines.length; i++)
   		   {
   		   	 cells = lines[i].split(';');
   		   	  if (parseFloat(cells[0]) && parseFloat(cells[1]))
				{
    					if (weight!=0)	   points.push(  new GLatLng(parseFloat(cells[0]),parseFloat(cells[1])) ); 
    					else	
    						{
    							moption = {'draggable':false,  'latitude':parseFloat(cells[0]),'longitude':parseFloat(cells[1])};
    							if (cells[2]!=null && cells[2]!='')  moption['bulle']=cells[2];    							  
    							if (cells[3]!=null && cells[3].length>1)  
    							  {
    							  	if (t.iconeExist(cells[3])==null)
    							  	  {   
    							  	  	t.addIcon([{ 'link' : cells[3], 'name': 'auto'+i }]);
    							  	  	moption['icone']='auto'+i;   
    							  	  }
    							  	else moption['icone']=cells[3];   							  	
    							  }   							  
    							t .points.push(moption);
    						}
    				}
   		   }
 		
 		if (weight==0)
 		  {
  			map.clearOverlays();
 		  	t .makePoint();	//maintenant que la carte est créée, on peut rajouter les points	  	
 		  }
 		else
 		  {
 		 	if(opts.fillOpa)  	var poly = new GPolygon(points,color,weight,opa,fillColor,opts.fillOpa);
           	else 					var poly = new GPolyline(points,color,weight,opa);
  		
  			map.clearOverlays();
			map.addOverlay(poly);
			bounds = poly.getBounds()
			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
            }    	
	}
  	
   GDownloadUrl(fileUrl, process);
},

GoGMap : function  (lng,lat, zoom, id, content)
  {
  	if (lng!=undefined && lat!=undefined && this.map!=undefined)
  	 {
  	 	 this.map.setCenter(new GLatLng(lat, lng), zoom);
  	 
  	 	 if (content!='')
  	   		this.markers[id].openInfoWindowHtml(content);
  	 }
  }
	
}	

 