//Convert mapZoom to integer
mapZoom = parseInt(mapZoom);

if(streetAddress!='') {
	var fullAddress = streetAddress + ',' + address;
} else {
	//var fullAddress = address;
	var fullAddress = communeName + ' ' + countryName;
}

var geocoder = null;
var map = null;
var geocodingTries = 0;
var viewMarker = false;

// Dichiarato esternamente tramite Typo3
//var viewPanoramio = true;

// Call this function when the page has been loaded
var mapInitialize = function(settedViewMarker) {
  viewMarker = settedViewMarker;
	if (GBrowserIsCompatible()) {
		map = new google.maps.Map2(document.getElementById('map_canvas'));
		//map.enableScrollWheelZoom();
		map.addControl(new google.maps.SmallZoomControl());
		geocoder = new google.maps.ClientGeocoder();
		//map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
		showLocation(fullAddress);
	}
}

function addAddressToMap(response) {
  var point;
  geocodingTries = geocodingTries + 1;
  if (!response || response.Status.code != 200) {
    if (geocodingTries > 2) {
      //Non mostriamo niente
    } else {
      // Mostrimao l'indirizzo locale
      showLocation(address);
    }
    
  } else {
    if (geocodingTries == 2) mapZoom = 7;
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    
    map.setCenter(point, mapZoom);
    if (viewMarker!=false) {
      marker = new GMarker(point);
      map.addOverlay(marker);
    }
    
		// Se richiesto, carichiamo le info foto da panoramio
		if (viewPanoramio == true) {
		  center_lt = point.lat();
		  center_ln = point.lng();
		  epsilon = 0.04;
		  epsilon2 = 0.04;
		  
		  minx = center_ln - epsilon
      miny = center_lt - epsilon2
      maxx = center_ln + epsilon
      maxy = center_lt + epsilon2
      
		  
		  var head;
      var script;

      head = $$('head')[0];
      if (head)
      {
        script = new Element('script', {
          type: 'text/javascript',
          src: 'http://www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=22&minx='+minx+'&miny='+miny+'&maxx='+maxx+'&maxy='+maxy+'&size=thumbnail&callback=storePhotos'
        });
        head.appendChild(script);
      }
    }
  }
}

// showLocation() geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation(locationAddress) {
 geocoder.getLocations(locationAddress, addAddressToMap);
}

function stripQuotes(x){
    x = x.replace(/['"]/g,'&rsquo;');
    
    return x;
};

function storePhotos(panoramio) {
  photos = panoramio.photos;
  numPhotos = panoramio.count;
  // Attiviamo la procedura di inserimento foto panoramio
  // se ci è stata restituita almeno una foto da panoramio
  if (numPhotos > 0) {
    photoGalleryDiv = $('photo-gallery');
    if (photoGalleryDiv) {
      
      // La prima foto va nella pagina in alto e deve essere quadrata
      //singlePhotoContainer
      /*if ($('singlePhoto')) {
        $('singlePhoto').remove();
      }*/
      if (!$('singlePhoto')) {
        singlePhotoUrlSmall = 'http://mw2.google.com/mw-panoramio/photos/small/'+photos[0]['photo_id']+'.jpg';
        singlephotoUrlMedium = 'http://mw2.google.com/mw-panoramio/photos/medium/'+photos[0]['photo_id']+'.jpg';
        singlePhotoUrlToAuthor = ' <br><a style=\'font-weight:normal;\' class=\'viewinpanoramio\' target=\'_blank\' href=\''+photos[0]['photo_url']+'\'>Visualizza la foto di \''+stripQuotes(photos[0]['owner_name'])+'\' in Panoramio</a>';
        singlePhotoElement = Builder.build(
          '<a href="'+singlephotoUrlMedium+'" rel="lightbox[service]" title="'+stripQuotes(photos[0]['photo_title'])+singlePhotoUrlToAuthor+'"><img src="'+singlePhotoUrlSmall+'" id="singlePhoto" class="singlePhoto" alt="'+photos[0]['photo_title']+'" title="'+photos[0]['photo_title']+'" border="0" /></a>'
        );
      
        singlePhotoCopyright = Builder.build(
          '<span><br />Foto fornita da <a href="http://www.panoramio.com/" target="_blank">Panoramio</a> soggetta al copyright del proprio autore.<br /></span>'
        );
       $('singlePhotoContainerInner').insert({ top: singlePhotoCopyright });
     
       $('singlePhotoContainerInner').insert({ top: singlePhotoElement });
    }
     
      
      // Quindi inseriamo un div nella parte finale del contenitore della gallery
      panoramioGalleryDiv = Builder.build(
        '<div id="photo-gallery-panoramio"></div>'
      );
      $('photo-gallery').insert({ bottom: panoramioGalleryDiv });
      
      n = 0;
    	photos.each(function(s, index) {
    	  //La prima foto va nella pagina in alto 
    	  if (n>0) {
          photoUrlMedium = 'http://mw2.google.com/mw-panoramio/photos/medium/'+s['photo_id']+'.jpg';
          photoUrlToAuthor = ' <br><a style=\'font-weight:normal;\' class=\'viewinpanoramio\' target=\'_blank\' href=\''+s['photo_url']+'\'>Visualizza la foto di \''+stripQuotes(s['owner_name'])+'\' in Panoramio</a>';
          photoElement = Builder.build(
            '<div class="tx-dddam-thumbnail"><div class="tx-dddam-innerthumbnail"><a href="'+photoUrlMedium+'" rel="lightbox[service]" title="'+stripQuotes(s['photo_title']) + photoUrlToAuthor + '"><img src="'+s['photo_file_url']+'" width="'+s['width']+'" height="'+s['height']+'" border="0" rel="lightbox" alt="'+s['photo_title']+'" title="'+s['photo_title']+'" /></a></div></div>'
          );
    
          $('photo-gallery-panoramio').appendChild(photoElement);
        }
        n++;
      });
      // inseriamo il testo sul copyright delle foto
      copyrightElement = Builder.build(
        '<div id="photo-gallery-panoramio-copyright">Alcune foto presenti in questo sito sono fornite da <a href="http://www.panoramio.com/" target="_blank">Panoramio</a> e sono soggette al copyright dei loro autori.</div>'
      );
      $('photo-gallery-panoramio').appendChild(copyrightElement);
      
      // Mostriamo il contenitore della galleria, se è nascosto
      // Se la lista di panoramio contiene almeno una immagine???
      if ($('photo-gallery-container')) {
        $('photo-gallery-container').show();
        $('link-to-gallery').show();
      };
    
      // Facciamo rianalizzare a Lightbox la lista di foto
      Lightbox.prototype.updateImageList();
    }
  }
  
  // Mostriamo il contenitore della foto singola che nel comune è stata settata come nascosta dall'inizio
  $('singlePhotoContainerInner').show();
}
