/*
 * Handles methods and properties for Google Map on restaurantWholeDtail.php
 * @author Cyril Amar, from work of David Galvis
 * @date 02/12/2009
 */

function MapResto (idMap, options, idResto) {

    if (GBrowserIsCompatible()) {
		jQuery.extend(this, options);
        this.id = idMap;
        this.map = new GMap2(document.getElementById( idMap ));
		if (this.showControls)
            this.map.addControl(new GLargeMapControl3D());
        this.map.setCenter(new GLatLng(this.center.lat, this.center.lng), this.center.zoom);
        
		this.map.enableContinuousZoom();
		this.geocoder = new GClientGeocoder();
        
		this.bounds = new GLatLngBounds();
        var mgrOptions = { borderPadding: 50, maxZoom: 5 };
        this.markerMgr = new MarkerManager(this.map, mgrOptions);

        this.idResto = idResto;
        
        // Enphasizer
        //var icon = new GIcon(G_DEFAULT_ICON);
        //icon.image = '/images/itaste_logo_57.gif';
        //icon.shadow = false;
        //var size = 17;
        //icon.iconSize = new GSize(size,size);
        //icon.iconAnchor = new GPoint(size/2, 45);
        //var point = new GLatLng(this.center.lat, this.center.lng);
        //this.enphasizer = new GMarker(point, {icon:icon});
        //this.enphasizer.icon = icon;
        //this.map.addOverlay(this.enphasizer);
        //this.enphasizer.hide();
	}
}

