// table des lieux, cle: id lieu, valeur: lieu JSON
var jsonLineByCommercialId = null;
var jsonPlacesById = null;
var jsonPlaceTypesById = null;
var selectedTypeId = null;
var markersByPlaceTypeId = new Hash();
var map;
var bounds;
var tooltipTitle;
var infoWindow = new google.maps.InfoWindow();

Event.observe(window, 'load', function() {

  var param = '';

  if (typeof(placeParamRequest)!="undefined")
    param += placeParamRequest;
  Map.load();

  new Ajax.Request('/places',
  {asynchronous:true, evalScripts:true, method:'get',
    parameters:param});
});

var Map = {
  load: function() {
      // make map with div that has "map" id
      map = new google.maps.Map($("map"), {
        zoom: defaultPlacesZoom,
        center: new google.maps.LatLng(defaultPlacesCenterLat, defaultPlacesCenterLng),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        navigationControl: true,
        scaleControl: true,
        scrollwheel: true
      });
      bounds = new google.maps.LatLngBounds();

    }
}


// table des arrets, cle: id arret, valeur: arret JSON

var Places = {
  displayPlaces: function( placeTypeId) {
    var markers = markersByPlaceTypeId.get( placeTypeId);

    if ( markers==undefined) {
      markers = $A();
      markersByPlaceTypeId.set( placeTypeId, markers);

      jsonPlacesById.values().each(function(place) {

        if (place.place_type_id == placeTypeId || placeTypeId == 0) {
          var options = {
            icon: place.icon_path,
            shadow: shadowImageFile,
            position: new google.maps.LatLng(place.lat, place.lng),
            map: map,
            title:  place.name,
            visible: true
          };
          var marker = new google.maps.Marker( options);

          markers.push( marker);
          bounds.extend(marker.getPosition());

          google.maps.event.addListener(marker,"click", function() {
            infoWindow.setOptions({
              position: marker.getPosition(),
              content: Places.toHtmlPlace(place)
            });
            infoWindow.open(map, marker);
          });
        }
      });
    } else {
      // display hidden markers
      markers.invoke('setMap',map);
    }
  },

  toHtmlPlace: function( place) {
    var html = "<dl class=\"place_tip_info\">";

    html += "<dt class=\"place_tip_info\">"+ place.name + "</dt>";
    //        html += "<dt style=\"background: url("+
    //                placeTypeImageDir+place.place_type_id+placeTypeImageExt+
    //                ") no-repeat; \" >" + place.name + "</dt>";

    if ( place.address && !place.address.blank())
      html += "<dd>"+place.address+"</dd>";

    if ( place.city_code && !place.city_code.blank())
      html += "<dd>"+place.city_code+"</dd>";

    html += "</dl>";

    var jsonStopAreas = place.stop_area_ids.evalJSON();
    var stopCount = 0;

    if (jsonStopAreas!=undefined && jsonStopAreas!=null)
      stopCount = jsonStopAreas.length;

    if ( stopCount > 0)
    {
      html += "<dl class=\"place_tip_info\">";
      html += "<dt class=\"place_tip_info\">"+tooltipTitle+"</dt>";
      var i = 0;
      for ( i=0; i<stopCount; i++) {
        var stopArea = jsonStopAreas[ i].evalJSON();
        var lines = jsonLineByCommercialId[ stopArea.id].evalJSON();

        html += Places.toHtmlStopLines( stopArea, lines);
      }
      html += "</dl>";
    }

    return html;
  },

  toHtmlStopLines: function( stopArea, lines)
  {
    var html = '';
    html += "<dd class=\"place_tip_info\"><dl ><dt class=\"place_stop_detail\">";
    html += stopArea.name;
    html += "</dt>";
    html += "<div class=\"place_stop_lines_block\">";
    html += Places.toHtmlLines( lines);
    html += "</div></dl></dd>";

    return html+"<dd class=\"place_stop_clear\" ></dd>";
  },

  toHtmlLines: function( lines)
  {
    var html = "";

    var i = 0;
    for (i = 0; i < lines.length; i++) {
      var backColor = lines[ i].color;
      var fontColor = lines[ i].text_color;
      html += "<dd class=\"place_stop_lines\" style=\"background-color: "+backColor+"; color: "+fontColor+";\">"
      html += lines[ i].number;
      html += "</dd>";
      if ( i!=(lines.length-1)) {
        html += " ";
      }
    }

    return html+"<dd class=\"place_stop_clear\" ></dd>";
  },

  load: function( placesJson, lineByCommercialStopJson, translatedTitle) {
    jsonPlacesById = new Hash();

    tooltipTitle = translatedTitle;

    var i = 0;
    for ( i=0; i<placesJson.length; i++) {
      var selectedPlace = placesJson[i].evalJSON();
      jsonPlacesById.set( selectedPlace.id, selectedPlace);
    }
    jsonLineByCommercialId = lineByCommercialStopJson.evalJSON();

    if ( $('menu_place_types')!=null)
      PlaceTypes.load();
    else if ( jsonPlacesById.values().size()>0)
      Places.displayPlaces( jsonPlacesById.values().first().place_type_id);
  }
}

var PlaceTypes = {
  load: function() {
    jsonPlaceTypesById = new Hash();

    $$('#menu_place_types li').each( function( itemLi) {
      var placeTypeHash = new Hash();
      var placeTypeId = PlaceTypes.dataId( itemLi.id);
      placeTypeHash.set( "id", placeTypeId);
      placeTypeHash.set( "name", itemLi.firstDescendant().text);
      this.set( placeTypeId, placeTypeHash.toJSON());
    }, jsonPlaceTypesById);

    PlaceTypes.updateMenuHtml();

    if ( jsonPlaceTypesById.keys().size()>0) {
      PlaceTypes.select( jsonPlaceTypesById.keys()[0]);
    }
  },

  updateMenuHtml: function() {
    var divMenu = $('menu_place_types');

    Event.observe( divMenu, 'click', function(event) {
      var link = event.element();
      // log( 'link.id='+link.id);
      if(link.tagName == "A") {
        var li = link.ancestors()[0];
        PlaceTypes.select( PlaceTypes.dataId( li.id));
      }
      return false;
    });
  },

  dataId: function(domId) {
    return domId.sub( 'place_type_', '');
  },

  domId: function(id) {
    return 'place_type_' + id;
  },

  select: function( placeTypeId) {
    var previousLi = $( PlaceTypes.domId( selectedTypeId));
    var targetLi = $( PlaceTypes.domId( placeTypeId));

    if ( previousLi!=null && previousLi!=undefined)
      previousLi.removeClassName( "placeTypeSelected");

    if ( !targetLi.hasClassName( "placeTypeSelected"))
      targetLi.addClassName( "placeTypeSelected");

    var markers = markersByPlaceTypeId.get( selectedTypeId);
    if ( markers!=undefined) {
      markers.invoke('setMap',null);
    }

    selectedTypeId = placeTypeId;

    Places.displayPlaces( selectedTypeId);
  }
}
