Merge branch 'master' into scheduler
[myslice.git] / plugins / googlemap / static / js / googlemap.js
index c9d3923..d600674 100644 (file)
 /**
- * Description: display a query result in a googlemap
- * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
+ * Description: display a query result in a Google map
+ * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
  * License: GPLv3
  */
 
-/*
- * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
- * Expression) that maps it to the dollar sign so it can't be overwritten by
- * another library in the scope of its execution.
+/* BUGS:
+ * - infowindow is not properly reopened when the maps does not have the focus
  */
 
-(function($){
-
-    var PLUGIN_NAME = 'GoogleMap';
-
-    // routing calls
-    jQuery.fn.GoogleMap = function( method ) {
-               if ( methods[method] ) {
-                       return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
-               } else if ( typeof method === 'object' || ! method ) {
-                       return methods.init.apply( this, arguments );
-               } else {
-                       jQuery.error( 'Method ' +  method + ' does not exist on jQuery.' + PLUGIN_NAME );
-               }    
-    };
-
-    /***************************************************************************
-     * Public methods
-     ***************************************************************************/
-
-    var methods = {
-
-        /**
-         * @brief Plugin initialization
-         * @param options : an associative array of setting values
-         * @return : a jQuery collection of objects on which the plugin is
-         *     applied, which allows to maintain chainability of calls
-         */
-        init : function( options ) {
+// events that happen in the once-per-view range
+googlemap_debug=false;
+// more on a on-per-record basis
+googlemap_debug_detailed=false;
 
-            return this.each(function(){
-         
-                var $this = $(this);
-
-                /* An object that will hold private variables and methods */
-                var plugin = new GoogleMaps(options);
-                $this.data('Manifold', plugin);
-
-                plugin.initialize();
-
-                /* Events */
-                $this.on('show.' + PLUGIN_NAME, methods.show);
-
-                $this.set_query_handler(options.query_uuid, plugin.query_handler);
-                $this.set_record_handler(options.query_uuid, plugin.record_handler); 
-                $this.set_record_handler(options.query_all_uuid, plugin.record_handler_all); 
+(function($){
 
-            }); // this.each
+    var GoogleMap = Plugin.extend({
+
+        init: function(options, element) {
+            this._super(options, element);
+
+            /* Member variables */
+            // query status
+            this.received_all = false;
+            this.received_set = false;
+            this.in_set_backlog = [];
+
+            // we keep a couple of global hashes
+            // lat_lon --> { marker, <ul> }
+            // hrn --> { <li>, <input> }
+            this.by_lat_lon = {};
+            this.by_hrn = {};
+
+            /* XXX Events */
+            this.elmt().on('show', this, this.on_show);
+            // TODO in destructor
+            // $(window).unbind('QueryTable');
+
+            var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
+            this.object = query.object;
+
+            var keys = manifold.metadata.get_key(this.object);
+            // 
+            this.key = (keys && keys.length == 1) ? keys[0] : null;
+
+           // xxx temporary hack
+           // as of nov. 28 2013 we have here this.key='urn', but in any place where
+           // the code tries to access record[this.key] the records only have
+           // keys=type,hrn,network_hrn,hostname
+           // so for now we force using hrn instead
+           // as soon as record have their primary key set this line can be removed
+           // see also same hack in querytable
+           this.key= (this.key == 'urn') ? 'hrn' : this.key;
+
+            //// Setup query and record handlers 
+            // this query is the one about the slice itself 
+            // event related to this query will trigger callbacks like on_new_record
+            this.listen_query(options.query_uuid);
+            // this one is the complete list of resources
+            // and will be bound to callbacks like on_all_new_record
+            this.listen_query(options.query_all_uuid, 'all');
+
+            /* GUI setup and event binding */
+            this.initialize_map();
         }, // init
 
-        /**
-         * @brief Plugin destruction
-         * @return : a jQuery collection of objects on which the plugin is
-         *     applied, which allows to maintain chainability of calls
-         */
-        destroy : function( ) {
+        /* PLUGIN EVENTS */
 
-            return this.each(function() {
-                var $this = $(this);
-                var hazelnut = $this.data('Manifold');
+        on_show: function(e) {
+            if (googlemap_debug) messages.debug("googlemap.on_show");
+            var googlemap = e.data;
+            google.maps.event.trigger(googlemap.map, 'resize');
+        }, // on_show
 
-                // Unbind all events using namespacing
-                $(window).unbind(PLUGIN_NAME);
+        /* GUI EVENTS */
 
-                // Remove associated data
-                hazelnut.remove();
-                $this.removeData('Manifold');
-            });
-
-        }, // destroy
-
-        show : function( ) {
-            google.maps.event.trigger(map, 'resize');
-        } // show
-
-    }; // var methods;
-
-    /***************************************************************************
-     * Plugin object
-     ***************************************************************************/
+        /* GUI MANIPULATION */
 
-    function GoogleMaps(options) 
-    {
-        /* member variables */
-        this.options = options;
-
-        // query status
-        this.received_all = false;
-        this.received_set = false;
-        this.in_set_buffer = Array();
-
-        var object = this;
-
-        /**
-         */
-        this.initialize = function() {
-            this.map = null;
+        initialize_map: function() {
             this.markerCluster = null;
-            this.markers = [];
-            this.coords = new Array();
 
-            var myLatlng = new google.maps.LatLng(options.latitude, options.longitude);
+            var center = new google.maps.LatLng(this.options.latitude, this.options.longitude);
             var myOptions = {
-                zoom: options.zoom,
-                center: myLatlng,
-                mapTypeId: google.maps.MapTypeId.ROADMAP
+                zoom: this.options.zoom,
+                center: center,
+                scrollwheel: false,
+                mapTypeId: google.maps.MapTypeId.ROADMAP,
             }
-      
-            this.map = new google.maps.Map(document.getElementById("map"), myOptions);
+            
+            var domid = this.options.plugin_uuid + '--' + 'googlemap';
+            var elmt = document.getElementById(domid);
+            if (googlemap_debug) messages.debug("gmap.initialize_map based on  domid=" + domid + " elmt=" + elmt);
+            this.map = new google.maps.Map(elmt, myOptions);
             this.infowindow = new google.maps.InfoWindow();
-        }
-
-        /**
-         */
-        this.new_record = function(record)
-        {
-
-            // get the coordinates
-            var latitude=get_value(record['latitude']);
-            var longitude=get_value(record['longitude']);
-            var hash = latitude + longitude;
-
-            // check to see if we've seen this hash before
-            if(this.coords[hash] == null) {
-                // get coordinate object
-                var myLatlng = new google.maps.LatLng(latitude, longitude);
-                // store an indicator that we've seen this point before
-                this.coords[hash] = 1;
-            } else {
-                // add some randomness to this point 1500 = 100 meters, 15000 = 10 meters
-                var lat = latitude + (Math.random() -.5) / 1500; 
-                var lng = longitude + (Math.random() -.5) / 1500; 
-
-                // get the coordinate object
-                var myLatlng = new google.maps.LatLng(lat, lng);
-            }
-            // If the node is attached to the slice, action will be Remove; else action will be add to slice
-            if (typeof(record['sliver']) != 'undefined') {
-                data.current_resources.push(record['urn']);
-                action="del";
-                action_class="ui-icon-circle-minus";
-                action_message="Remove from slice";
-            }else{
-                action="add";
-                action_class="ui-icon-circle-plus";
-                action_message="Add to slice";
-            }
-            // XXX not working
-            if (!(record['latitude'])) {
-                return true;
+        }, // initialize_map
+
+        // The function accepts both records and their id
+       // record.key points to the name of the primary key for this record
+       // typically this is 'urn'
+       record_id : function (input) {
+            var id;
+            switch (manifold.get_type(input)) {
+            case TYPE_VALUE:
+               id = input;
+                break;
+            case TYPE_RECORD:
+               if ( ! this.key in input ) return;
+                id = input[this.key];
+                break;
+            default:
+                throw "googlemap.record_id: not implemented";
+                break;
             }
-
-            //jQuery(".map-button").click(button_click);
-            //if(jQuery.inArray(record, rows)>-1){
-                var marker = new google.maps.Marker({
-                    position: myLatlng,
-                    title: get_value(record['hostname']),
-                    // This should be done by the rendering
-                    content: '<p>Agent: ' + get_value(record['ip']) + ' (' + get_value(record['resource_hrn']) + ')<br/>Platform: ' + get_value(record['platform'])+'</p>' +
-                            '<div class="map-button" id="'+action+'/'+get_value(record['resource_hrn'])+'" style="cursor:pointer;">'+
-                            '<span class="ui-icon '+action_class+'" style="clear:both;float:left;"></span>'+action_message+
-                            '</div>'
-                }); 
-
-                this.addInfoWindow(marker, object.map);
-                object.markers.push(marker);
-            //}
-
-        };
-
-        this.addInfoWindow = function(marker, map) {
-            google.maps.event.addListener(marker, 'click', function () {     
-                if(object.infowindow){
-                    object.infowindow.close();
-                }
-                object.infowindow.setContent(marker.content);// = new google.maps.InfoWindow({ content: marker.content });
-                object.infowindow.open(map, marker);
-                // onload of the infowindow on the map, bind a click on a button
-                google.maps.event.addListener(object.infowindow, 'domready', function() {
-                    jQuery('.map-button').unbind('click');
-//                    jQuery(".map-button").click({instance: instance_, infoWindow: object.infowindow}, button_click);                     
-                });
+           return id;
+       },
+
+       // return { marker: gmap_marker, ul : <ul DOM> }
+       create_marker_struct: function (object,lat,lon) {
+           // the DOM fragment
+           var dom = $("<p>").addClass("geo").append(object+"(s)");
+           var ul = $("<ul>").addClass("geo");
+           dom.append(ul);
+           // add a gmap marker to the mix
+           var marker = new google.maps.Marker({
+               position: new google.maps.LatLng(lat, lon),
+                title: object,
+                // gmap can deal with a DOM element but not a jquery object
+                content: dom.get(0),
+            }); 
+           return {marker:marker, ul:ul};
+       },
+
+       // given an input <ul> element, this method inserts a <li> with embedded checkbox 
+       // for displaying/selecting the resource corresponding to the input record
+       // returns the created <input> element for further checkbox manipulation
+       create_record_checkbox: function (record,ul,checked) {
+           var checkbox = $("<input>", {type:'checkbox', checked:checked, class:'geo'});
+           var id=this.record_id(record);
+           // use hrn as far as possible for displaying
+           var label= ('hrn' in record) ? record.hrn : id;
+           ul.append($("<li>").addClass("geo").append(checkbox).
+                     append($("<span>").addClass("geo").append(label)));
+           var googlemap=this;
+           // the callback for when a user clicks
+           // NOTE: this will *not* be called for changes done by program
+           checkbox.change( function (e) {
+               manifold.raise_event (googlemap.options.query_uuid, this.checked ? SET_ADD : SET_REMOVED, id);
+           });
+           return checkbox;
+       },
+           
+       warning: function (record,message) {
+           try {messages.warning (message+" -- hostname="+record.hostname); }
+           catch (err) {messages.warning (message); }
+       },
+           
+       // retrieve DOM checkbox and make sure it is checked/unchecked
+        set_checkbox: function(record, checked) {
+           var id=this.record_id (record);
+           if (! id) { 
+               this.warning (record, "googlemap.set_checkbox: record has no id");
+               return; 
+           }
+           var checkbox = this.by_id [ id ];
+           if (! checkbox ) { 
+               this.warning (record, "googlemap.set_checkbox: checkbox not found");
+               return; 
+           }
+           checkbox.prop('checked',checked);
+        }, // set_checkbox
+
+        // this record is *in* the slice
+        new_record: function(record) {
+                if (googlemap_debug_detailed) messages.debug ("new_record");
+            if (!(record['latitude'])) return false;
+            
+            // get the coordinates
+            var latitude=unfold.get_value(record['latitude']);
+            var longitude=unfold.get_value(record['longitude']);
+            var lat_lon = latitude + longitude;
+
+           // check if we've seen anything at that place already
+           // xxx might make sense to allow for some fuzziness, 
+           // i.e. consider 2 places equal if not further away than 300m or so...
+           var marker_s = this.by_lat_lon [lat_lon];
+           if ( marker_s == null ) {
+               marker_s = this.create_marker_struct (this.object, latitude, longitude);
+               this.by_lat_lon [ lat_lon ] = marker_s;
+               this.arm_marker(marker_s.marker, this.map);
+           }
+           
+           // now add a line for this resource in the marker
+           // xxx should compute checked here ?
+           // this is where the checkbox will be appended
+           var ul=marker_s.ul;
+           var checkbox = this.create_record_checkbox (record, ul, false);
+           var id=this.record_id(record);
+           // used to keep a dict here, but only checkbox is required
+            this.by_id[id] = checkbox;
+        }, // new_record
+
+        arm_marker: function(marker, map) {
+            if (googlemap_debug_detailed) messages.debug ("arm_marker content="+marker.content);
+            var googlemap = this;
+            google.maps.event.addListener(marker, 'click', function () {
+                googlemap.infowindow.close();
+                googlemap.infowindow.setContent(marker.content);
+                googlemap.infowindow.open(map, marker);
             });
-        }
-
-
-        this.set_checkbox = function(record)
-        {
-            // XXX urn should be replaced by the key
-            // XXX we should enforce that both queries have the same key !!
-            //checkbox_id = "#hazelnut-checkbox-" + object.options.plugin_uuid + "-" + unfold.escape_id(record[ELEMENT_KEY].replace(/\\/g, ''))
-            //$(checkbox_id, object.table.fnGetNodes()).attr('checked', true);
-        }
-
-        this.record_handler = function(e, event_type, record)
-        {
-            // elements in set
-            switch(event_type) {
-                case NEW_RECORD:
-                    /* NOTE in fact we are doing a join here */
-                    if (object.received_all)
-                        // update checkbox for record
-                        object.set_checkbox(record);
-                    else
-                        // store for later update of checkboxes
-                        object.in_set_buffer.push(record);
-                    break;
-                case CLEAR_RECORDS:
-                    // nothing to do here
-                    break;
-                case IN_PROGRESS:
-                    manifold.spin($(this));
-                    break;
-                case DONE:
-                    if (object.received_all)
-                        manifold.spin($(this), false);
-                    object.received_set = true;
-                    break;
+        }, // arm_marker
+
+        /*************************** QUERY HANDLER ****************************/
+
+        /*************************** RECORD HANDLER ***************************/
+        on_new_record: function(record) {
+            if (googlemap_debug_detailed) messages.debug("on_new_record");
+            if (this.received_all)
+                // update checkbox for record
+                this.set_checkbox(record, true);
+            else
+                // store for later update of checkboxes
+                this.in_set_backlog.push(record);
+        },
+
+        on_clear_records: function(record) {
+            if (googlemap_debug_detailed) messages.debug("on_clear_records");
+        },
+
+        // Could be the default in parent
+        on_query_in_progress: function() {
+            if (googlemap_debug) messages.debug("on_query_in_progress (spinning)");
+            this.spin();
+        },
+
+        on_query_done: function() {
+            if (googlemap_debug) messages.debug("on_query_done");            
+            if (this.received_all) {
+                this.unspin();
             }
-        };
-
-        this.record_handler_all = function(e, event_type, record)
-        {
-            // all elements
-            switch(event_type) {
-                case NEW_RECORD:
-                    // Add the record to the table
-                    object.new_record(record);
-                    break;
-                case CLEAR_RECORDS:
-                    // object.table.fnClearTable();
+            this.received_set = true;
+        },
+
+        on_field_state_changed: function(data) {
+            if (googlemap_debug_detailed) messages.debug("on_field_state_changed");            
+            switch(data.request) {
+                case FIELD_REQUEST_ADD:
+                case FIELD_REQUEST_ADD_RESET:
+                    this.set_checkbox(data.value, true);
                     break;
-                case IN_PROGRESS:
-                    manifold.spin($(this));
+                case FIELD_REQUEST_REMOVE:
+                case FIELD_REQUEST_REMOVE_RESET:
+                    this.set_checkbox(data.value, false);
                     break;
-                case DONE:
-
-                    // MarkerClusterer
-                    object.markerCluster = new MarkerClusterer(object.map, object.markers, {zoomOnClick: false});
-                    google.maps.event.addListener(object.markerCluster, "clusterclick", function (cluster) {
-                        var markers = cluster.getMarkers();
-                        var bounds  = new google.maps.LatLngBounds();
-                      /* 
-                      * date: 24/05/2012
-                      * author: lbaron
-                      * Firefox JS Error - replaced $.each by JQuery.each
-                      */                  
-                      jQuery.each(markers, function(i, marker){
-                          bounds.extend(marker.getPosition()); 
-                      });
-
-                      //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
-                      object.map.fitBounds(bounds);
-                    });
-
-                    if (object.received_set) {
-                        /* XXX needed ? XXX We uncheck all checkboxes ... */
-                        $("[id^='datatables-checkbox-" + object.options.plugin_uuid +"']").attr('checked', false);
-
-                        /* ... and check the ones specified in the resource list */
-                        $.each(object.in_set_buffer, function(i, record) {
-                            object.set_checkbox(record);
-                        });
-
-                        manifold.spin($(this), false);
-                    }
-                    object.received_all = true;
+                default:
                     break;
             }
-        };
-
-
-        this.query_handler = function(e, event_type, query)
-        {
-            // This replaces the complex set_query function
-            // The plugin does not need to remember the query anymore
-            switch(event_type) {
-                // Filters
-                case FILTER_ADDED:
-                case FILTER_REMOVED:
-                case CLEAR_FILTERS:
-                    break;
+        },
+
+
+        // all : this 
+
+        on_all_new_record: function(record) {
+            if (googlemap_debug_detailed) messages.debug("on_all_new_record");
+            this.new_record(record);
+        },
+
+        on_all_clear_records: function() {
+            if (googlemap_debug) messages.debug("on_all_clear_records");            
+        },
+
+        on_all_query_in_progress: function() {
+            if (googlemap_debug) messages.debug("on_all_query_in_progress (spinning)");
+            // XXX parent
+            this.spin();
+        },
+
+        on_all_query_done: function() {
+            if (googlemap_debug) messages.debug("on_all_query_done");
+
+            // MarkerClusterer
+            var markers = [];
+            $.each(this.by_lat_lon, function (k, s) { markers.push(s.marker); });
+            this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
+            google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
+                var cluster_markers = cluster.getMarkers();
+                var bounds  = new google.maps.LatLngBounds();
+                $.each(cluster_markers, function(i, marker){
+                    bounds.extend(marker.getPosition()); 
+                });
+                //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
+                this.map.fitBounds(bounds);
+            });
 
-                // Fields
-                /* Hide/unhide columns to match added/removed fields */
-                case FIELD_ADDED:
-                    break;
-                case FIELD_REMOVED:
-                    break;
-                case CLEAR_FIELDS:
-                    alert('GoogleMaps::clear_fields() not implemented');
-                    break;
-            } // switch
+            var googlemap = this;
+            if (this.received_set) {
+                /* ... and check the ones specified in the resource list */
+                $.each(this.in_set_backlog, function(i, record) {
+                    googlemap.set_checkbox(record, true);
+                });
+                // reset 
+                googlemap.in_set_backlog = [];
 
+                if (googlemap_debug) messages.debug("unspinning");
+                this.unspin();
+            }
+            this.received_all = true;
 
-        }
+        } // on_all_query_done
+    });
+        /************************** PRIVATE METHODS ***************************/
 
-        function button_click(e){
-            var op_value=this.id.split("/");
-            if(op_value.length>0){
-                var value = op_value[1];
-                manifold.raise_event(object.options.query_uuid, (op_value[0] == 'add')?SET_ADD:SET_REMOVED, value);
-            }
-        } // function button_click()
-    } 
-
-    // clear and replace
-//                jQuery.each(data.results, function(i, row){
-//                    jQuery.each(query.filter, function (idx, filter){
-//                        if(get_value(row[filter[0]])==filter[2]){
-//                            rows.push(row);
-//                        }
-//                    });
-//                });
-//                data.markerCluster=[];
-//                data.markers=[];
-//                var myLatlng = new google.maps.LatLng(34.397, 150.644);
-//                var myOptions = {
-//                    zoom: 2,
-//                    center: myLatlng,
-//                    mapTypeId: google.maps.MapTypeId.ROADMAP
-//                }
-//                map = new google.maps.Map(jQuery('#map')[0],myOptions);
-//                data.map=map;
-//                //map.clearMarkers();
-//                update_map(e, rows);
-//            }
-//        }
-
-})( jQuery );
+    $.plugin('GoogleMap', GoogleMap);
+
+})(jQuery);