MapResto.prototype =
{
    /*
     * Images for the icons of the different zoom levels
     */
    images : [
        // Unrated icons
        [
            //'/images/bulleNoRated.png',
            '/images/bulleNoRated_pin.png',
            '/images/bulleNoRated_pin.png',
            '/images/bulleNoRated_pin.png',
        ],
         // Favorite icons
        [
            '/images/bulleRated_pin.png',
            '/images/bulleRated_pin.png',
            '/images/bulleRated_pin.png'
        ],

        // Want to go
        [
            '/images/bulleWantogo_pin.png',
            '/images/bulleWantogo_pin.png',
            '/images/bulleWantogo_pin.png'
        ]
    ],

    markerCount : 0,

    /**
     * Flag for listeners
     */
    listeners : false,

    /**
     * Default center of the map
     */
    center : {
        lng : 1.740879,
        lat : 47.154607,
        zoom : 5
    },

    showControls : true,

    /**
     * Adds a marker
     * @param data object Contains marker informations such as bounds (lat & lng), rating, id
     * @param object options options for marker such as icon size.
     */
    addMarker : function(data, options)
    {
        if (data.x == 0 || data.y == 0)
            return false;
        
        var _this = this;
        var point = new GLatLng(data.x, data.y);
        this.bounds.extend(point);
        var icon = this.initIcon(data, options);
        //if (this.map.getZoom() > 14)
        //else var toolTip = '';

        var marker = new GMarker(point, {icon:icon, draggable: true});
        var tooltip = new Tooltip(marker,'<img src="' + this.getRating(data) + '" /> <span class="textOnMap">' + data.nom + '</span>', 4);
        
        //this.markerMgr.addMarker(marker, 5);
        this.map.addOverlay(marker);
        marker.tooltip = tooltip;
        this.map.addOverlay(tooltip);
        
        marker.enableDragging();

        GEvent.addListener(marker, "mouseover", function(){
             this.tooltip.show();
        });

        GEvent.addListener(marker, "mouseout", function(){
            this.tooltip.hide();
        });

        GEvent.addListener(marker, "click", function(){
             _this.markerClick(marker, data);
        });
        
        GEvent.addListener(marker, "dragend", function () {
        	jQuery.post(
        	'/application/ajax/setCoordinatesResto.php',
        	{id: _this.idResto,
        	 x: marker.getLatLng().lat(),
        	 y: marker.getLatLng().lng()},
        	 function (response) {
        		 if (response == '1')
        		 {
        			 jQuery("#modif_ok").show().fadeOut(10000);
        		 }
        		 else
        		 {
        			 jQuery("#modif_ko").show().fadeOut(30000);
        		 }
        	 }
        	);
        });
        // Tooltip
        //this.tooltip(marker, data);
        return marker;
    },

    /**
     * Initializes the icons settings such as icon image, size
     * @param object data
     * @return GIcon
     */
    initIcon : function(data, options)
    {
        //var zoom = this.map.getZoom();
        var icon = new GIcon(G_DEFAULT_ICON);
        var image;
        var size = 17;
        
        icon.image = this.getRating(data);
        icon.shadow = false;

        try{
            if (options.size != 'undefined'){
                size = options.size;
            }
        } catch(e){};
        icon.iconSize = new GSize(12,28);
        icon.iconAnchor = new GPoint(12/2, 28);

        return icon;
    },

    /*
     * Centers the map on the given location
     * @param string location or city to go
     */
    goToLocation : function(location)
    {
        initSearch();
        var _this = this;
       // this.startListeners();
        this.geocoder.getLatLng(
           location,
           function(point) {
              if (!point) {
                //alert(location + " not found");
              } else {
                _this.map.setCenter(point, 15);
              }
          }
        );
        location = location.split(', ');
        filter.city = location[0];
        filter.country = location[1];
        page_actuelle = 1;
        //refresh();
    },

    /**
     * Returns JSON object with the South-west and North-est bounds
     * @return json
     */
    getBounds : function(){
        var bounds = mapSearch.map.getBounds();

        return {
            SW : {
                lat : bounds.getSouthWest().lat(),
                lng : bounds.getSouthWest().lng()
            },
            NE : {
                lat : bounds.getNorthEast().lat(),
                lng : bounds.getNorthEast().lng()
            }
        };
    },

    /**
     * Stars listening to map events
     * @param function (optional) fnc
     */
    startListeners: function(fnc)
    {
        this.listeners = true;
        var _this = this;
        jQuery("#redo_search_move_map").attr('checked', true);
        GEvent.addListener(this.map, "moveend", function()
        {
              try {
                  clearTimeout(GMapTimeout);
              } catch(e){}
              // If the user's zoom is low, for performance questions we don'display the markers
              if (_this.map.getZoom() > 5) {
                 _this.request();
              }
              GMapTimeout = setTimeout('refresh()',10);

              // Callback
              if (typeof fnc == 'function')
                  fnc();
        });
    },

    /**
     * Stops the listeners of the map
     */
    stopListeners : function(){
        this.listeners = false;
        jQuery("#redo_search_move_map").attr('checked', false);
        GEvent.clearListeners(this.map, 'moveend');
    },

    /**
     * Returns if the map is listening
     * @return bool
     */
    isListening : function(){
        return this.listeners;
    },

    /**
     * Ajax request for restaurants
     */
    request : function()
    {
        var _this = this;
        initSearch();
        filter.bounds = _this.getBounds();
        filter.center.lat = _this.map.getCenter().lat();
        filter.center.lng = _this.map.getCenter().lng();
        filter.zoom = _this.map.getZoom();
    },

    /**
     * Gets the rating of the restaurant. If it is null, the
     * restaurant is marked as unrated, otherwise as rated.
     */
    getRating : function(data)
    {
        var satis_global;
        if (data.satis_global == null)
            satis_global = 'null';
        else
            satis_global = Math.round(data.satis_global);

        return '/images/pin_' + satis_global + '.png'
    },

    /**
     * Adds an array of markers on the map
     * @param markers array
     */
    addMarkers : function(markers, options){
        var _this = this;
        //this.clearMarkers();
        _this.markerCount = markers.length;
        var markersArray = [];
        jQuery(markers).each(function(){
                m=_this.addMarker(this, options);
                if (m!=false)
                    markersArray.push(m);
        });
        this.markerMgr.addMarkers(markersArray,5);
        
        setTimeout(function(){
            _this.markerMgr.refresh();
        },200);
    },

    

    fitZoom : function(){
        newzoom = this.map.getBoundsZoomLevel(this.bounds);
        newcenter = this.bounds.getCenter();
        this.map.setCenter (newcenter,newzoom);
    },
    
    getZoom: function()
    {
        return this.map.getBoundsZoomLevel(this.bounds);
    },

    clearMarkers : function(){
        this.bounds = new GLatLngBounds();
        //this.map.clearOverlays();
        this.markerMgr.clearMarkers();
        //this.markerMgr.refresh();
    },

    /**
     * Marker onclick acions
     */
    markerClick : function(marker, data){
        window.location = "/application/restaurantWholeDtail.php?id_rest=" + data.id_etablissement;
    },

    /**
     * Returns the number of markers
     */
    getMarkerCount : function(){
        return this.markerCount;
    }

};
