/*
 * $Id: gMaps.js 2721 2011-05-18 12:39:35Z a.kromark $
 * (c) 2010 Tallence GmbH
 */
window.gicons = [];
window.gmarkers = [];
window.gErrorReasons=[];
window.gMap = {};
window.gGeoCoder = new GClientGeocoder();
window.gMapBubbleClick = false;

function gMapsInitForSingleLocation(startLat, startLng, label, html){
  window.gMap = new GMap(document.getElementById("google_maps_single"));
  window.gMap.addControl(new GLargeMapControl());
  window.gMap.addControl(new GMapTypeControl());
  window.gMap.setCenter(new GLatLng(startLat, startLng),13);

  var marker = gMapsCreatePoint(new GLatLng(startLat, startLng),label,html);
  window.gMap.addOverlay(marker);
}

function gMapsInit(startLat, startLng, startZoomLevel, errorReasons) {
  // init Icons
  var baseIcon = new GIcon(G_DEFAULT_ICON);
  baseIcon.iconAnchor = new GPoint(8,27);
  baseIcon.iconSize = new GSize(16,27);
  baseIcon.infoWindowAnchor = new GPoint(9,2);  //TODO adapt
  window.gicons["orglvl1"] = new GIcon(baseIcon,"/spd-webapp/static/images/gmaps/icon_orglvl1.png");
  window.gicons["orglvl2"] = new GIcon(baseIcon,"/spd-webapp/static/images/gmaps/icon_orglvl2.png");
  window.gicons["orglvl3"] = new GIcon(baseIcon,"/spd-webapp/static/images/gmaps/icon_orglvl3.png");
  window.gicons["orglvl4"] = new GIcon(baseIcon,"/spd-webapp/static/images/gmaps/icon_orglvl4.png");
  window.gicons["orglvl5"] = new GIcon(baseIcon,"/spd-webapp/static/images/gmaps/icon_orglvl5.png");

  // init errorReasons
  window.gErrorReasons = errorReasons;

  // init Map
  window.gMap = new GMap(document.getElementById("google_map"));
  window.gMap.addControl(new GLargeMapControl());
  window.gMap.addControl(new GMapTypeControl());
  window.gMap.setCenter(new GLatLng(startLat, startLng),startZoomLevel);

  // add an listener to the "moveend" event - i.e. when the move has been concluded
  GEvent.addListener(window.gMap, 'moveend', GMapsMoveEnd);
/*  GEvent.addListener(window.gMap, 'dragend', GMapsMoveEnd);
  GEvent.addListener(window.gMap, 'zoomend', GMapsMoveEnd);

  GEvent.addListener(window.gMap, "zoomend", GMapsZoom);*/

  gMapsDownloadMarkers(startLat, startLng, startZoomLevel);
  
};

function GMapsMoveEnd() {
  if (!window.gMapBubbleClick) {
    // when the map has been moved,first clear the old markers, then...
    window.gMap.clearOverlays();
    // ...get new markers for the area!
    gMapsDownloadMarkers(window.gMap.getCenter().lat(), window.gMap.getCenter().lng(), window.gMap.getZoom());
  } else {
    window.gMapBubbleClick = false;
  }
}

/*function GMapsZoom(oldLevel, newLevel) {
  if (newLevel > oldLevel) {
    // zoom in - maybe re-enable checkboxes
    if (newLevel > 7) {
      // disable level 4
      $('#option-orglvl4').removeAttribute('disabled');
    }
    if (newLevel > 6) {
      // disable level 4
      $('#option-orglvl3').removeAttribute('disabled');
    }
    if (newLevel > 5) {
      // disable level 4
      $('#option-orglvl2').removeAttribute('disabled');
    }
  } else {
    // zoom out maybe disable checkboxes
    if (newLevel <= 7) {
      // disable level 4
      $('#option-orglvl4').attr('disabled', true);
    }
    if (newLevel <= 6) {
      // disable level 4
      $('#option-orglvl3').attr('disabled', true);
    }
    if (newLevel <= 5) {
      // disable level 4
      $('#option-orglvl2').attr('disabled', true);
    }
  }
}*/

function gMapsDownloadMarkers(startLat, startLng, startZoomLevel) {
  var jsonProcessor = function(doc) {
    gMapsParseJson(doc,window.gMap);
  }

  // ================================================================
  // === Fetch the JSON data file ====
  // /spd-webapp/gMaps/?lat=12.345678&lgt=34.567890&zoom=12
  GDownloadUrl("/spd-webapp/gMaps/?lat=" + startLat + "&lgt=" + startLng + "&zoom=" + startZoomLevel, jsonProcessor);
}


