﻿<?xml version="1.0" encoding="UTF-8"?>
<Module> 
<!--
Copyright 2009 Google Inc.
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
     http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Danish version by Søren Johannessen http://www.microformats.dk
--> 
<!--
thumbnail="http://code.google.com/apis/kml/embed/res/embedkmlgadget-thumb.png"
screenshot="http://code.google.com/apis/kml/embed/res/embedkmlgadget-screen.png"
description="Embed a KML file in your page using Google Earth or Google Maps!"
--> 
  <ModulePrefs title="Dansk Google Earth Wave" directory_title="Dansk Earth Wave" author="Søren Johannessen" author_email="soren.johannessen+danskearthwavegadget@gmail.com" author_affiliation="Private" author_link="http://www.microformats.dk/" author_location="Copenhagen, Denmark" width="600" height="500"> 
    <Locale lang="da" country="dk"></Locale> 
    <Require feature="minimessage"></Require> 
    <Require feature="wave"></Require> 
  </ModulePrefs> 
  
  <UserPref name="show_buildings" display_name="Show buildings" default_value="1" datatype="bool"></UserPref> 
  <UserPref name="show_terrain" display_name="Show 3D terrain" default_value="1" datatype="bool"></UserPref> 
  <UserPref name="show_roads" display_name="Show roads" default_value="1" datatype="bool"></UserPref> 
  <UserPref name="show_borders" display_name="Show borders and labels" default_value="0" datatype="bool"></UserPref> 
  <UserPref name="sphere" display_name="Sphere" default_value="earth" datatype="enum"> 
    <EnumValue value="earth" display_value="Earth"></EnumValue> 
    <EnumValue value="sky" display_value="Sky"></EnumValue> 
    <EnumValue value="moon" display_value="Moon"></EnumValue> 
    <EnumValue value="mars" display_value="Mars"></EnumValue> 
  </UserPref> 
  
  <Content type="html"><![CDATA[ 
<script type="text/javascript" src="http://www.google.com/jsapi?hl=en&key=ABQIAAAAKkfkHb2nXsD0o1OX2TbdkRTZdFmpiU8vv3PBIA-hr88t-5BzzxQjEeEmKaZUy66ADwTlY8x2M14hHg"></script> 
<script type="text/javascript" src="http://earth-api-samples.googlecode.com/svn/trunk/demos/geolocation/location.js"></script> 
<script type="text/javascript" src="http://earth-api-samples.googlecode.com/svn/trunk/demos/geolocation/gears_init.js"></script> 
<script type="text/javascript" src="http://earth-api-utility-library.googlecode.com/svn/tags/extensions-0.2/dist/extensions.js"></script> 
<script type="text/javascript"> 
  google.load('earth', '1');
  google.load('maps', '2');
 
  var ge = null;
  var gex = null;
  var prefs = new gadgets.Prefs();
  var mm = new gadgets.MiniMessage();
  
  var waveState = null;
  var participantMetaById = {};
  
  var initialZoomComplete = false;
 
  /**
   * Instantiate the gadget.
   */
  function initGadget() {
    wave.setStateCallback(waveStateCallback);
    wave.setParticipantCallback(waveParticipantCallback);
    
    createGadgetUI();
  }
  
  function waveStateCallback() {
    waveState = wave.getState();
    if (!ge || !waveState)
      return;
    
    var locationsFound = 0;
    var keys = waveState.getKeys();
    for (var i = 0; i < keys.length; i++) {
      var km = keys[i].match(/^location-(.*)/);
      if (km[1]) {
        locationsFound++;
        
        var id = km[1];
        var participant = wave.getParticipantById(id);
        if (!(id in participantMetaById))
          participantMetaById[id] = {};
        
        var participantMeta = participantMetaById[id];
        
        var latLonStrArr = waveState.get(keys[i]).split(',');
        participantMeta.location = new geo.Point(
            parseFloat(latLonStrArr[0]),
            parseFloat(latLonStrArr[1]));
 
        if (participantMeta.placemark)
          gex.dom.removeObject(participantMeta.placemark);
 
        participantMeta.placemark = gex.dom.addPointPlacemark({
          point: participantMeta.location,
          name: (participant ? participant.getDisplayName()
                             : 'Unknown Participant'),
          style: {
            label: '#F0E68C',
            icon: {
              color: '#f80',
              stockIcon: 'shapes/target'
            }
          }
        });
        
        if (id == wave.getViewer().getId()) {
          document.getElementById('my-location-button').disabled = '';
        }
      }
    }
    
    document.getElementById('num-locations').innerHTML =
        locationsFound + ' Deltageres lokalitet';
    
    if (!initialZoomComplete && locationsFound) {
      initialZoomComplete = true;
      zoomToParticipants();
    }
    
    trySetupLocationWatcher();
  }
  
  function waveParticipantCallback() {
    var participants = wave.getParticipants();
    if (!ge || !participants)
      return;
    
    waveStateCallback(); // try updating state
    trySetupLocationWatcher();
  }
  
  function trySetupLocationWatcher() {
    if (wave.getState() && wave.getParticipants()) {
      window.trySetupLocationWatcher = function(){};
      
      watchLocation(locationWatcher, function(error) {
        mm.createDismissibleMessage('Kunne ikke finde din lokalitet: ' + error);
      }, false);
    }
  }
  
  /**
   * Create the gadget UI.
   */
  function createGadgetUI() {
    // Determine which sphere to create (earth/sky/moon/mars).
    var createOptions = {};
    var sphere = prefs.getString('sphere') || 'earth';
 
    if (sphere == 'mars' || sphere == 'moon')
      createOptions = { database: 'http://khmdb.google.com/?db=' + sphere };
 
    google.earth.createInstance('earth', function(pluginInstance) {
      ge = pluginInstance;
      gex = new GEarthExtensions(ge);
      
      if (sphere == 'sky')
        ge.getOptions().setMapType(ge.MAP_TYPE_SKY);      
      
      ge.getWindow().setVisibility(true);
 
      // Set options.
      ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
      ge.getOptions().setStatusBarVisibility(true);

 
      if (sphere == 'earth') {
        ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS,
            prefs.getBool('show_buildings'));
 
        ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN,
            prefs.getBool('show_terrain'));
 
        ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS,
            prefs.getBool('show_roads'));
 
        ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS,
            prefs.getBool('show_borders'));
      }
      
      waveStateCallback();
      waveParticipantCallback();
    }, function(error) {
      mm.createDismissibleMessage('Error loading GEPlugin: ' + error);
    }, createOptions);
    
    document.getElementById('zoom-participants-button').addEventListener(
        'click', function() {
          zoomToParticipants();
        }, false);
 
    document.getElementById('my-location-button').addEventListener(
        'click', function() {
          var viewer = participantMetaById[wave.getViewer().getId()];
          if (!viewer || !viewer.placemark)
            return;
 
          gex.util.flyToObject(viewer.placemark);
        }, false);
  }
  
  /**
   * Callback function for when the user's location changes.
   */
  function locationWatcher(coords) {
    var viewer = wave.getViewer();
 
    var stateDelta = {};
    stateDelta['location-' + viewer.getId()] =
        coords.latitude + ',' + coords.longitude;
    wave.getState().submitDelta(stateDelta);
  }
  
  function zoomToParticipants() {
    var bounds = new geo.Bounds();
    for (var id in participantMetaById) {
      var participantMeta = participantMetaById[id];
      bounds.extend(participantMeta.location);
    }
    
    var aspectRatio = document.getElementById('earth').offsetWidth / 
                      document.getElementById('earth').offsetHeight;
    gex.view.setToBoundsView(bounds,
        {aspectRatio: aspectRatio});
  }
  
  google.setOnLoadCallback(initGadget);
</script> 
<style type="text/css"> 
  #container {
    height: 100%;
    position: relative;
  }
  
  #earth {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    bottom: 30px;
  }
  
  #toolbar {
    position: absolute;
    bottom: 0;
    height: 30px;
  }
</style> 
<div id="container"> 
  <div id="earth"></div> 
  <div id="toolbar"> 
    <input id="zoom-participants-button" type="button" value="Oversigt over alle"/> 
    <input id="my-location-button" type="button" value="Min lokalitet" disabled="disabled"/> 
    <span id="num-locations"></span> 
  </div> 
</div> 
]]></Content> 
</Module>

