
var CGMap = function(params){ this.initialize(params); }

CGMap.prototype = {
	//////////////////////////////////////////////////////////////
	initialize: function(params){
		
		var settings = {
			mapId: "",
			directionsId: "",
			formId: "",
			fromId: "",
			toId: "",
			localeId: "",
			address:"",
			text: "",
			type: "address",
			lat: 0,
			lng: 0,
			showMapControl: true,
			showTypeControl: true,
			showDirections: false,
			showCoords:false,
			zoom:14
		};
		
		if(params) {
			jQuery.extend(settings, params);
		}
		
		this.settings = settings;
		
		this.isLoaded = false;
		this.isUnLoaded = false;
		
		var Scope = this;
		window.onload = function(){ Scope.setup() };
		window.onunload = function(){ GUnload(); };
	},
	
	setup: function(){		
		
		if( this.settings.mapId != "" )
		this.jMap = jQuery("#"+this.settings.mapId);
		
		if( this.settings.directionsId != "" )
		this.jDirections = jQuery("#"+this.settings.directionsId);
		
		if( this.settings.formId != "" )
		this.jForm = jQuery("#"+this.settings.formId);
		
		if( this.settings.fromId != "" )
		this.jFrom = jQuery("#"+this.settings.fromId);
		
		if( this.settings.toId != "" )
		this.jTo = jQuery("#"+this.settings.toId);
		
		if( this.settings.localeId != "" )
		this.jLocale = jQuery("#"+this.settings.localeId); 
		
		this.loadMap();
		
	} ,
	
	//////////////////////////////////////////////////////////////
	loadMap: function(){
		this.setMap();
	} ,
	
	// MAP ///////////////////////////////////////////////////
	setMap: function(){
		
        this.map = new GMap2( this.jMap[0] );
		
		if( ! this.map ){
			alert('CGMap.setMap(): Elemento per la mappa inesistente');
			return false;
		} 
		
		this.setPoint();
	} ,
	
	// POINT ///////////////////////////////////////////////////
	setPoint: function(){
		var success = false;
		switch(this.settings.type){
			case "address":
			this.setPointByAddress();
			break;
			case "coords":
			case "coordinates":
			this.setPointByCoords();
			break;
		}
	} ,
	setPointByAddress: function(){
		var Scope = this;
		
		if( this.settings.address == "" ){
			alert('CGMap.getPointByAddress(): Indirizzo non impostato');
			return false;
		} 
		
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng( Scope.settings.address, function(point){
			if( ! point ){
				alert('CGMap.getPointByAddress(): Indirizzo non trovato');
				return false;
		  	} else {
				Scope.display(point);
			}
		});
		
		if( this.point ) return true;
		
		return false;
	} ,
	setPointByCoords: function(){
		
		if( this.settings.lat == 0 ){
			alert('CGMap.getPointByCoords(): Latitudine non impostata');
				return false;
		} 
		if( this.settings.lng == 0 ){
			alert('CGMap.getPointByCoords(): Longitudine non impostata');
				return false;
		} 
		this.display( new GLatLng(this.settings.lat, this.settings.lng) );
	},
	
	// MARKER ///////////////////////////////////////////////////
	display: function(point){	  
		var Scope = this;
		
		this.point = point;
		this.map.setCenter(this.point, this.settings.zoom);
		
		if( this.settings.showCoords ){
			GEvent.addListener(this.map, "click", function(overlay, point) {
				var str = "Lat = " + point.y + ", Long = " + point.x;
				Scope.map.openInfoWindow(point, str );
			});
		}
		
		this.addControls();
		this.addDirections();
		
		this.marker = new GMarker(this.point);
		this.map.addOverlay(this.marker);
		if( this.settings.text != "" )
		this.marker.openInfoWindowHtml( this.settings.text );
	},
	
	// CONTROLS ///////////////////////////////////////////////////
	addControls: function(){
		if( this.settings.showMapControl ){
			this.map.addControl(new GSmallMapControl());
		}
		if( this.settings.showTypeControl ){
        	this.map.addControl(new GMapTypeControl());
		}
	},
	
	// DIRECTIONS ///////////////////////////////////////////////////
	addDirections: function(){
		if( this.settings.showDirections ){
			
			var Scope = this;
			this.directions = new GDirections(this.map,this.jDirections[0]);
				
			GEvent.addListener(this.directions, "addoverlay", function(){ Scope.directionsLoad()} );
			GEvent.addListener(this.directions, "error", function(){ Scope.directionsError()} );

			this.jTo.val(this.settings.address);
			this.jForm.bind("submit",function(e){
				var from = Scope.jFrom.val();
				var to = Scope.jTo.val();
				var locale = Scope.jLocale.val();
				if( Scope.settings.type == "address" || (Scope.settings.type == "coords" && to != Scope.settings.address) ){
					Scope.directions.load( "from: " + from + " to: " + to , { "locale": locale } );
					Scope.marker.hide();
				} else if( Scope.settings.type == "coords" ){
					Scope.directions.load( "from: " + from + " to: " + Scope.point.y + "," + Scope.point.x , { "locale": locale } );
					Scope.marker.hide();
				}
				e.preventDefault();
			});
		
		}
	},
	
	directionsError: function (){
	   if (this.directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		 alert("La posizione geografica potrebbe non essere trovata per uno degli indirizzi specificati. Ciò può essere dovuto al fatto che l'indirizzo è relativamente nuovo, o può non essere corretto. Errore n* " + this.directions.getStatus().code);
	   else if (this.directions.getStatus().code == G_GEO_SERVER_ERROR)
		 alert("Un geocodifica in direzioni o richiesta non ha potuto essere trattata con successo, ma l'esatto motivo per il fallimento non è noto. Errore n* " + this.directions.getStatus().code);
	   else if (this.directions.getStatus().code == G_GEO_MISSING_QUERY)
		 alert("HTTP parametro q è stato mancante o non ha avuto alcun valore. Per richieste di geocode, questo significa che un vuoto indirizzo è stato specificato come input. Per le indicazioni richieste, il che significa che non è stato specificato di query in ingresso. Errore n* " + this.directions.getStatus().code);
	   else if (this.directions.getStatus().code == G_GEO_BAD_KEY)
		 alert("Il dato chiave non è valido o non corrisponde al dominio per il quale è stato dato. Errore n* " + this.directions.getStatus().code);
	   else if (this.directions.getStatus().code == G_GEO_BAD_REQUEST)
		 alert("Una direzione richiesta non ha potuto essere analizzata con successo. Errore n* " + this.directions.getStatus().code);
	   else alert("Si è verificato un errore.");
	},
	
	directionsLoad: function (){ 
		var poly = this.directions.getPolyline();
		if (poly.getVertexCount() > 10000) {  //cambia il vaolore del numero dei vertici
		 alert("CGMap.directionsLoad(): Questo itinerario ha troppi vertici");
		 return;
   		}
	}
};