var G_spotsLoaded={};
var G_clusterer = null;

function initSingleMap(oSpot) {
  oMap = new GMap2(document.getElementById('map'));
  oMap.addControl(new GSmallMapControl());
  oMap.addControl(new GMapTypeControl());
  oLatLng = new GLatLng (oSpot.lat, oSpot.lng );
  oMap.setCenter(oLatLng, 15);    
  oMarker = new PdMarker(oLatLng);
  oMarker.setTooltip(oSpot.sName);
  oMarker.setOpacity(70);  
  oMap.addOverlay(oMarker);
}


function initLargeMap(lat,lng,nZoom, bSearch, extendDynamically) {
  G_tabs= [
    new GInfoWindowTab("Info", "This is tab #1 content"),
    new GInfoWindowTab("Rating", "This is tab #2 content")];
    
  G_baseIcon=new GIcon();
  G_baseIcon.iconSize = new GSize(20, 34);
  G_baseIcon.iconAnchor = new GPoint(9, 34);
  G_baseIcon.infoWindowAnchor = new GPoint(9, 2);

 
  G_baseIcon.shadowSize = new GSize(37, 34);
  G_baseIcon.shadow = "/images/shadow50.png";
  G_baseIcon.infoShadowAnchor = new GPoint(18, 25);    
  
	oMap = new GMap2(document.getElementById('map'));
	oMap.addControl(new GSmallMapControl());
	oMap.addControl(new GMapTypeControl());
	oMap.addControl(new GScaleControl());
	oMap.addControl(new GOverviewMapControl());
	oMap.addControl(new GZoomControl());
  oMap.setCenter(new GLatLng(lat,lng), nZoom);

  clusterIcon=new GIcon();
  clusterIcon.image = "/images/cluster.png";
  clusterIcon.shadow = "/images/cluster_shadow.png";
  clusterIcon.iconSize = new GSize(63.0, 75.0);
  clusterIcon.shadowSize = new GSize(101.0, 75.0);
  clusterIcon.iconAnchor = new GPoint(31.0, 37.0);
  clusterIcon.infoWindowAnchor = new GPoint(31.0, 37.0);

  G_clusterer = new Clusterer(oMap);
  G_clusterer.SetIcon(clusterIcon);
  
  if (bSearch)
  {
  	// if this is search results, add the spots and bound the map
    var bounds = new GLatLngBounds();
    var mySpots;
    if (aSpots.results != null)
    	mySpots = aSpots.results;
    else
    	mySpots = aSpots;
  	for (i=0;i<mySpots.length;i++) {
      var marker=addSpot(mySpots[i]);
      bounds.extend(marker.getPoint()); //only used for search results mode
  	}
    oMap.setZoom(oMap.getBoundsZoomLevel(bounds));
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    oMap.setCenter(new GLatLng(clat,clng));  
  }
  if (extendDynamically) 
  {
  	loadSpotsInView();
   	GEvent.addListener(oMap, "moveend", function() {
    	loadSpotsInView();
    });
  }
}

/* HACKING: shop.to_json returns boolean as "1" string, whereas my own spot rendering produces true/false*/
function loadSpotsInView() {
	$('map-loading-indicator').show();
  
  ne = oMap.getBounds().getNorthEast();
  sw = oMap.getBounds().getSouthWest();
  GDownloadUrl(G_urls.map_data+"?ne="+ne.toUrlValue()+"&sw="+sw.toUrlValue(), function(data, responseCode) {
    spots=eval('('+data+')');
    for (i=0;i<spots.length;i++) {
      s=spots[i];
      s.free = (s.free=='1')? true : false; 
      if (G_spotsLoaded[s.id]!=true) {
        addSpot(s);   
      }
    }
  $('map-loading-indicator').hide();    
  });
}



