var map;
var marker;
var infowindow;

var oldonload = window.onload;
if (typeof window.onload != 'function') {
  window.onload = google_maps_load;
} else {
  window.onload = function() {
    if (oldonload) {
      oldonload();
    }
    google_maps_load();
  }
}

function google_maps_load() {
  marker = Array();
  if (typeof(current_est_id) == "undefined")
    current_est_id = 0;
  array_position = false;
  if(current_est_id) {
    for (i = 0; i < est_descr_id.length; i++) {
      if (est_descr_id[i] == current_est_id) {
        if (est_location_x[i] != "0" && est_location_y[i] != "0")
          array_position = i;
      }
    }
  }
  if (!current_est_id || array_position) {
    var info;
    marker = Array();
    infowindow = Array();
    if (current_est_id) {
      zoom_level = 12;
      latlng = new google.maps.LatLng(est_location_y[array_position], est_location_x[array_position]);
    }
    else {
      zoom_level = 8;
      latlng = new google.maps.LatLng(54.200000, 9.700000);
    }
    var maps_options = {
      zoom: zoom_level,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.HYBRID
    };
    map = new google.maps.Map(document.getElementById("est-google-map"), maps_options);
    j = 0;
    for (i = 0; i < est_descr_id.length; i++) {
      if (est_location_x[i] != "0" && est_location_y[i] != "0") {
        if (current_est_id == est_descr_id[i]) {
          marker_image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/yellow-dot.png";
          current_marker_position = j;
        }
        else
          marker_image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png";
        marker.push(new google.maps.Marker({
          map: map,
          position: new google.maps.LatLng(est_location_y[i],est_location_x[i]),
          title: est_title[i],
          icon: marker_image
        }));
        infowindow.push(new google.maps.InfoWindow({
          content: "<div style=\"font-size: 10px; height: 150px;\"><img src=\"/wp-content/themes/oeko-jahr/est/logo/" + est_title_url[i] + "." + est_logo[i] + "\" style=\"float: right;\"/><h4>" + est_title[i] + "</h4><p>" + est_subtitle[i] + "</p><p><a href=\"/einsatzstelle/" + est_title_url[i] + "\">Mehr Informationen</a></p></div>"
        }));
        google.maps.event.addListener(marker[j], 'click', (function(map, marker, cur_infowindow) { return(function() {
          for (k = 0; k < infowindow.length; k++) {
            infowindow[k].close();
          }
          cur_infowindow.open(map, marker);
          } ) })(map, marker[j], infowindow[j]));
        j++;
      }
    }
/*    if (current_est_id) {
      infowindow = new google.maps.InfoWindow({
        content: "<h4 style=\"height: 50px;\">" + est_title[array_position] + "</h4>"
      });
      infowindow.open(map, marker[current_marker_position]);
    }*/
  }
}
