var nachtcaches={"defaultMapLocation":[51.151786,10.415039],"defaultMapZoom":7,"caches":[],"markers":{},"overlays":{},"geocoder":new google.maps.Geocoder,"codeRegex":/^GC[A-Z0-9]+$/,"overlayVisible":false,"cacheTypes":["traditional","multi","mystery","wherigo","letterbox"],"markerIcons":{},"updateInProgress":false,"currentBounds":null};nachtcaches.buildBoundsQueryString=function(){var bounds=nachtcaches.map.getBounds();return[bounds.getSouthWest().lat(),bounds.getSouthWest().lng(),bounds.getNorthEast().lat(),bounds.getNorthEast().lng()].join(",");}
nachtcaches.updateHash=function(){var loc=nachtcaches.map.getCenter(),zoom=nachtcaches.map.getZoom();window.location.hash=[loc.lat(),loc.lng(),zoom].join(",");}
nachtcaches.updateCaches=function(){var qs=nachtcaches.buildBoundsQueryString();$.getJSON("/caches.json",{"bounds":qs},function(data){nachtcaches.caches=data;nachtcaches.didReceiveCaches();});}
nachtcaches.didReceiveCaches=function(){var codes=[];for(var i=0;i<nachtcaches.caches.length;i++){var cache=nachtcaches.caches[i];codes.push(cache.code);if(!(cache.code in nachtcaches.markers)){nachtcaches.addMarkerForCache(cache);}
if(!(cache.code in nachtcaches.overlays)){var pos=nachtcaches.markers[cache.code].getPosition();nachtcaches.addOverlayForCache(cache,pos);}}
for(var code in nachtcaches.markers){if(codes.length==0||codes.indexOf(code)==-1){nachtcaches.markers[code].setMap(null);delete nachtcaches.markers[code];}}
for(var code in nachtcaches.overlays){if(codes.length==0||codes.indexOf(code)==-1){nachtcaches.overlays[code].setMap(null);delete nachtcaches.overlays[code];}}}
nachtcaches.updateExportLinks=function(){var qs=nachtcaches.buildBoundsQueryString();$("#kmlLink").attr("href","/caches.kml?bounds="+qs);$("#rssLink").attr("href","/caches.atom?bounds="+qs);$("#gpxLink").attr("href","/caches.gpx?bounds="+qs);}
nachtcaches.performSearch=function(query){if($.trim(query).length==0){return false;}
nachtcaches.geocoder.geocode({"address":query,"language":"de","region":"de"},function(results,status){if(status==google.maps.GeocoderStatus.OK&&results.length>0){nachtcaches.map.setCenter(results[0].geometry.location);nachtcaches.map.setZoom(11);nachtcaches.updateCaches();}else{nachtcaches.showError("Ort nicht gefunden");}});}
nachtcaches.addMarkerForCache=function(cache){var marker=new google.maps.Marker({"position":new google.maps.LatLng(cache.latitude,cache.longitude),"map":nachtcaches.map,"title":cache.name,"icon":nachtcaches.markerIcons[cache.type]});google.maps.event.addListener(marker,"mouseover",function(){if(nachtcaches.overlayHideTimeout){clearTimeout(nachtcaches.overlayHideTimeout);nachtcaches.overlayHideTimeout=null;}
nachtcaches.hideAllOverlays();nachtcaches.overlays[cache.code].show();});google.maps.event.addListener(marker,"mouseout",function(){nachtcaches.overlayHideTimeout=setTimeout(function(){nachtcaches.hideAllOverlays();},1000);});nachtcaches.markers[cache.code]=marker;}
nachtcaches.addOverlayForCache=function(cache,position){var overlay=new nachtcaches.Overlay(nachtcaches.map,cache,position);nachtcaches.overlays[cache.code]=overlay;}
nachtcaches.removeMarkers=function(){for(var code in nachtcaches.markers){nachtcaches.markers[code].setMap(null);delete nachtcaches.markers[code];}}
nachtcaches.removeOverlays=function(){for(var code in nachtcaches.overlays){nachtcaches.overlays[code].setMap(null);delete nachtcaches.overlays[code];}}
nachtcaches.hideAllOverlays=function(){for(var code in nachtcaches.overlays){nachtcaches.overlays[code].hide();}}
nachtcaches.boundsDidChange=function(){nachtcaches.updateHash();nachtcaches.updateExportLinks();if(nachtcaches.map.getZoom()>=9){$("#exportControls").css("visibility","visible");nachtcaches.updateCaches();}else{nachtcaches.removeOverlays();nachtcaches.removeMarkers();$("#exportControls").css("visibility","hidden");}}
nachtcaches.showLoadingOverlay=function(){var div=$('<div id="loadingOverlay" class="mapOverlay">&nbsp;</div>');$(document.body).append(div);nachtcaches.overlayVisible=true;}
nachtcaches.hideLoadingOverlay=function(){$("#loadingOverlay").remove();nachtcaches.overlayVisible=false;}
nachtcaches.setupMap=function(locationAndZoom){nachtcaches.map=new google.maps.Map($("#map")[0],{"zoom":locationAndZoom.zoom,"center":locationAndZoom.location,"mapTypeId":google.maps.MapTypeId.TERRAIN,"mapTypeControl":false,"navigationControl":false});google.maps.event.addListener(nachtcaches.map,"click",function(){nachtcaches.hideAllOverlays();});for(var i=0;i<nachtcaches.cacheTypes.length;i++){var name=nachtcaches.cacheTypes[i];nachtcaches.markerIcons[name]=new google.maps.MarkerImage("/img/"+name+".png",new google.maps.Size(20,20),new google.maps.Point(0,0),new google.maps.Point(10,10));}}
nachtcaches.getLocation=function(){var ret=null;ret=nachtcaches.getLocationFromHash();if(!ret){ret=nachtcaches.getLocationFromGoogle();}
if(!ret){ret=nachtcaches.getDefaultLocation();}
return ret;}
nachtcaches.getLocationFromHash=function(){if(window.location.hash.length<1){return false;}
var bits=window.location.hash.substring(1).split(",");if(bits.length!==3){return false;}
var lat=parseFloat(bits[0]),lng=parseFloat(bits[1]),zoom=parseInt(bits[2]);if(!lat||!lng||!zoom){return false;}
return{"location":new google.maps.LatLng(lat,lng),"zoom":zoom};}
nachtcaches.setLocationFromGeolocation=function(){nachtcaches.showLoadingOverlay();if(navigator.geolocation){navigator.geolocation.getCurrentPosition(function(position){var loc=new google.maps.LatLng(position.coords.latitude,position.coords.longitude);nachtcaches.hideLoadingOverlay();nachtcaches.map.setCenter(loc);nachtcaches.map.setZoom(11);},function(error){var locationAndZoom=nachtcaches.getLocationFromGoogle();nachtcaches.hideLoadingOverlay();if(locationAndZoom.location){nachtcaches.map.setCenter(locationAndZoom.location);nachtcaches.map.setZoom(locationAndZoom.zoom);}else{nachtcaches.showError("Position konnte nicht bestimmt werden");}});}else{var locationAndZoom=nachtcaches.getLocationFromGoogle();nachtcaches.hideLoadingOverlay();if(locationAndZoom.location){nachtcaches.map.setCenter(locationAndZoom.location);nachtcaches.map.setZoom(locationAndZoom.zoom);}else{nachtcaches.showError("Position konnte nicht bestimmt werden");}}}
nachtcaches.getLocationFromGoogle=function(){if(!google.loader.ClientLocation){return false;}
var lat=google.loader.ClientLocation.latitude,lng=google.loader.ClientLocation.longitude;return{"location":new google.maps.LatLng(lat,lng),"zoom":11};}
nachtcaches.getDefaultLocation=function(){var lat=nachtcaches.defaultMapLocation[0],lng=nachtcaches.defaultMapLocation[1];return{"location":new google.maps.LatLng(lat,lng),"zoom":nachtcaches.defaultMapZoom};}
nachtcaches.setSelectedMapTypeButton=function(id){$("#mapTypeControls button").each(function(){if($(this).attr("id")==id){$(this).addClass("selected");}else{$(this).removeClass("selected");}});}
nachtcaches.showReportCacheDialog=function(code){$.ajax({"url":"/report.html","success":function(data){var html=$(data);html.find("#reportCacheDialog").attr("data-code",code);html.find("h2 > span").text(code);$("#addCacheOverlay").remove();$(document.body).append(html);$("#closeReportCacheDialog").click(function(){$("#reportCacheOverlay").fadeOut("fast",function(){$("#reportCacheOverlay").remove();});});$("#reportCacheDialog button").click(nachtcaches.userDidClickReportCacheButton);}});}
nachtcaches.userDidClickReportCacheButton=function(){var code=$("#reportCacheDialog").attr("data-code"),comment=$("#reportCacheDialog textarea").val();$.ajax({"url":"/caches/"+code+"/report","type":"POST","data":{"comment":comment},"complete":nachtcaches.reportCacheRequestDidComplete});}
nachtcaches.reportCacheRequestDidComplete=function(xhr,textStatus){$("#reportCacheOverlay").remove();if(xhr.status==200){nachtcaches.showNotice("Der Cache wurde erfolgreich gemeldet");}else{nachtcaches.showError("Es ist ein Fehler beim Melden des Caches aufgetreten");}}
nachtcaches.showAddCacheDialog=function(){$.ajax({"url":"/add.html","success":function(data){$("#reportCacheOverlay").remove();$(document.body).append($(data));$("#closeAddCacheDialog").click(function(){$("#addCacheDialog").fadeOut("fast",function(){$("#addCacheOverlay").remove();});});$("#addCacheDialog button").click(nachtcaches.userDidClickAddCacheButton);$("#addCacheDialog input").keydown(function(ev){if(ev.keyCode==13){nachtcaches.userDidClickAddCacheButton();}});}});}
nachtcaches.userDidClickAddCacheButton=function(){var code=$("#addCacheDialog input").val().toUpperCase();$("#addCacheDialog div.notice").text("");$("#addCacheDialog div.error").text("");if(!code||!nachtcaches.codeRegex.test(code)){$("#addCacheDialog div.error").text("Bitte gebe einen gültigen GC-Code ein");return;}
$.ajax({"url":"/caches","type":"POST","data":{"code":code},"complete":nachtcaches.addCacheRequestDidComplete});}
nachtcaches.addCacheRequestDidComplete=function(xhr,textStatus){var response={};try{response=$.parseJSON(xhr.responseText);}catch(e){}
if(xhr.status==200){$("#addCacheOverlay").remove();nachtcaches.showNotice("Danke! Der Cache wurde erfolgreich hinzugefügt.");}else{$("#addCacheDialog div.error").text(response.error||"Es ist ein Fehler beim Eintragen des Caches aufgetreten.");}}
nachtcaches.showNotice=function(message){var html=$('<div id="noticeBar"></div>').text(message);if(nachtcaches.noticeBarHideTimeout){clearTimeout(nachtcaches.noticeBarHideTimeout);nachtcaches.noticeBarHideTimeout=null;}
$("#noticeBar").remove();$(document.body).append(html);nachtcaches.noticeBarHideTimeout=setTimeout(function(){$("#noticeBar").fadeOut(function(){$("#noticeBar").remove();});},2000);}
nachtcaches.showError=function(message){var html=$('<div id="errorBar"></div>').text(message);if(nachtcaches.errorBarHideTimeout){clearTimeout(nachtcaches.errorBarHideTimeout);nachtcaches.errorBarHideTimeout=null;}
$("#errorBar").remove();$(document.body).append(html);nachtcaches.errorBarHideTimeout=setTimeout(function(){$("#errorBar").fadeOut(function(){$("#errorBar").remove();});},2000);}
nachtcaches.setupEventListeners=function(){var searchCallback=function(){var query=$("#search input")[0].value;nachtcaches.performSearch(query);}
setInterval(nachtcaches.checkBounds,500);$("#search button").click(searchCallback);$("#search input").keydown(function(ev){if(ev.keyCode==13){searchCallback();}});$("#zoomOutButton").click(function(){var currentZoom=nachtcaches.map.getZoom();nachtcaches.map.setZoom(currentZoom-1);});$("#zoomInButton").click(function(){var currentZoom=nachtcaches.map.getZoom();nachtcaches.map.setZoom(currentZoom+1);});$("#roadmapMapTypeButton").click(function(){nachtcaches.map.setMapTypeId(google.maps.MapTypeId.ROADMAP);nachtcaches.setSelectedMapTypeButton("roadmapMapTypeButton");});$("#satelliteMapTypeButton").click(function(){nachtcaches.map.setMapTypeId(google.maps.MapTypeId.SATELLITE);nachtcaches.setSelectedMapTypeButton("satelliteMapTypeButton");});$("#hybridMapTypeButton").click(function(){nachtcaches.map.setMapTypeId(google.maps.MapTypeId.HYBRID);nachtcaches.setSelectedMapTypeButton("hybridMapTypeButton");});$("#terrainMapTypeButton").click(function(){nachtcaches.map.setMapTypeId(google.maps.MapTypeId.TERRAIN);nachtcaches.setSelectedMapTypeButton("terrainMapTypeButton");});$("#geolocationButton").click(function(){if(!nachtcaches.overlayVisible){nachtcaches.setLocationFromGeolocation();}});$("#addCacheLink").click(function(ev){if(!nachtcaches.overlayVisible){nachtcaches.showAddCacheDialog();ev.preventDefault();}});}
nachtcaches.checkBounds=function(){var bounds=nachtcaches.map.getBounds();if(bounds!==undefined&&!bounds.equals(nachtcaches.currentBounds)){nachtcaches.boundsDidChange();nachtcaches.currentBounds=bounds;}}
nachtcaches.init=function(){nachtcaches.setupEventListeners();nachtcaches.setupMap(nachtcaches.getLocation());}
$(document).ready(nachtcaches.init);nachtcaches.Overlay=function(map,cache,markerPosition){this.cache=cache;this.markerPosition=markerPosition;this.div=$('<div class="cacheoverlay"> \
                  <div class="inner"> \
                    <h3></h3> \
                    <div> \
                      <div class="box difficulty"> \
                        <img width="60" height="12"> \
                        Difficulty \
                      </div> \
                      <div class="box terrain"> \
                        <img width="60" height="12"> \
                        Terrain \
                      </div> \
                      <div class="box gcvote"> \
                        <img width="60" height="12"> \
                        GCVote \
                      </div> \
                    </div> \
                    <ol class="segmentedControl"> \
                      <li><a class="gc">Auf geocaching.com anzeigen</a> \
                      <li><a href="#" class="report">Cache melden</a> \
                    </ol> \
                  </div> \
                </div>');this.div.hover(function(){if(nachtcaches.overlayHideTimeout){clearTimeout(nachtcaches.overlayHideTimeout);nachtcaches.overlayHideTimeout=null;}},function(){nachtcaches.overlayHideTimeout=setTimeout(function(){nachtcaches.hideAllOverlays();},1000);});this.div.find("h3").text(this.cache.name);this.div.find("a.gc").attr("href","http://coord.info/"+this.cache.code);if(this.cache.gcvote_rating_median!=0&&this.cache.gcvote_votes>=10){var rating=Math.round(this.cache.gcvote_rating_median*2)/2;var str=this.cache.gcvote_rating_median+" bei "+this.cache.gcvote_votes+" Bewertungen";this.div.find(".gcvote img").attr("src","/img/stars/"+rating*10+".png").attr("title",str);}else{this.div.find(".gcvote").remove();}
if(this.cache.difficulty){this.div.find(".difficulty img").attr("src","/img/stars/"+this.cache.difficulty*10+".png");}else{this.div.find(".difficulty").remove();}
if(this.cache.terrain){this.div.find(".terrain img").attr("src","/img/stars/"+this.cache.terrain*10+".png");}else{this.div.find(".terrain").remove();}
this.div.find("a.report").click(function(){nachtcaches.showReportCacheDialog(cache.code);return false;});var stealEvents=["mousedown","dblclick","DOMMouseScroll","contextmenu"],that=this;for(var i=0;i<stealEvents.length;i++){google.maps.event.addDomListener(that.div[0],stealEvents[i],that._onClick);}
this.setMap(map);}
nachtcaches.Overlay.prototype=new google.maps.OverlayView();nachtcaches.Overlay.prototype.onAdd=function(){this.div.appendTo(this.getPanes().floatPane);}
nachtcaches.Overlay.prototype.onRemove=function(){this.div.remove();}
nachtcaches.Overlay.prototype.draw=function(){var overlayProjection=this.getProjection(),m=overlayProjection.fromLatLngToDivPixel(this.markerPosition),x=m.x-27,y=m.y-this.div.height()-19;this.div.css({"top":y+"px","left":x+"px"});}
nachtcaches.Overlay.prototype.show=function(){this.div.css("visibility","visible");}
nachtcaches.Overlay.prototype.hide=function(){this.div.css("visibility","hidden");}
nachtcaches.Overlay.prototype._onClick=function(ev){if(navigator.userAgent.toLowerCase().indexOf("msie")!=-1&&document.all){window.event.cancelBubble=true;}else{ev.stopPropagation();}}