function addSpot(oSpot){
  sDisplay="<div class='map-balloon'><strong>"+oSpot.name+
		"</strong><br /> "+oSpot.address;
	if (!oSpot.free) 
		sDisplay+="&nbsp;<img alt='kommerziell' src='/images/money.gif'>";
	
	sDisplay+="<br />&nbsp;&nbsp;<a href='javascript:mapDetail("+oSpot.id+")'><img width='12' height='12' src='/images/zoom-in.gif' /> Nahansicht</a>"+
		"<br />&nbsp;&nbsp;<a href='"+G_urls.showShop+"/"+oSpot.id+"'><img width='12' height='12' src='/images/icon-about.gif' /> Details anzeigen &raquo;</a>"+
    "</div>";
  htmls[oSpot.id]=sDisplay;
  G_spotsLoaded[oSpot.id]=true;
	var oMarker = createMarker(new GLatLng(oSpot.lat,oSpot.lng),sDisplay,oSpot.id,oSpot.name, oSpot.free);
	GEvent.addListener(oMarker,'mouseover',function(){over(oSpot.id)});
	GEvent.addListener(oMarker,'mouseout',function(){out(oSpot.id)});
	oMarkers[oSpot.id] = oMarker;
	G_clusterer.AddMarker(oMarker, oSpot.name);	
  return oMarker;
}

function recordSelect(id){
	
	if (oMarkers[id] != null)
	{
		zoomTo(oMarkers[id].getPoint().lat(), oMarkers[id].getPoint().lng(), 15);
		oMarkers[id].openInfoWindowHtml(getDetailHTML(id));
	}
}

function over(id){
	/*if (oMarkers[id] != null)
		oMarkers[id].setImage('/images/teardrop-selected.png');
	
	if ($("record"+id) != null)
	{
		$("record"+id).addClassName('record-hover');
	}*/
};

function out(id){
	if (oMarkers[id] != null)
		oMarkers[id].setImage(oMarkers[id].getIcon().image);
		
	if ($("record"+id) != null)
	{
		$("record"+id).removeClassName('record-hover');
	}
};

function createMarker(point,html,id,name,free) {
	//for custom icons
	var icon = new GIcon(G_baseIcon);
	icon.image=free?"/images/teardrop-green.png":"/images/teardrop-dollar.png";
	//var marker = new PdMarker(point,icon);
	//marker.setTooltip(name);
	//marker.setOpacity(70);
	var marker=new GMarker(point,{icon:icon,title:name});
	
	GEvent.addListener(marker, "click", function() {
	  marker.openInfoWindowHtml(getDetailHTML(id));
	});
	
	GEvent.addListener(marker, "mouseover", function() {
	  
	});

	
	oMarkers[id] = marker;
  return marker;
}


/* For displaying all the cities  */
function initCitiesMap(oCountry) {
	oMap = new GMap2(document.getElementById('map'));

  //var bounds = new GLatLngBounds(new GLatLng(oCountry.lat,oCountry.lng),new GLatLng(oCountry.lat,oCountry.lng));
  //oMap.getBoundsZoomLevel(bounds)

	oMap.addControl(new GSmallMapControl());
	oMap.addControl(new GZoomControl());
  oMap.setCenter(new GLatLng(oCountry.lat, oCountry.lng), 6);

	for (i=0;i<cities.length;i++) {
    oMarker=createCityMarker(cities[i],i+1);
    oMap.addOverlay(oMarker);
	}
  // now that map is zoomed to bounds at the smaller size, open it up a bit
  //$('#cities-map').css('height','600px')
}

//called by initCountryMap
function createCityMarker(city,rank){
  marker = new PdMarker(new GLatLng (city.lat, city.lng ));
  var hsName = "Hotspot";
  if (city.spots_count != 1)
  	hsName += "s";
  marker.setTooltip(city.name+" ("+city.spots_count+" "+ hsName +")");
  marker.setOpacity(80);
  
  GEvent.addListener(marker, "click", function() {
    document.location=G_urls.city+'/'+city.link;
	});
	
	return marker;
}

function getDetailHTML(id){
  return htmls[id];
}

function zoomTo(lat,lng,zoom) {
  if (zoom==null) zoom=oMap.getZoom()+3;
  oMap.setCenter(new GLatLng(lat,lng),zoom);
}

function mapDetail(id) {
  oMap.showMapBlowup(oMarkers[id].getPoint(),{mapType:G_HYBRID_MAP,zoomLevel:18});
}


function loadSmallMapNewSpot(oCity){  
  oMap = new GMap2($('map'));
  oMap.addControl(new GSmallMapControl());
  oMap.addControl(new GMapTypeControl());
  if (editSpotID == undefined)
  	oMap.setCenter(new GLatLng(oCity.lat,oCity.lng), oCity.nZoom);
}


