/*
 *  GmapMedia - 21/08/2006
 *  Description : Gestion Google Maps pour l'annuaire bestofmedia
 *  Copyright (c) 2006 Frantz Gauthier - Bestofmedia
 *  Constructor :
 *      map_conteneur   id of map container html element | String
 *      origine         coord search origine | {lat,lon} : lat,lon => Float
 *      list_mag        array of mag objects (search result object) | [mag1, mag2, ...] mag => Object
 *
 *  Attributes :
 *      @origine        search origine | {lat,lon, point, marker} :
 *                              lat,lon => Float
 *                              point => GLatLng (Google API)
 *                              marker => Gmarker (Google API)
 *      @list_mag       array of mag objects (search result object) | [mag1, mag2, ...] mag => Object
 *      @map            GMap2 => Object (Google API)
 *      @mapCenter      first determined center | GLatLng => Object (Google API)
 *      @originalZoom   first determined zoom | Integer
 */


 var GmapMedia = {
    initialize: function(map_conteneur, origine, list_mag) {
        if (! GBrowserIsCompatible()) return false;
        if (list_mag.length == 0) { if(window.noMap) noMap(); return false };
        // Recupere les coordonnees de l'origine de la recherche et les objets resultats de recherche
        this.origine = origine;
        this.list_mag = list_mag;
        // initialisation de la carte
        this.map = new GMap2($(map_conteneur));
        this.map.addControl(new GLargeMapControl3D());
        
        
        // affichage du plan et des points
        this._showMap();
        this._setPoint();
        this._showPoints();
        for (i=0; i < this.list_mag.length; i++) {
            this.addMarkerEvent(i); //evenement de base : info-bulle
        }
        if (origine.hasOwnProperty('lat')) {
	        this._showOrigine();
	        // mise en place des gestionnaires d'evenement
	        GEvent.addListener(GmapMedia.map, "click", function() {
	            GmapMedia.map.closeInfoWindow();
	        });
        }
        //
        //GEvent.addListener(GmapMedia.map, "infowindowclose", function() {Effect.SlideUp('result-map-selection-wrapper', {duration: 0.5})});
        this.map.enableDoubleClickZoom();
        this.map.enableContinuousZoom();
        this.map.addControl(new GMapTypeControl());
		this.map.addMapType(G_PHYSICAL_MAP);
		this.map.addMapType(G_SATELLITE_3D_MAP);
    },
    // Affichage de la carte centre sur le rectangle circonscrivant tous les points a afficher
    _showMap: function() {
        // Recherche des extremes en latitude/longitude
        var list_lat = new Array();
        list_lat.push(this.origine.lat);
        this.list_mag.each(function(mag){list_lat.push(mag.lat)});

        var list_lon = new Array();
        list_lon.push(origine.lon);
        this.list_mag.each(function(mag){list_lon.push(mag.lon)});

        var lat_max = list_lat.max();
        var lat_min = list_lat.min()

        var lon_max = list_lon.max();
        var lon_min = list_lon.min();

        //  Creation d une marge de 3%  pour eviter les points trop colle au bord
        var margeLat = 3*((lat_max - lat_min)/100);
        var margeLon = 3*((lon_max - lon_min)/100);

        var sw = new GLatLng(lat_min - margeLat, lon_min - margeLon);
        var ne = new GLatLng(lat_max + margeLat, lon_max + margeLon);

        // Calcul coordonnees du centre de la carte
        var centerLat = list_lat.min() + (list_lat.max() - list_lat.min())/2;
        var centerLon = list_lon.min() + (list_lon.max() - list_lon.min())/2;

        this.mapCenter = new GLatLng(centerLat, centerLon);
        this.originalZoom = this.map.getBoundsZoomLevel(new GLatLngBounds(sw, ne));

        this.map.setCenter(this.mapCenter, this.originalZoom);
    },
    _createMarker: function(point, index) {
          // Create a base icon for all of our markers that specifies the
          // shadow, icon dimensions, etc.
          var baseIcon = new GIcon();
          baseIcon.shadow = "http://img.bestofmicro.com/annuaire/map2/shadow50.png";
          baseIcon.iconSize = new GSize(20, 34);
          baseIcon.shadowSize = new GSize(37, 34);
          baseIcon.iconAnchor = new GPoint(9, 34);
          baseIcon.infoWindowAnchor = new GPoint(9, 2);
          baseIcon.infoShadowAnchor = new GPoint(18, 25);
          // Create a lettered icon
          var icon = new GIcon(baseIcon);
          if (GmapMedia.list_mag[index].reseller) {
          icon.image = "http://img.bestofmicro.com/annuaire/map2/marker" + index + "-premium.png";
          } else {
          icon.image = "http://img.bestofmicro.com/annuaire/map2/marker" + index + ".png";
          }
          //icon.printImage = "http://img.bestofmicro.com/annuaire/map2/marker" + index + ".gif";
          //icon.mozPrintImage = "http://img.bestofmicro.com/annuaire/map2/marker" + index + ".gif";
          var marker = new GMarker(point, icon);
          return marker;
    },
    // Ajoute un attribut GLatLng aux objets de list_mag
    _setPoint: function() {
        this.list_mag.each( function(mag) {
            mag.point = new GLatLng(mag.lat, mag.lon);
        });
    },
    // Affiche les points resultats de la recherche sur la carte
    _showPoints: function() {
        this.list_mag.each( function(mag, index) {
            mag.marker = GmapMedia._createMarker(mag.point, index);
            GmapMedia.map.addOverlay(mag.marker);
        });
    },
    addMarkerEvent: function(pos) {

        function myClosure(pos) {
        	var texte = '<strong>' + GmapMedia.list_mag[pos].name + '</strong><p>' + GmapMedia.list_mag[pos].streetName + '<br />' + GmapMedia.list_mag[pos].postalCode + ' ' + GmapMedia.list_mag[pos].cityName + '</p>';
        	if (GmapMedia.list_mag[pos].url) texte += '</p><br /><a href="' + GmapMedia.list_mag[pos].url + '">+ d\'infos</a>';

    	    var closured = function() {
                GmapMedia.list_mag[pos].marker.openInfoWindowHtml(texte);
                switchContent(pos);
            }
            if (GmapMedia.list_mag[pos].initial) {GmapMedia.list_mag[pos].marker.openInfoWindowHtml(texte);}
            return closured;
        }

        GEvent.addListener(GmapMedia.list_mag[pos].marker, "click", myClosure(pos));
    },
    _showOrigine: function() {
        // construction de l'icone
        var icon = new GIcon();
        icon.iconSize = new GSize(30, 30);
        icon.iconAnchor = new GPoint(15, 30);
        icon.infoWindowAnchor = new GPoint(15, 30);
        icon.image = "http://img.bestofmicro.com/annuaire/map2/croixTemp.png";
        // Affichage sur la carte
        this.origine.point = new GLatLng(this.origine.lat, this.origine.lon);
        this.origine.marker = new GMarker(this.origine.point, icon);
        this.map.addOverlay(this.origine.marker);
        // Mise en place des gestionnaires d'evenements pour ce marker
        //GEvent.addListener(GmapMedia.origine.marker, "click", function() {GmapMedia.origine.marker.openInfoWindowHtml('Votre adresse')});
    }

}

