
var ArchiMap = {
    map : null,
    popupTemplate : null,
    mapId : null,
    
    mapOptions : {
		//zoom : null,
		//center : null,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	},
    
    markers : {
        fixed : [],
        mobile : {},
        deletable : [] // quelli da cancellà
    },
    
	category : {
		luoghi_di_culto : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/luoghi-di-culto.png', categories: ['cattolici','anglicani','buddhisti','musulmani','ebraici','valdesi','evangelici','ortodossi']},
		musica : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/musica.png', categories: ['musica']},
		eventi : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/mostre.png', categories: ['mostre']},
		sport : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/sport.png', categories: ['parchi']},
		shopping : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/shopping.png', categories: ['grandi_magazzini']},
		musei : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/musei.png', categories: ['musei']},
		servizi : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/servizi.png', categories: ['esteri','oggetti_smarriti','organismi_internazionali','rimborso_tasse_sugli_acquisti','sanita','servizi_turistici','sicurezza']},
		mangiare : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/mangiare.png', categories: ['ristoranti']},
		dormire : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/dormire.png', categories: ['alberghi','bed_and_breakfast','affittacamere','appartamenti','residence']},
		beni_culturali : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/11_beni-culturali.png', categories: ['beni_architettonici_e_storici']},
		istituzioni_culturali : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/istituzioni-culturali.png', categories: ['strutture_culturali']},
		visite_guidate : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/itinerari.png', categories: ['visite_guidate_e_didattica']},
		manifestazioni : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/manifestazioni.png', categories: ['manifestazioni']},
		spettacolo : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/cinema.png', categories: ['cinema']},
		teatro : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/teatro.png', categories: ['teatro']},
		mostre : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/mostre.png', categories: ['mostre']},
		incontri : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/incontri.png', categories: ['incontri']},
		danza : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/danza.png', categories: ['danza']},
		cinema : {img: 'http://www.manafactory.it/turismoroma_repository/icone_pin/cinema.png', categories: ['cinema']}
	},
    /**
     * category serve solo nel caso dei mobile e corrisponde alle categorie di Curci, tutto minuscolo.
     */
    initMarker : function(type, lat, lng, title, description, category) {       
        if(type == 'fixed') 
        {
            this.markers.fixed.push({
                'lat' : lat,
                'lng' : lng,
                'title' : title,
                'description' : description,
				'icon' : ''
            });
        }
        else if(type == 'mobile')
        {
            if(!this.markers.mobile[category]) this.markers.mobile[category] = [];
            
            this.markers.mobile[category].push({
                'lat' : lat,
                'lng' : lng,
                'title' : title,
                'description' : description,
				'icon' : this.getTheIcon(category)
            });
        }
    },
	
	getTheIcon : function(cat){
		for(var i in this.category){
			for(var x in this.category[i].categories){
				if(cat == this.category[i].categories[x])
					return this.category[i].img;
			}
		}
	},
    
    initMapItinerario : function(mapId) {
        this.mapId = mapId;
        
        this.map = new google.maps.Map(document.getElementById(this.mapId), this.mapOptions);
        
        this.map.fitBounds(this._calculateBounds(this.markers.fixed));
        
        if(this.markers.fixed[0]){
            for(var i in this.markers.fixed) {
                this._printMarker(this.markers.fixed[i], true);
            }
        }
    },
    
    initMapQuartiere : function(mapId, northWestPointLat, northWestPointLng, southEastPointLat, southEastPointLng) {
        this.mapId = mapId;
        
        this.map = new google.maps.Map(document.getElementById(this.mapId), this.mapOptions);
        
        
        this.map.fitBounds(new google.maps.LatLngBounds(
            new google.maps.LatLng(northWestPointLat, northWestPointLng),
            new google.maps.LatLng(southEastPointLat, southEastPointLng)
        ));
	
	if(this.markers.fixed[0]){
            for(var i in this.markers.fixed) {
                this._printMarker(this.markers.fixed[i], true);
            }
        }
    },
    
    initMapSingle : function(mapId, zoom,option_satellite) {
   
    if(option_satellite==undefined){
     var option_satellite=0;
   }
        this.mapId = mapId;
        this.mapOptions['zoom'] = 14;
        this.mapOptions['center'] = new google.maps.LatLng(this.markers.fixed[0].lat, this.markers.fixed[0].lng);
        if(option_satellite=='satellite'){this.mapOptions['mapTypeId']= 'satellite';this.mapOptions['zoom'] = 18;}
      
        this.map = new google.maps.Map(document.getElementById(this.mapId), this.mapOptions);
          
  		
        
        this._printMarker(this.markers.fixed[0], true);
    },
    
	printMobileMarkersCat : function(cat) {
	
		this._deleteMarkers(this.markers.deletable);
		var theCat= this.category[cat].categories;
		var isFull=true;		
        var pieno=0;
		for(var i=0;i<theCat.length;i++){
			isFull = isFull && this._printMobileMarkers(theCat[i]);
			//se ho almeno un risultato nelle sottocategorie valorizzo pieno
			if(isFull) pieno=1;
			
		}
		  
		//se non è pieno stampo un messaggio d'errore,differenziato se è un evento o un servizio
		var under="_";
		var nomecat=cat.replace("_"," ");
		if(pieno!=1)
		
		if(cat=='danza'||cat=='incontri'||cat=='manifestazioni'||cat=='mostre'||cat=='musica'||cat=='sport'||cat=='visite-guidate'||cat=='teatri')
		
			alertMappa('Nessun evento nella voce '+nomecat+' nei dintorni.<br/> <a href=\"http://www.turismoroma.it/?cosa_fare='+cat+'\">Cerca in tutta Roma</a>');
			else 
			alertMappa('Nessun servizio nella voce '+nomecat+' nei dintorni.<br/>');
			
			//se ho risultato e ho la visualizzazione a 45°(satellite a zoom 18), allontano la mappa
			else if(ArchiMap.map.mapTypeId=='satellite'){
			ArchiMap.map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
			}
			
			//se ho uno zoom superiore a 14 lo reimposto a 14 e ricentro la mappa
			if(ArchiMap.map.zoom>14){
		    ArchiMap.map.setZoom(14);
		    }
		    //prendo le coordinate del centro calcolando quelle dei vari marker
		    var coord=ArchiMap.markers.fixed.length;
		    
		   //se ho un solo marker,lo uso come centro
		   	if (coord==1){
		    var nlat=ArchiMap.markers.fixed[0].lat;
			var nlng=ArchiMap.markers.fixed[0].lng;
		}
		
		//se ne ho di più faccio una media matematica tra i punti
		else if(coord>1) {
		var totlat=0;
		var totlng=0;
		
		//sommo latitudine e longitudine
		    for(var yy=0;yy<coord;yy++){
		    totlat+= ArchiMap.markers.fixed[yy].lat;
		    totlng += ArchiMap.markers.fixed[yy].lng;
		    }
		    
		    //le divido per il numero di coordinate
		    var nlat=totlat/coord;
		    var nlng=totlng/coord;
		   }
		   
		   //ricentro la mappa
		    var newcenter = new google.maps.LatLng(nlat,nlng);
            ArchiMap.map.setCenter(newcenter);
			
	},
	
	_printMobileMarkers : function(type) {
        
       		for(var i in this.markers.mobile[type]) {
        	    this._printMarker(this.markers.mobile[type][i],null,type);
        	}
		return this.markers.mobile[type];
    	},
	
    printMobileMarkers : function(type) {
        this._deleteMarkers(this.markers.deletable);
        
        for(var i in this.markers.mobile[type]) {
            this._printMarker(this.markers.mobile[type][i]);
        }
    },
    
    _deleteMarkers : function(markers) {
    
    //se il div .mappa_alert è visibile(nessun risultato in altra ricerca) lo nascondo e cancello il contenuto del messaggio d'errore precedente 
    var stile=$('.mappa_alert').css("display");
    if(stile=='block')
    $('.mappa_alert').fadeOut("slow");
    $('.mappa_alert').empty();
    
        for(var i=0;i<markers.length;i++) {
            markers[i].setMap(null);
        }
    },
    
    _printMarker : function(markerOption, isPermanent,cat) {
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(markerOption.lat, markerOption.lng), 
            map: this.map,
			icon: this.getTheIcon(cat)
        });
        
        if(!isPermanent)
            this.markers.deletable.push(marker); 
            
        this._attachTextToMarker(marker, '<h1>'+markerOption.title+'</h1><p>'+markerOption.description+'</p>');
    },
    
    _attachTextToMarker : function(marker, text) {
        var infowindow = new google.maps.InfoWindow({
            content: text
        });
        
        google.maps.event.addListener(marker, 'click', function(){
            infowindow.open(this.map, marker);
        });
        
        google.maps.event.addListener(this.map, 'click', function(){
            infowindow.close();
        });
    },
    
    _calculateBounds : function(markers) {
    	var north;
    	var south;
    	var east;
    	var west;
    
    	for(var i in markers){
    		if(north < markers[i].lat || !north)
    			north = markers[i].lat;
    		if(south > markers[i].lat || !south)
    			south = markers[i].lat;
    		
            if(east < markers[i].lng || !east)
    			east = markers[i].lng;
    		if(west > markers[i].lng || !west)
    			west = markers[i].lng;
    	}
    
    	return new google.maps.LatLngBounds(
            new google.maps.LatLng(north,west),
            new google.maps.LatLng(south,east)
        );
    }
}