/* Ajax Check Address */
function checkAddressForSubmit() {
  bRes=G_bValidGeocode;
	if(!G_bValidGeocode){
		alert("Bitte überprüfen Sie die Adresse, bevor Sie den Hotspot speichern!");
	} else if ($('hotspot_address').value != G_sKnownGoodAddress) {
		alert("Sie haben die Adresse seit der letzten Überprüfung geändert. Bitte überprüfen Sie die Adresse erneut!");   
		bRes=false;
	}
	return bRes;
}

function addressKeyup(sValue) {
  if (sValue == G_sKnownGoodAddress && G_sKnownGoodAddress != '') {
    $("address-unsure-icon").hide();
    $('address-good-icon').show();
  } else {
    $("address-unsure-icon").show();
    $('address-good-icon').hide();
  }
}

function addressKeypress(e) {
  if (!e) e=window.event;
  if (e.keyCode==13) {
    checkAddress(); 
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    return false;
  }
}

function checkAddress(){
	$("address-unsure-icon").hide();
  oAddress=$('hotspot_address');
	oAddress.disabled=true;
	sAddress=oAddress.value;
	
	$('check_address_button').hide();
	$('check_address_working').show();

	new Ajax.Request(G_urls.validateAddress, {
		method: 'get',
		parameters: { address: sAddress, editSpotID: editSpotID },   
		onSuccess: function(transport) {
			parseAddressJSON (transport.responseText);
		}
	});
}

function parseAddressJSON (sResult){
	$('check_address_button').show();
	$('check_address_working').hide();
	$('hotspot_address').disabled=false;	
	
	var bRes=false;
	var bValid = false;
	var HotSpotName = "";
	var oRes={};
	try {
		var oRes = eval('(' + sResult + ')');
		if (oRes.success || oRes.id != undefined) {
	    bValid = true;
		}
	} catch (e) {
		alert("Check address: failed to parse JSON results: "+e);
	}
	if (bValid) {
		//Eintrag gibt es bereits
		if (oRes.id != undefined) {
			
			//oRes = oRes.attributes;
		  var txt="Achtung. Es existiert bereits ein Hotspot mit dem Namen <a style='font-weight:bold' href='" + G_urls.showShop+'/'+oRes.id + "'>" + oRes.name + "</a> in <strong>"+ oRes.address + "</strong>.<br>Bitte verwenden Sie diese Adresse nur, wenn Sie sich sicher sind. (z.B. Bei mehreren Hotspots in einem Einkaufszentrum).";
		  
		  $('error-message').update(txt);
		  $('hotspot_address').setStyle({backgroundColor: 'red',   color: 'white' }); 
			Effect.BlindDown('error-message');
			$('hotspot_address').value = oRes.address;
			HotSpotName = oRes.name;
			$('hotspot_address').activate();
			$('address-good-icon').hide();
			G_bValidGeocode=false;
		} else {
			
			/*if (editSpot)
			{
				if (oRes.attributes != undefined)
				{
					oRes = oRes.attributes;
					$('hotspot_address').value = oRes.address;
				}
				else
					$('hotspot_address').value = oRes.full_address;
			}
			else*/
			
			$('hotspot_address').value = oRes.full_address;
				
			$('hotspot_address').setStyle({backgroundColor: 'green',   color: 'white' }); 
			$('address-good-icon').show();
			$('error-message').hide();
		} 

		
		oLatLng = new GLatLng (oRes.lat, oRes.lng );
		oMap.setCenter(oLatLng,15);
		
		if (oMarker != null){
			oMap.removeOverlay(oMarker);
		} 
	  oMarker = new PdMarker(oLatLng);
	  oMarker.setTooltip(HotSpotName);
	  oMarker.setOpacity(70);  
		oMap.addOverlay(oMarker);             
		
		G_bValidGeocode=true;
		G_sKnownGoodAddress=$('hotspot_address').value;		
		
	  bRes=true;
	  
	} else {
		$('address-good-icon').hide();
		$('hotspot_address').setStyle({backgroundColor: 'red',   color: 'white' }); 
		$('error-message').update('Die angegebene Adresse wurde <b>nicht gefunden</b>. Bitte versuchen Sie es erneut und geben Sie ggf. detailliertere Informationen wie z.B. PLZ oder Bundesland mit ein.');
		Effect.BlindDown('error-message');
		$('hotspot_address').activate();
		G_bValidGeocode=false;
	}
  return bRes;
}