 var gmarkers = [];
 var map;

$(document).ready(function() {

  // Kategorien Status auslesen (Checkboxen auf der Seite)
  function getKatStatus(){

    kategorieStatus = "";

    $("input.categories").each(function(){
      if($(this).attr("checked") == true){
        kategorieStatus += $(this).attr("value")+"_";
      }
    });

    return kategorieStatus;
  }

  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));

    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

    // Basel
    //map.setCenter(new GLatLng(47.559614,7.580611), 8);
    // Luzern
    map.setCenter(new GLatLng(46.8957815,8.2455919), 8);


    zoom = map.getZoom();

    swLat = map.getBounds().getSouthWest().lat();
    swLng = map.getBounds().getSouthWest().lng();
    neLat = map.getBounds().getNorthEast().lat();
    neLng = map.getBounds().getNorthEast().lng();

    // Katgeorien
    kats = getKatStatus();

    // Daten je nach Zoomstufe holen
    $.getJSON('index.php?page=locations&zoom='+zoom+'&swLat='+swLat+'&swLng='+swLng+'&neLat='+neLat+'&neLng='+neLng+'&kats='+kats+'&lang='+globalLang, displayMarkers );

    // Zoom Listener
    GEvent.addListener(map, 'zoomend', function() {
      map.clearOverlays();

      zoom = map.getZoom();

      swLat = map.getBounds().getSouthWest().lat();
      swLng = map.getBounds().getSouthWest().lng();
      neLat = map.getBounds().getNorthEast().lat();
      neLng = map.getBounds().getNorthEast().lng();

      // Katgeorien
      kats = getKatStatus();

      $.getJSON('index.php?page=locations&zoom='+zoom+'&swLat='+swLat+'&swLng='+swLng+'&neLat='+neLat+'&neLng='+neLng+'&kats='+kats+'&lang='+globalLang, displayMarkers );
    });

    // Moveend Listener
    GEvent.addListener(map, 'dragend', function() {
      //map.clearOverlays();

      zoom = map.getZoom();

      swLat = map.getBounds().getSouthWest().lat();
      swLng = map.getBounds().getSouthWest().lng();
      neLat = map.getBounds().getNorthEast().lat();
      neLng = map.getBounds().getNorthEast().lng();

      // Katgeorien
      kats = getKatStatus();

      $.getJSON('index.php?page=locations&zoom='+zoom+'&swLat='+swLat+'&swLng='+swLng+'&neLat='+neLat+'&neLng='+neLng+'&kats='+kats+'&lang='+globalLang, displayMarkers );
    });

    // Map der aktuellen Browsergröße anpassen
    function resizeMap() {
      height = $("html").height();
      width = $("body").width();
      mapWidth = width - 347;
      mapHeight = height - 140;
      minWidth = 650;
      minHeight = 470;
      // Karte resizen
      if(mapWidth < minWidth){
        newMapWidth = minWidth;
      }
      else{
        newMapWidth = mapWidth;
      }
      if(mapHeight < minHeight){
        newMapHeight = minHeight;
      }
      else{
        newMapHeight = mapHeight;
      }
      $("#map").css("width", newMapWidth);
      $("#map").css("height", newMapHeight);

      // Schwarzer Abdecker für Fotos
      $("#foto-view").css("width", newMapWidth);
      $("#foto-view").css("height",  newMapHeight);

      // Foto auf dem schwarzen Abdecker mittig positionieren
      newTop = Math.ceil(newMapHeight / 2) - Math.ceil($("#foto-view-img").height() / 2) + 99;
      newLeft = Math.ceil(newMapWidth / 2) - Math.ceil($("#foto-view-img").width() / 2) + 15;
      $("#foto-view-img").css("left", newLeft);
      $("#foto-view-img").css("top", newTop);
      $("#foto-view-text").css("left", newLeft);
      $("#foto-view-text").css("top", newTop + $("#foto-view-img").height());

      // Closebutton
      $("#close-button").css("left", newLeft + $("#foto-view-img").width()- 15);
      $("#close-button").css("top", newTop + 5);

      // Kategorienspalte rechts
      if($("#kategorien ul").height() < $("#map").height() - 195){
        $("#kategorien").css("height", $("#map").height() - 195);
      }

      map.checkResize();
      map.clearOverlays();
      //Basel
      //map.setCenter(new GLatLng(47.559614,7.580611), 8);
      //Luzern
      map.setCenter(new GLatLng(46.8957815,8.2455919), 8);

      zoom = map.getZoom();

      swLat = map.getBounds().getSouthWest().lat();
      swLng = map.getBounds().getSouthWest().lng();
      neLat = map.getBounds().getNorthEast().lat();
      neLng = map.getBounds().getNorthEast().lng();

      // Katgeorien
      kats = getKatStatus();

      $.getJSON('index.php?page=locations&zoom='+zoom+'&swLat='+swLat+'&swLng='+swLng+'&neLat='+neLat+'&neLng='+neLng+'&kats='+kats+'&lang='+globalLang, displayMarkers );
    };

    var resizeTimer = setTimeout(resizeMap, 200);
    $(window).bind('resize', function() {
      if (resizeTimer) clearTimeout(resizeTimer);
      resizeTimer = setTimeout(resizeMap, 200);
    });

  }

  // Marker darstellen
  function displayMarkers(json){

    $.each(json, function(i,item){

      var icon = new GIcon();
      icon.image = "img/uploads/"+item.image_name+item.id+"_icon.png";
      icon.iconSize = new GSize(32, 32);
      icon.iconAnchor = new GPoint(15, 15);
      icon.infoWindowAnchor = new GPoint(15, 15);

      var marker = new GMarker(new GLatLng(item.latitude, item.longitude), icon);
      GEvent.addListener(marker, 'click', function() {

        try { et_eC_Wrapper( 'FQxGuE', 'Foto Infobubble', 'Foto ID:'+item.id, 0, '', '', 0, 0, 0, 0, 0, 0, 0); } catch(e) { };
//        pageTracker._trackPageview("/index.php?page=infowindow&id="+item.id+"&lang=de");

        marker.openInfoWindowHtml('<img src="img/ajax-loading.gif" /><br />Loading....');

        $.get('index.php?page=infowindow&id='+item.id+'&lang='+globalLang, function(data){
          marker.openInfoWindowHtml(data);

            function bewertung(){
            var colorBefore = new Array();
            $("#links a").hover(function(){

            // Alte Werte merken
            colorBefore["1"] = $("#links a[@name='1'] img").attr("src");
            colorBefore["2"] = $("#links a[@name='2'] img").attr("src");
            colorBefore["3"] = $("#links a[@name='3'] img").attr("src");
            colorBefore["4"] = $("#links a[@name='4'] img").attr("src");
            colorBefore["5"] = $("#links a[@name='5'] img").attr("src");

            // Alles auf grau stellen#+
            $("#links a[@name='1'] img").attr("src", "img/star-grey.gif");
            $("#links a[@name='2'] img").attr("src", "img/star-grey.gif");
            $("#links a[@name='3'] img").attr("src", "img/star-grey.gif");
            $("#links a[@name='4'] img").attr("src", "img/star-grey.gif");
            $("#links a[@name='5'] img").attr("src", "img/star-grey.gif");

              var i = 1;
              while(i<=$(this).attr("name")){
                $("#links a[@name='"+i+"'] img").attr("src", "img/star-orange.gif");
                i++;
              }
            }, function(){

               $("#links a[@name='1'] img").attr("src", colorBefore["1"]);
               $("#links a[@name='2'] img").attr("src", colorBefore["2"]);
               $("#links a[@name='3'] img").attr("src", colorBefore["3"]);
               $("#links a[@name='4'] img").attr("src", colorBefore["4"]);
               $("#links a[@name='5'] img").attr("src", colorBefore["5"]);
            });

            $("#links a").click(function(){
              vote = $(this).attr("name");
              $.ajax({
                type: "POST",
                url: "index.php?page=voting",
                data: "id="+item.id+"&vote="+vote+"&action=update",
                success: function(data){
                if(data >= 1 ){
                var j=5;
                $("#links a img").each(function(){

                 if(j<=data){
                    $(this).attr("src", "img/star-orange.gif");
                    colorBefore[j] = "img/star-orange.gif";
                  }
                  else{
                    $(this).attr("src", "img/star-grey.gif");
                    colorBefore[j] = "img/star-grey.gif";
                  }

                  j--;
                })

                  $("#message").slideDown(function(){
                    $("#links a").unbind();
                    $("#links a[@name='1']").css("cursor", "default");
                    $("#links a[@name='2']").css("cursor", "default");
                    $("#links a[@name='3']").css("cursor", "default");
                    $("#links a[@name='4']").css("cursor", "default");
                    $("#links a[@name='5']").css("cursor", "default");
                    window.setTimeout('$("#message").slideUp()', 4000);

                  });
                }
                }
              });

              return false;
            });
            }


          // Schauen ob schon mal bewertet wurde
           GEvent.addListener(marker, 'infowindowopen', function() {
           $.get('index.php?page=voting&id='+item.id, function(res){
            if(res == 1){
             bewertung();
            }
            else{
              $("#links a[@name='1']").css("cursor", "default");
              $("#links a[@name='2']").css("cursor", "default");
              $("#links a[@name='3']").css("cursor", "default");
              $("#links a[@name='4']").css("cursor", "default");
              $("#links a[@name='5']").css("cursor", "default");
            }
           });

           });
/*
          $("#foto-zeigen").click(showFoto);
          $("#thumb-img").click(showFoto);

          function showFoto(){
            $("#foto-view").show();

            $("#foto-view-img").attr("src", "img/uploads/"+item.image_name+item.id+"_resized.jpg");
            // Foto auf den schwazen Abdecker

            $("#foto-view-img").show(function(){

              $("#foto-view-text").empty();
              height = $("html").height();
              width = $("body").width();
              mapWidth = width - 347;
              mapHeight = height - 140;
              minWidth = 650;
              minHeight = 470;
alert(json);              // Karte resizen
              if(mapWidth < minWidth){
                newMapWidth = minWidth;
              }
              else{
                newMapWidth = mapWidth;
              }
              if(mapHeight < minHeight){
                newMapHeight = minHeight;
              }
              else{
                newMapHeight = mapHeight;
              }

              $("#foto-view-text").css("width",$("#foto-view-img").width() - 2);
              $("#foto-view-text").append("<strong>"+item.title+"</strong><br />"+item.description);
              $("#foto-view-text").show();
              $("#close-button").show();

              newTop = Math.ceil(newMapHeight / 2) - Math.ceil($("#foto-view-img").height() / 2) + 99;
              newLeft = Math.ceil(newMapWidth / 2) - Math.ceil($("#foto-view-img").width() / 2) + 15;
              $("#foto-view-img").css("left", newLeft);
              $("#foto-view-img").css("top", newTop);
              $("#foto-view-text").css("left", newLeft);
              $("#foto-view-text").css("top", newTop + $("#foto-view-img").height());

              // Closebutton
              $("#close-button").css("left", newLeft + $("#foto-view-img").width()- 15);
              $("#close-button").css("top", newTop + 5);
            });

            $("#foto-view").click(function(){
              $("#foto-view").hide();
              $("#foto-view-img").hide();
              $("#foto-view-text").empty();
              $("#foto-view-text").hide();
              $("#close-button").hide();
            });

            $("#foto-view-img").click(function(){
              $("#foto-view").hide();
              $("#foto-view-img").hide();
              $("#foto-view-text").empty();
              $("#foto-view-text").hide();
              $("#close-button").hide();
            });

            $("#close-button").click(function(){
              $("#foto-view").hide();
              $("#foto-view-img").hide();
              $("#foto-view-text").empty();
              $("#foto-view-text").hide();
              $("#close-button").hide();
            });

            return false;
          }
*/
        });
      });

      marker.category = item.categories_id;
      map.addOverlay(marker);
      if($("input#"+item.name).attr("checked") == false){
        marker.hide();
      }

      gmarkers.push(marker);
    });
  }

  // Kategorien an- und ausschalten
  $("input.categories").click(function(){

    if($(this).attr("checked") == true){
      show($(this).attr("value"));
    }
    else{
      hide($(this).attr("value"));
    }
  });

  function show(category) {

    map.clearOverlays();
    zoom = map.getZoom();

    swLat = map.getBounds().getSouthWest().lat();
    swLng = map.getBounds().getSouthWest().lng();
    neLat = map.getBounds().getNorthEast().lat();
    neLng = map.getBounds().getNorthEast().lng();

    // Katgeorien
    kats = getKatStatus();

    $.getJSON('index.php?page=locations&zoom='+zoom+'&swLat='+swLat+'&swLng='+swLng+'&neLat='+neLat+'&neLng='+neLng+'&kats='+kats+'&lang='+globalLang, displayMarkers );


    for (var i=0; i<gmarkers.length; i++) {
      if (gmarkers[i].category == category) {
        gmarkers[i].show();
      }
    }
  }

  function hide(category) {
    for (var i=0; i<gmarkers.length; i++) {
      if (gmarkers[i].category == category) {
        gmarkers[i].hide();
      }
    }

    map.closeInfoWindow();
  }

  // Geosuche
  var reasons = new Array();
  var geo = new GClientGeocoder();
  var searchMarker = undefined;


  reasons[G_GEO_SUCCESS]            = "Success";
  reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
  reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
  reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
  reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
  reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
  reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

  // Geocoding Formular
  $("form[@name='addressSearch']").submit(function(){

  geo.getLocations($("#search").attr("value"), function (result){
    if (result.Status.code == G_GEO_SUCCESS) {
      if (result.Placemark.length > 1) {
//        $("#message").empty();
//        $("#message").append("<strong>Did you mean:</strong>");
        // Loop through the results
/*        for (var i=0; i<result.Placemark.length; i++) {
          var p = result.Placemark[i].Point.coordinates;
          $("#message").append("<br>"+(i+1)+": <a href='javascript:placeMarker(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"</a>");
        }
        */
        var p = result.Placemark[0].Point.coordinates;
      }
      else {
        //$("#message").empty();
        var p = result.Placemark[0].Point.coordinates;

      }
//      placeMarker(p[1],p[0]);
//console.log(p[1]+"--"+p[0]);

      var point = new GLatLng(p[1],p[0]);
      map.setCenter(point,map.setZoom(13));

      // Bilder auf die Karte setzen
      swLat = map.getBounds().getSouthWest().lat();
      swLng = map.getBounds().getSouthWest().lng();
      neLat = map.getBounds().getNorthEast().lat();
      neLng = map.getBounds().getNorthEast().lng();

      // Katgeorien
      kats = getKatStatus();

      $.getJSON('index.php?page=locations&zoom='+zoom+'&swLat='+swLat+'&swLng='+swLng+'&neLat='+neLat+'&neLng='+neLng+'&kats='+kats+'&lang='+globalLang, displayMarkers );

      if(searchMarker != undefined){
        map.removeOverlay(searchMarker);
      }
      searchMarker = new GMarker(point);
      map.addOverlay(searchMarker);
    }
  });

  return false;
  });

});