/*
 *  Mag - Objet 'magasin' representant les resultats de la recherche dans l'annuaire
 *  Attributes :
 *  @name   String
 *  @lat    Float
 *  @lon    Float
 *  @point  GLatLng object (google API)
 *  ...
 */


function switchContent(id) {
   /* if (Element.getHeight('result-map-selection-content') != 0)
    {
        Effect.SlideUp('result-map-selection-wrapper', {duration: 0.5, afterFinish: function() {var a = $('result-element['+ (id) +']').innerHTML;
        $('result-map-selection-content').innerHTML = a;}});
    } else {
    */
    	if(!$('result-element['+ (id) +']')) return;
        var a = $('result-element['+ (id) +']').innerHTML;
        $('result-map-selection-content').innerHTML = a;
    //}
    var howHeight = Element.getHeight('result-map-selection-content');
    if (!howHeight) {
    	Effect.SlideDown('result-map-selection-wrapper', { queue: 'end', duration: 0.5});
    }
}

/*
 *
 */

function openInfoWindowHtml(id) {
    GmapMedia.list_mag[id].marker.openInfoWindowHtml(
        "<strong>" + GmapMedia.list_mag[id].name + "</strong><p>" + 
        GmapMedia.list_mag[id].streetName + "<br />" + GmapMedia.list_mag[id].postalCode + " " + GmapMedia.list_mag[id].cityName +
        "</p><br /><a href=\"" + GmapMedia.list_mag[id].url + "\">+ d'infos</a>"
    );
   //var bulle = GmapMedia.map.getInfoWindow();
   //GEvent.addListener(bulle, "closeclick", function() {console.log('ccc'); if (Element.getHeight('result-map-selection-content') != 0) Effect.SlideUp('result-map-selection-wrapper', {duration: 0.5});});
}
