<Module>
  <ModulePrefs title="Latitudymap - Shows all users on a map" height="400">
   <Require feature="rpc"/>
  </ModulePrefs>

  <Content type="html">
 <![CDATA[



  <script type="text/javascript"
      src="http://wave-api.appspot.com/public/wave.js"></script>
  <script type="text/javascript" 
  	  src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key="></script>
  <script type="text/javascript"
  	  src="http://www.google.com/jsapi?key=internal"></script>	  
 
 	
 <script type="text/javascript">	
 	// ############################### widget js START #############
 
   var glatitudymap;
 
 	function userbuttonClicked() {
        // Currently get always returns a string:
        var participants = wave.getParticipants();
        var plength = participants.length;
        var randomnum = Math.floor(Math.random()*plength);
        
        p = participants[randomnum];

        wave.getState().submitDelta({'membername': p.getDisplayName()});
        wave.getState().submitDelta({'memberimage': p.getThumbnailUrl()});
        
        // defining / storing key,value pair inside the current wave...
        var winnercount = parseInt(wave.getState().get('winnercount', '0'));
        wave.getState().submitDelta({'winnercount': winnercount + 1});
       
        
      }
      
 	 /*
 	  *  store user location inside the waves state ...
 	  *  
 	  * */
      function updateUserLocation(lat, lon, placeName) {
      	// Get the participant whose client renders this gadget.
     		var user = wave.getViewer().getId();
     		var state = wave.getState();
     		
     		if (user === 'null') {
     			user = "unknown";
     		}
     		
     		
     		// creating propertyid's in a separate variable
     		var pidUserLat = user + '_lat';
     		var pidUserLng = user + '_lon';
     		var pidUserPlace = user + '_place';
     		var pidUserCount = user + '_count';
     		var locationChangCounter = parseInt(state.get('locChangeCounter', '0'));
          
         // Updates the state delta. This is an asynchronous call that will update the state and not take effect immediately. 
         //Creating any key with a null value will attempt to delete the key.
         
           var delta = {};
            delta[pidUserLat] = lat;
            delta[pidUserLng] = lon;
            delta[pidUserPlace] = placeName;
            delta[pidUserCount] = 0;
            delta['locChangeCounter'] = locationChangCounter + 1;
            
            state.submitDelta(delta);
          
      }
      
      /*
       * retrieve all participants lat,lon pairs and update the map
       * this is being called onStateChanged events
       * 
       * */
      function updateLocationsOnMap() {
    	  
        var participants = wave.getParticipants();
        var plength = participants.length;
        
        var state = wave.getState();
     
        // variables to hold latitude + longitude
        var curLat;
        var curLon;
        var curPlace;
        
        // property id ( key ) 
         var curPidLat = "id_lat";
         var curPidLon = "id_lon";
         var curPidPlace = "id_place";
         var userCounter = 0; // count how many times the user updated his/her location
        
        
       // var userLocationListHTML = "";
        var html = "";
        
        var curPoint;
        
      for (i=0; i<plength; i++) {
        
        if ( participants[i].getId()  === 'latitudymap@appspot.com' ) {
        
             var randomnum = parseInt(Math.random()*2);
           
           if (randomnum === 0) {
	           curLat = 37.615223;
	           curLon = 122.389979;  // SFO
	           curPlace = " is going on vacation";
           } else {
           	   curLat = 37.320052;
	           curLon = 121.877636;  // San Jose
	           curPlace = " is in San Jose";
	           
           }
  
        } else {
       
	         curPidLat = participants[i].getId() +'_lat';
	         curPidLon = participants[i].getId() +'_lon';
	         curPidPlace = participants[i].getId() +'_place';
	         userCounterPid = participants[i].getId() + '_count';
	         
	        
	         curLat = parseFloat(state.get(curPidLat));
	         curLon = parseFloat(state.get(curPidLon));
	         curPlace = state.get(curPidPlace);
	         userCounter = parseInt(state.get(userCounterPid));
	      }   
	         //alert (i+ " " + participants[i].getId() + "\n" +
	        	//	 curPidLat + ": " +curLat + "\n " + curPidLon + ": " + curLon + "\n"      		 
	         //);
	         
	         // update the map now.....
	         if ( !glatitudymap.llmarkers ) {	 
	        	  glatitudymap.llmarkers = {}; 
	        	  glatitudymap.llbounds = new GLatLngBounds();

	         } 

	          html ='<img src="'+ participants[i].getThumbnailUrl() +'" width="50" height="50"></img><br />' + participants[i].getDisplayName() +'  <b>'+curPlace+'</b>';
      
              // check if marker exists, if so remove from map before adding again...
              if ( glatitudymap.llmarkers[ participants[i].getId() ] ) {
                 glatitudymap.removeOverlay( glatitudymap.llmarkers[ participants[i].getId() ]  );
              }
              
             curPoint = new GLatLng(curLat,curLon);
	         glatitudymap.llmarkers[ participants[i].getId() ] = createMarker(curPoint, html, participants[i].getThumbnailUrl());
	         glatitudymap.llbounds.extend(curPoint);
	         glatitudymap.addOverlay(   glatitudymap.llmarkers[participants[i].getId()] );
	            
        
      
     }
     }


      function stateUpdated() {
      
      
        if(!wave.getState().get('locChangeCounter')) {
          return;
        } 
        else {
         updateLocationsOnMap();
        
        	var state = wave.getState();
          
       // document.getElementById('userCount').innerHTML =
       //     'Winner # ' + state.get('winnercount') + ' is: ' + state.get('membername') + 'list:' + state.get('userLocList');
            
       // document.getElementById('userWinner').innerHTML = 
       // 	'<img src="'< + state.get('memberimage') + '" width="50" height="50">';
       
      // document.getElementById('userLocationList').innerHTML = state.get('userList');
       
        }
        
         
      }
      
      //------------
     
      function initializeMap() {
        if (GBrowserIsCompatible()) {
          glatitudymap = new GMap2(document.getElementById("latitudymap_canvas"));
        //  glatitudymap.setCenter(new GLatLng(37.4419, -122.1419), 13);  
        glatitudymap.setCenter(new GLatLng(37.52483011815223, -121.755981445312), 8);
          glatitudymap.addControl(new GSmallMapControl());
          glatitudymap.addControl(new GNavLabelControl());
          
          glatitudymap.disableDoubleClickZoom();
         
          
          GEvent.addListener(glatitudymap,"dblclick", function(overlay, latlng) {     
			  if (latlng) { 
			    //var myHtml = "The GPoint value is: " + glatitudymap.fromLatLngToDivPixel(latlng) + " at zoom level " + glatitudymap.getZoom();
			    //glatitudymap.openInfoWindow(latlng, myHtml);
			    updateUserLocation(latlng.lat(), latlng.lng(), " ");
			  }
			});
          
          
          
          
          
         // glatitudymap.setUIToDefault();
        }
        
        // now that we have a map try to get user location data and plot it on the map ...
      //  wave.getState().submitDelta({'userLocList': 'testList'}); // this is called too early no state available
      //  updateLocationsOnMap();
        
      }
      
      
  /* BEGIN Google trying to determine client location ------------------------------------------------------------------  */
  	setDefaultLocation_ = function() {
  	  this.currentState_ = this.options_.startingState;
  	  if (google.loader.ClientLocation &&
  	      google.loader.ClientLocation.address.country_code == "US" &&
  	      google.loader.ClientLocation.address.region) {
  	    var state = google.loader.ClientLocation.address.region.toUpperCase();
  	    var lat = google.loader.ClientLocation.latitude;
  	    var lng = google.loader.ClientLocation.longitude;
  	    
  	    if (InTheNews.stateNames[state]) {
  	      this.currentState_ = state;
  	    }
  	  }
  	  this.currentCountry_ = "US";
  	}
  /* END Google trying to determine client location --------------------------------------------------------------------  */
   
   function getClientLocation() { 
  	if (google.loader.ClientLocation.address.city != null && google.loader.ClientLocation.address.region != null )
       return google.loader.ClientLocation.address.city +', ' +google.loader.ClientLocation.address.region;
  	}
  	
  	 function createMarker(point,html, thumbUrl) {
  	 
  	 var myIcon = new GIcon();
		myIcon.image = thumbUrl;
		myIcon.iconSize = new GSize(12,20);
		myIcon.infoWindowAnchor = new GPoint(6,0);
		//myIcon.imageMap = [0,0,12,0,12,12,0,12];
  	 
  	 
          var marker = new GMarker(point, {draggable: true});
          GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html);
          });

          // The new marker "mouseover" listener        
          GEvent.addListener(marker,"mouseover", function() {
            //marker.openInfoWindowHtml(html);
          });        
          
          GEvent.addListener(marker, "dragend", function() {
            updateUserLocation(marker.getLatLng().lat(), marker.getLatLng().lng(), " dragged me here");
            //marker.openInfoWindowHtml("Just bouncing along...");
          });
          
          
          return marker;
        }
  	
  	
  	function setUserLocationManualButtonClicked() {
  	  var address = document.getElementById('uplaceName').value;
  	  
  	  
  	  var geocoder = new GClientGeocoder();
  	  
		  geocoder.getLatLng(
		    address,
		    function(point) {
		      if (!point) {
		        alert(address + " not found");
		      } else {
		        updateUserLocation(point.lat(), point.lng(), address);
		        glatitudymap.setCenter(point);
		      }
		    }
		  );

  	}
   
      
      function setUserLocationButtonClicked() {

    	  
    	  // obtain latitude & longitude based on IP address
    	  var lat = google.loader.ClientLocation.latitude;
    	  var lon = google.loader.ClientLocation.longitude;
    	  
    	  
          
        //  var latlng = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
        //  var html ='<img src="'+wave.getState().get('memberimage')+'" width="50" height="50"></img>' + wave.getViewer().getDisplayName() +' is in <br/><b>'+getClientLocation()+'</b>';
        //  glatitudymap.addOverlay(createMarker(latlng, html));
         // glatitudymap.setCenter(latlng);
          
          updateUserLocation(lat, lon, getClientLocation());
          glatitudymap.setCenter(new GLatLng(lat, lon));
         
          
      }
      
      function setSFOButtonClicked() {
      
      var latlngSFO = new GLatLng(40.6424805, -73.788071);
      
       var html ='<img src="'+wave.getState().get('memberimage')+'" width="50" height="50"></img>' + wave.getViewer().getDisplayName() +' is in <br/><b>SFO Airport</b>';
         glatitudymap.addOverlay(createMarker(latlngSFO, html));
          glatitudymap.setCenter(latlngSFO);
          
          updateUserLocation(40.6424805, -73.788071); // put the key,value pair into the wave state
          updateLocationsOnMap();                    // read all users, key,value pairs to update the map
      
      
      }
      
      //-----------
      
      
      function main() {
        if (wave && wave.isInWaveContainer()) {
          wave.setStateCallback(stateUpdated);
          initializeMap();
          
          //do no try to set the users location on startup...

        }
      }
      gadgets.util.registerOnLoadHandler(main);
 	
 	//############################### widget js END ################ 
</script>  	  


  <input type="text" name="uplaceName" id="uplaceName" value=""></input>
  <button id="setUserLocationManual" style="font:bold .9em Arial, Helvetica, sans-serif; color:#FFFFFF; background-color:#00CC99" onclick="setUserLocationManualButtonClicked()">Change Location</button>
  <button id="setUserLocation" style="font:bold .9em Arial, Helvetica, sans-serif; color:#FFFFFF; background-color:#00CC99" onclick="setUserLocationButtonClicked()">IP Location</button>
  <table border="0">
   <tr>
     <td><div id="userWinner"></div></td>
     <td><div id="userLocationList"></div></td>
     </tr>
     <tr>
     <td><div id="usercount"></div></td>
     <td></td>
   </tr>
   </table>
  <div id="latitudymap_canvas" style="width:*; height:450px"></div>

 ]]>
  </Content>
</Module>