function gMapsCreateMarker(point,name,html,category) {
  var marker = new GMarker(point,window.gicons[category]);
  // === Store the category and name info as a marker properties ===
  marker.mycategory = category;
  marker.myname = name;
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
    window.gMapBubbleClick = true;
  });
  window.gmarkers.push(marker);
  return marker;
}
function gMapsCreatePoint(point,name,html) {
  var marker = new GMarker(point);
  marker.myname = name;
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(html);
    window.gMapBubbleClick = true;
  });
  window.gmarkers.push(marker);
  return marker;
}

// == shows all markers of a particular category, and ensures the checkbox is checked ==
function gMapsShowCategory(category) {
  for (var i=0; i<window.gmarkers.length; i++) {
    if (window.gmarkers[i].mycategory == category) {
      window.gmarkers[i].show();
    }
  }
  // == check the checkbox ==
  document.getElementById("option-" + category).checked = true;
}

// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function gMapsHideCategory(category) {
  for (var i=0; i<window.gmarkers.length; i++) {
    if (window.gmarkers[i].mycategory == category) {
      window.gmarkers[i].hide();
    }
  }
  // == clear the checkbox ==
  document.getElementById("option-" + category).checked = false;
  // == close the info window, in case its open on a marker that we just hid
  window.gMap.closeInfoWindow();
}

// == a checkbox has been clicked ==
function gMapsBoxclick(box,category) {
  if (box.checked) {
    gMapsShowCategory(category);
  } else {
    gMapsHideCategory(category);
  }
}

// ================================================================
// === Define the function thats going to process the JSON file ===
function gMapsParseJson(doc, map) {
  // === Parse the JSON document ===
  var jsonData = $.parseJSON( doc );

  // === Plot the markers ===
  for (var i=0; i<jsonData.markers.length; i++) {
    var marker = gMapsCreateMarker(new GLatLng(jsonData.markers[i].lat,jsonData.markers[i].lng), jsonData.markers[i].label, jsonData.markers[i].html, jsonData.markers[i].category);
    window.gMap.addOverlay(marker);
  }

  $('#form-in-der-naehe input[name="gMaps-organizations"]').each(function(a,b) {
    var cat = "orglvl" + b.value;
    if (b.checked) {
      gMapsShowCategory(cat);
    } else {
      gMapsHideCategory(cat);
    }
  });
}

function gMapsPlace(lat, lng) {
  var point = new GLatLng(lat,lng);
  var zoomLevel = 14;
  // clear overlays
  window.gMap.clearOverlays();
  window.gMap.setCenter(point,zoomLevel);
  window.gMap.addOverlay(new GMarker(point));

  // now load the new stuff
  gMapsDownloadMarkers(lat, lng, zoomLevel);

  // reset feedback HTML
  $("#gmaps_feedback").empty();
}

function gMapsShowAddress() {
  var search = document.getElementById("map-address").value;
  if (search != null && $.trim(search) != '') {
    search = $.trim(search);
    if (search.toLowerCase().indexOf("deutschland") == -1 && search.toLowerCase().indexOf("germany") == -1) {
      search = search + ", Deutschland";
    }
    // ====== Perform the Geocoding ======
    window.gGeoCoder.getLocations(search, function (result)
      {

        // HotFix: removed clear Overlays() so that the markers stay on the map even after a Search.
        // --> TODO readNew Overlays for the new Coordiantes
        if (result.Status.code == G_GEO_SUCCESS) {
          // ===== If there was more than one result, "ask did you mean" on them all =====
          if (result.Placemark.length > 1) {
            var html = "Mehrere Treffer gefunden. Meinten Sie...?";
            // Loop through the results
            for (var i=0; i<result.Placemark.length; i++) {
              var p = result.Placemark[i].Point.coordinates;
              var _s2 = "<br/>"+(i+1)+": <a href='javascript:gMapsPlace(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"<\/a>";
              html += _s2;
            }
            $("#gmaps_feedback").empty().append(html);
          }
          // ===== If there was a single marker =====
          else {
            var p = result.Placemark[0].Point.coordinates;
            // jump to the coordinates
            gMapsPlace(p[1],p[0]);
          }
        }
        // ====== Decode the error status ======
        else {
          var reason="Code "+result.Status.code;
          if (window.gErrorReasons[result.Status.code]) {
            reason = window.gErrorReasons[result.Status.code]
          }
          alert('Kann "'+search+ '" nicht finden. Grund: ' + reason); //TODO I18N
        }
      }
    );
  }
}



