var map;
var geocoder;
var baseIcon;
var filter_id;
var marker_id;
var default_point;
var i;
var node;
var temp_element;
var positions = [];
var gmarkers = [];
var points = [];
var filters = [];
var temp_array = [];
var can_interact_with_map = false;

Event.observe(window, 'load', function(){loadMap(default_location)}, false);

// At first, we load the map.
function loadMap(default_location){
  // Inits the map.
  google.load("maps", "2", {
    "language" : default_location["culture"],
    "callback" : mapLoaded,
    "other_params" : default_location
  });
}

// Then, we use the map.
function mapLoaded(){
  // Use the map.
  map = new google.maps.Map2($(default_location["canvas"]));
  geocoder = new google.maps.ClientGeocoder();
  map.clearOverlays();
  // Adds controls.
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  // Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
  baseIcon = new GIcon();
//   baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
  baseIcon.iconSize = new GSize(22, 23);
//   baseIcon.shadowSize = new GSize(37, 34);
  baseIcon.iconAnchor = new GPoint(9, 34);
  baseIcon.infoWindowAnchor = new GPoint(9, 2);
//   baseIcon.infoShadowAnchor = new GPoint(18, 25);
  // Show default position.
  showLocation(default_location, true, true);
  // if fiters exist, let's use them
  if($('map_filters'))
  {
    window.setTimeout(function(){initSidebar();}, 2000);
//     initSidebar();
  }
}

// initSidebar() is called to use filters and to add all the locations on the map.
function initSidebar(){
  // Positions
  for(var i in positions){
    if(!isNaN(i)){
      // Add the location
      addLocation(positions[i]);
      // Hide Positions Blocks from the CMS if not logged
      if($('slot_'+i) && !$('toolbar_'+i))
      {
        $('slot_'+i).hide();
      }
      // Load element interaction
      temp_element = $('filter_position_'+positions[i]['id']);
      positions['filter_position_'+positions[i]['id']] = positions[i];
      Event.observe(temp_element, 'click', function(event) {
        if(Event.element(event).tagName == 'LI')
          var myElement = positions[Event.element(event).id];
        else
          var myElement = positions[Event.element(event).readAttribute('class')];
        showLocation(myElement['id'], true, false);
      });
      // Show element
      temp_element.show();
    }
  }

  // Filters
  for(var i in filters){
    if(!isNaN(i)){
      // Load element interaction
      temp_array = $$('#map_filters .filter_'+i+' .link');
      temp_array.each(function(node){
        filters['filter_filter_'+i] = filters[i];
        Event.observe(node, 'click', function(event) {
          var myElement = filters[Event.element(event).id];
          toggleFilter(myElement['id'], myElement['slot_id']);
        });
        node.show();
      });
    }
  }
  can_interact_with_map = true;
}

// addLocation() is called to add a location on the map.
function addLocation(infos){
  if(infos["id"]){
    // if coordinates, let's use them
    if ((infos['latitude'] != '') && (infos['longitude'] != '')){
      var point = new google.maps.LatLng(infos['latitude'],infos['longitude'] );
//       window.setTimeout(function(){addMarkerToLocation(point, infos);}, 1000);
      addMarkerToLocation(point, infos);
    } else {
    // otherwise, let's use the address, if exists.
      if (infos["address"] != ''){
        geocoder.getLocations(infos["address"], function(response){
          if (!response || response.Status.code != 200) {
            var point = default_point;
          } else {
            var point = new google.maps.LatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]);
          }
          addMarkerToLocation(point, infos);
        });
      }
    }
  }
}

// addMarkerToLocation() is called to add a marker on the map.
function addMarkerToLocation(coordinates, infos){
  // Create a lettered icon for this point using our icon class
  if(infos["filter"] != ''){
    var filter_id = infos["filter"];
    var letter = String.fromCharCode("A".charCodeAt(0) + filters[filter_id]["id"]);
  } else {
    var letter = '';
  }
  var letterIcon = new GIcon(baseIcon);
  letterIcon.image = "/images/marker" + letter + ".png";

  // Create the marker
  var marker = new GMarker(coordinates, {icon:letterIcon});
  map.addOverlay(marker);
  marker_id = infos["id"];
  gmarkers[marker_id] = marker;
  points[marker_id] = coordinates;
  if(infos["description"] != ''){
    GEvent.addListener(marker,"click", function() {
      marker.openInfoWindowHtml(infos["description"]);
    });
  }
  return marker;
}

// showLocation() is called :
// - to show the default location
// - when you click on an item in the list.
function showLocation(infos, display_info, is_default_location){
  if(is_default_location){
    // if coordinates, let's use them
    if ((infos["latitude"] != '') && (infos["longitude"] != '')){
      default_point = new google.maps.LatLng(infos["latitude"], infos["longitude"]);
      map.setCenter(default_point, parseFloat(infos["zoom"]));
      if(display_info && (infos["description"] != '')){
        marker = addMarkerToLocation(default_point, infos);
        marker.openInfoWindowHtml(infos["description"]);
      }
    } else {
    // otherwise, let's use the address, if exists.
      if (is_default_location && (infos["address"] == '')){
        map.setZoom(infos["zoom"]);
      } else if (infos["address"] != ''){
        geocoder.getLatLng(infos["address"], function (point){
          default_point = point;
          map.setCenter(default_point, parseFloat(infos["zoom"]));
          if(display_info && (infos["description"] != '')){
            marker = addMarkerToLocation(default_point, infos);
            marker.openInfoWindowHtml(infos["description"]);
          }
        });
      }
    }
  } else {
    marker_id = infos;
    map.panTo(points[marker_id]);
    gmarkers[marker_id].openInfoWindowHtml(positions[marker_id]["description"]);
  }
}

// toggleFilter() is called to show/hide the marker
function toggleFilter(my_filter_id, my_slot){
  if(document.loaded && (can_interact_with_map == true)){
    for(var i in positions){
      if(!isNaN(i)){
        if((positions[i]["filter"] != '') && (positions[i]["filter"] == my_filter_id)){
          marker_id = positions[i]["id"];
          if (gmarkers[marker_id].isHidden()){
            gmarkers[marker_id].show();
            temp_array = $$("#google_maps_positions_"+my_slot+" .filter_"+my_filter_id);
            temp_array.each(function(node){
              node.show();
            });
          } else {
            gmarkers[marker_id].hide();
            temp_array = $$("#google_maps_positions_"+my_slot+" .filter_"+my_filter_id);
            temp_array.each(function(node){
              node.hide();
            });
          }
        }
      }
    }
    $("google_maps_filter_"+my_slot+"_"+my_filter_id).toggleClassName("unchecked");
  }
}