function windowOpen(){
  window.open("bedingungen_"+globalLang+".html", "Zweitfenster", "width=500,height=550,left=200,top=200,scrollbars=yes");
}

function windowOpenLegal(){
  window.open("rechtlichehinweise.html", "Zweitfenster", "width=500,height=550,left=200,top=200,scrollbars=yes");
}

function showFoto(image_name,id,title,description){

  $("#foto-view").show();

  $("#foto-view-img").attr("src", "img/uploads/"+image_name+id+"_resized.jpg");
  $.get("img/uploads/"+image_name+id+"_resized.jpg", function(){

    // Foto auf den schwazen Abdecker
    $("#foto-view-img").show(function(){

      $("#foto-view-text").empty();
      height = $("html").height();
      width = $("body").width();
      mapWidth = width - 347;
      mapHeight = height - 140;
      minWidth = 650;
      minHeight = 470;
      // Karte resizen
      if(mapWidth < minWidth){
        newMapWidth = minWidth;
      }
      else{
        newMapWidth = mapWidth;
      }
      if(mapHeight < minHeight){
        newMapHeight = minHeight;
      }
      else{
        newMapHeight = mapHeight;
      }

      $("#foto-view-text").css("width",$("#foto-view-img").width() - 2);
      $("#foto-view-text").append("<strong>"+title+"</strong><br />"+description);
      $("#foto-view-text").show();
      $("#close-button").show();

      newTop = Math.ceil(newMapHeight / 2) - Math.ceil($("#foto-view-img").height() / 2) + 99;
      newLeft = Math.ceil(newMapWidth / 2) - Math.ceil($("#foto-view-img").width() / 2) + 15;
      $("#foto-view-img").css("left", newLeft);
      $("#foto-view-img").css("top", newTop);
      $("#foto-view-text").css("left", newLeft);
      $("#foto-view-text").css("top", newTop + $("#foto-view-img").height());

      // Closebutton
      $("#close-button").css("left", newLeft + $("#foto-view-img").width()- 15);
      $("#close-button").css("top", newTop + 5);
    });

    $("#foto-view").click(function(){
      $("#foto-view").hide();
      $("#foto-view-img").hide();
      $("#foto-view-text").empty();
      $("#foto-view-text").hide();
      $("#close-button").hide();
    });

    $("#foto-view-img").click(function(){
      $("#foto-view").hide();
      $("#foto-view-img").hide();
      $("#foto-view-text").empty();
      $("#foto-view-text").hide();
      $("#close-button").hide();
    });

    $("#close-button").click(function(){
      $("#foto-view").hide();
      $("#foto-view-img").hide();
      $("#foto-view-text").empty();
      $("#foto-view-text").hide();
      $("#close-button").hide();
    });

  });

  return false;

}

