// $Id$

/**
 * Google Maps Script for the Knowledgemapping module.
 * @file
 */

//Creating the Knowledgemapping namespace. 
var Knowledgemapping = Knowledgemapping || {};

/**
 * Sets up the map and all its navigation using Drupal's behaviour functionality which is invoked when the DOM is ready for manipulation.
 */ 
Drupal.behaviors.setupMap = function () {
  if ($('#map').length == 1){
    var basepath = $('#basepath').val();
    var path = $('#path').val();
    var mapID = $('#mapID').val();
	
	//First we create the navbar. This will only happen if the navbar div is set.
    if ($('#mapnav').length == 1){
	  Knowledgemapping.setUpNavbar();
	}
	
	//Then we check if the browser is compatible 
	if (GBrowserIsCompatible()) {
      //...and create the default map with 	default user interface
      var map = new GMap2(document.getElementById("map"));
	  var defaultUI = map.getDefaultUI();  
      map.setUI(defaultUI);
	  
	  $('#content').append(Drupal.theme('caption', basepath));
	  var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(5,35));
      pos.apply(document.getElementById("caption"));
      map.getContainer().appendChild(document.getElementById("caption"));
	  
	  //If the user uses a IE browser older than IE8 a message is displayed which tells him that there can be problems with the map vizualisation.
	  if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
        var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ieversion < 8){
	      var error = Drupal.theme('errorBox', Drupal.t("You use an Internet Explorer which is older than version 8. There can be problems with the map widget if it is displayed with older versions of Internet Explorer. It also takes a lot longer to load the points due to bad JavaScript support. We recommend an update to Internet Explorer version 8 to ensure a flawless experience."));
	      $(error).appendTo('body').fadeIn('slow');
	      $('#ok-error').click(Knowledgemapping.removeBox);
	      $('body').append('<div id="dark-background"></div>');   
	    }
	  }
	  
	  //Click event handler for displaying the overview map.
	  //If the map does not exist it is created. From then on we just hide or show.
      $('#gm-settings1').click(function () {
        var checked = this.checked;
        if (checked) {
	      if($('#map_overview').length == 0) {
            var overviewControl = new GOverviewMapControl(new GSize(150,150));
		    map.addControl(overviewControl);
	      } else {
		    $('#map_overview').show();
	      }
	    } else {
          $('#map_overview').hide();
	    }
      });
	  
	  //Click event handler for switching the display mode.
	  $('input[name="display-settings"]').click(function(){
	    //If the Google Maps display is activated we enable the sidebar and tooltip options.
	    if ($('input[name="display-settings"]:checked').val() == '0') {
	      $('input[name="gm-settings"]').removeAttr('disabled');
		  $('#caption').hide();
	    } else if ($('input[name="display-settings"]:checked').val() == '1') {
		  $('input[name="gm-settings"]').removeAttr('disabled');
		  $('#caption').show();
        } else {
		  //If heatmap view is enabled we hide the sidebar and disable sidebar and tooltips
		  if($('#gm-settings0').attr('checked')){
		    $('#map').removeClass('with-sidebar').addClass('without-sidebar');
            $('#map-sidebar').fadeOut();
			$('#gm-settings0').removeAttr('checked');
		  }
	      $('#gm-settings0').attr('disabled', 'true');
		  $('#gm-settings2').attr('disabled', 'true');
		  $('#caption').hide();
	    }
		//Then we reset the map.
        setMap();
      });
	  
	  //If "Tooltips" is clicked we just call the setMap function.
	  $('#gm-settings2').click(function () {
        setMap(); 
      });
	
	  //A variable which contains all the sidebar entries.
      var side_bar_html = $('<ul class="sidebar-list"></ul>').appendTo('#map-sidebar');
	  
	  //Create some custom circle icons
	  var circle5Icon = new GIcon();
      circle5Icon.image = basepath + "/images/circle5.png";
      circle5Icon.iconSize = new GSize(9, 9);
      circle5Icon.iconAnchor = new GPoint(5, 5);
      circle5Icon.infoWindowAnchor = new GPoint(5, 5);
	  circle5Icon.transparent = "/images/circle5trans.png";
	  
	  var circle10Icon = new GIcon();
      circle10Icon.image = basepath + "/images/circle10.png";
      circle10Icon.iconSize = new GSize(15, 15);
      circle10Icon.iconAnchor = new GPoint(8, 8);
      circle10Icon.infoWindowAnchor = new GPoint(8, 8);
	  circle10Icon.transparent = "/images/circle10trans.png";
	  
	  var circle15Icon = new GIcon();
      circle15Icon.image = basepath + "/images/circle15.png";
      circle15Icon.iconSize = new GSize(21, 21);
      circle15Icon.iconAnchor = new GPoint(11, 11);
      circle15Icon.infoWindowAnchor = new GPoint(11, 11);
	  circle15Icon.transparent = "/images/circle15trans.png";
	  
	  var circle25Icon = new GIcon();
      circle25Icon.image = basepath + "/images/circle25.png";
      circle25Icon.iconSize = new GSize(25, 25);
      circle25Icon.iconAnchor = new GPoint(13, 13);
      circle25Icon.infoWindowAnchor = new GPoint(13, 13);
	  circle25Icon.transparent = "/images/circle25trans.png";
	  
	  var circleMoreThan25Icon = new GIcon();
      circleMoreThan25Icon.image = basepath + "/images/circleMoreThan25.png";
      circleMoreThan25Icon.iconSize = new GSize(29, 29);
      circleMoreThan25Icon.iconAnchor = new GPoint(15, 15);
      circleMoreThan25Icon.infoWindowAnchor = new GPoint(15, 15);
	  circleMoreThan25Icon.transparent = "/images/circleMoreThan25trans.png";

	
      //A function to create the marker and set up the event window. Only if show is true, the tooltips are displayed.
      function createMarker(point,name,html,show,count) {
		if(count) {
		  if(count <= 5) {
		    var marker = new GMarker(point, circle5Icon);
		  } else if (count <= 10) {
		    var marker = new GMarker(point, circle10Icon);
		  } else if (count <= 15) {
		    var marker = new GMarker(point, circle15Icon);
		  } else if (count <= 25) {
		    var marker = new GMarker(point, circle25Icon);
		  } else if (count > 25) {
		    var marker = new GMarker(point, circleMoreThan25Icon);
		  } 
        } else {
		  var marker = new GMarker(point);
		}
	    if (show){
		  //The click event for the marker which triggers the tooltip.
          GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(html);
          });      
          //Add a line to the side_bar html. A click on this entry will also trigger the tooltip.
	      $('<li class="sidebar-entry">' + name + '</li>').appendTo(side_bar_html).click(function() {
	        marker.openInfoWindowHtml(html);
	      });
	    } else {
		  //If tooltips are disabled the center of the map is set to the point of the marker.
	      $('<li class="sidebar-entry">' + name + '</li>').appendTo(side_bar_html).click(function() {
	        map.setCenter(point);
	      });
	    }
     
        return marker;
      }
      
	  //The most important function.
	  //Setting the map to display everything in the way the user wants it.
	  function setMap() {
	    //If there are no markers we just return without doing anything.
	    if (typeof markers == 'undefined') {
		  return;
		}
		
        //First we clear all the old stuff.		
		map.clearOverlays();	    
	    side_bar_html.empty();
	    
		//Then we distinguish the users who are allowed to save from those who are not.
		if (nosave) {//case: not allowed to save
		  try {
		    //Create the Heatmap object.
            var myHM = new GEOHeatmap();
            myHM.Init($('#map').width(), 550); // Must be same as map size, or same ratio

            var data = new Array(); //Array which will contain the points in case we build a heatmap.
		    
			//First we check which display mode is selected.
	        if (google == true) {//case: Google Maps Display
			  //Each marker is put onto the map. The markers have been loaded into the markers object by the getMap function.
			  $.each(markers, function () {
		        var point = new GLatLng(this.breite, this.laenge);
				//We use the helper function to create the markers.
                var mapmarker = createMarker(point, this.name, Drupal.theme('mapTooltip', this.nid, this.name, this.leiter, this.website, this.artefakte), tooltips);
                map.addOverlay(mapmarker);
              });
		    } else if (circles == true) {//case: Circles 
			  //Each marker is put onto the map. The markers have been loaded into the markers object by the getMap function.
			  $.each(markers, function () {
		        var point = new GLatLng(this.breite, this.laenge);
				//We use the helper function to create the markers.
                var mapmarker = createMarker(point, this.name, Drupal.theme('mapTooltip', this.nid, this.name, this.leiter, this.website, this.artefakte), tooltips,this.count);
                map.addOverlay(mapmarker);
              });
		    } else {//case: Heatmap display
		      var i = 1;
			  //We put each marker into the data array. One heat point on the map consists of three sequent values in the array.  
		      $.each(markers, function () {
			    if(i++ < 200) {  
		          data.push(this.breite); //The latitude
			      data.push(this.laenge); //The longitude
			      data.push(this.count); //The heat value at this point
			    }	
		      });
			  
			  //As the free version of the heatmap API officially supports only 100 points we display a warning if there are too many points. 
			  //Because tests with up to 200 points were successful we only show the warning when 200 points are created.
		      if (i > 200) {
		        var error = Drupal.theme('errorBox', Drupal.t("Your map contains more than the currently supported amount of heat points. Only a selection of points is displayed."));
	            $(error).appendTo('body').fadeIn('slow');
	            $('#ok-error').click(Knowledgemapping.removeBox);
	            $('body').append('<div id="dark-background"></div>');
		      } 
	        }
		    
            //We attach the data array to the heatmap class.		
		    myHM.SetData(data);
            myHM.SetBoost(0.4); // Optional parameter of the HeatmapAPI, see HeatmapAPI documentation
            myHM.SetDecay(0); // Optional parameter of the HeatmapAPI, see HeatmapAPI documentation
            var preUrl = myHM.GetURL();

            //Now render in our Google Map
            var heatmapOverlay = new HMGoogleOverlay(preUrl);
            map.addOverlay(heatmapOverlay); //Adding the heatmap overlay to the map.
          } catch(e) {
			if (heat == true) {
			  var error = Drupal.theme('errorBox', Drupal.t("Due to technical problems with the HeatMapAPI service heatmap view is temporarily unavailable. We apologize for the inconvenience caused. Please check back later!"));		  
	          $(error).appendTo('body').fadeIn('slow');
			  $('#ok-error').click(Knowledgemapping.removeBox);
			  $('body').append('<div id="dark-background"></div>');
			  $('#display-settings0').attr('checked', 'true');
			  $('#display-settings2').attr('disabled', 'true');
			  $('input[name="gm-settings"]').removeAttr('disabled');
			  google = true;
			}
			
  		    $.each(markers, function () {
		      var point = new GLatLng(this.breite, this.laenge);
              var mapmarker = createMarker(point, this.name, Drupal.theme('mapTooltip', this.nid, this.name, this.leiter, this.website, this.artefakte), tooltips);
              map.addOverlay(mapmarker);
            });
	      }
		} else {//case: user is allowed to save and has a navbar	  
          try {
		    //Basically this is the same as before. The only difference is that we use the state of the tooltips checkbox and the display mode radios to determine which setup is needed.
            var myHM = new GEOHeatmap();
            myHM.Init($('#map').width(), 550); // Must be same as map size, or same ratio

            var data = new Array();
		    
	        if ($('#display-settings0').attr('checked')) {
			  $.each(markers, function () {
		        var point = new GLatLng(this.breite, this.laenge);
                var mapmarker = createMarker(point, this.name, Drupal.theme('mapTooltip', this.nid, this.name, this.leiter, this.website, this.artefakte), $('#gm-settings2').attr('checked'));
                map.addOverlay(mapmarker);
              });
		    } else if ($('#display-settings1').attr('checked')){
			  $.each(markers, function () {
		        var point = new GLatLng(this.breite, this.laenge);
                var mapmarker = createMarker(point, this.name, Drupal.theme('mapTooltip', this.nid, this.name, this.leiter, this.website, this.artefakte), $('#gm-settings2').attr('checked'), this.count);
                map.addOverlay(mapmarker);
              });
			} else {
		      var i = 1;
		      $.each(markers, function () {
			    if(i++ < 200) {		  
		          data.push(this.breite);
			      data.push(this.laenge);
			      data.push(this.count);
			    }	
		      });
			
		      if (i > 200) {
		        var error = Drupal.theme('errorBox', Drupal.t("Your map contains more than the currently supported amount of heat points. Only a selection of points is displayed."));
	            $(error).appendTo('body').fadeIn('slow');
	            $('#ok-error').click(Knowledgemapping.removeBox);
	            $('body').append('<div id="dark-background"></div>');
		      } 
	        }
		            
		    myHM.SetData(data);
            myHM.SetBoost(0.4); // Optional, see documentation
            myHM.SetDecay(0); // Optional, see documentation
            var preUrl = myHM.GetURL();

            // Now render in our Google Map
            var heatmapOverlay = new HMGoogleOverlay(preUrl);
            map.addOverlay(heatmapOverlay);
          } catch(e) {
			if ($('#display-settings2').attr('checked')) {
			  var error = Drupal.theme('errorBox', Drupal.t("Due to technical problems with the HeatMapAPI service heatmap view is temporarily unavailable. We apologize for the inconvenience caused. Please check back later!"));		  
	          $(error).appendTo('body').fadeIn('slow');
			  $('#ok-error').click(Knowledgemapping.removeBox);
			  $('body').append('<div id="dark-background"></div>');
			  $('#display-settings0').attr('checked', 'true');
			  $('#display-settings2').attr('disabled', 'true');
			  $('input[name="gm-settings"]').removeAttr('disabled');
			}
			
  		    $.each(markers, function () {
		      var point = new GLatLng(this.breite, this.laenge);
              var mapmarker = createMarker(point, this.name, Drupal.theme('mapTooltip', this.nid, this.name, this.leiter, this.website, this.artefakte), $('#gm-settings2').attr('checked'));
              map.addOverlay(mapmarker);
            });
		  }
	    }
	  }
	
	  //Function to retrieve the markers of a specified dimension. The PHP-Script is called. 
	  function getMap(dim) {
	    $.ajax({
          type: 'POST', 
          url: path,
		  async: false, //This is set to false as we need all the markers loaded first before we are able to continue.
	      data: {'function': 'getmarkers', 'mapID': mapID, 'dim': dim},
		  dataType: 'json', //The incoming data is interpreted as a JSON object.
		  success: function (data) {
		    markers = data;
		  }
        });
	  }
	  
	  //Function that sets up the dimension bar and preselects the dimension which should be visible from the beginning.
	  function buildDimBar(dims, visible) {
	    $.each(dims, function () {
	      $('#dimbar').append(Drupal.theme('dimBar', this));
          var id = '#dim' + this.ID;
          $(id).click(function () {
            getMap($(this).attr('id'));
		    setMap();
          });		
	    });
	  	
	    if(visible) {
	      var visibleDim = '#' + visible;
		  $(visibleDim).click();
	    } else {
		  $('#dim0').click();
		}
	  }
	  
	  //Function which automatically sets the map to fit all the markers.
	  function setZoom() {
	    if (typeof markers == 'undefined') {
		  return;
		}
		var bounds = new GLatLngBounds();
		$.each(markers, function () {
		  var point = new GLatLng(this.breite, this.laenge);
	      bounds.extend(point);  //The bounds object is extendend to cover all points.
		});
		map.setZoom(map.getBoundsZoomLevel(bounds)); //Zoom...
	    map.setCenter(bounds.getCenter());  //...and center are set.
	  }
	  
	  //This AJAX call "starts" the behaviour. First it loads the saved config into the data variable.
	  $.ajax({
	    type: 'POST', 
        url: path,
	    data: {'function': 'getconfig', 'mapID': mapID},
        dataType: 'json',
        success: function (data) {
		  //Setting the right maptype.
	      if (data.maptype == 'sat') {
		    map.setMapType(G_SATELLITE_MAP);
		  }
		  
  		  if (data.maptype == 'hyb') {
		    map.setMapType(G_HYBRID_MAP);
		  }

		  if (data.maptype == 'phy') {
		    map.setMapType(G_PHYSICAL_MAP);
		  }
		  
		  //Setting the center and zoom.
		  if (data.zoom > 0) {
            map.setCenter(new GLatLng(data.center[0], data.center[1]), data.zoom);
		  }
		  
		  //If there is a mapnav div, the user is allowed to save. In this case we just set all the checkboxes and radiobuttons.
		  //case: allowed to save
		  if ($('#mapnav').length > 0) {
		    //Set the nosave variable to false - important for the setMap function.
			nosave = false;
			
			//If the overview was 1 then add the overviewControl directly.
	        if (data.overview == 1) {
		      $('#gm-settings1').attr('checked', 'true');
			  var overviewControl = new GOverviewMapControl(new GSize(150,150));
		      map.addControl(overviewControl);
		    }
		  
		    //case: google maps view
	        if (data.view == 'google') {
			  //Check the Google Maps radio button.
		      $('#display-settings0').attr('checked', 'true');		
		      
			  //Check the tooltips checkbox if tooltips was "1".
		      if (data.tooltips == 1) {
		        $('#gm-settings2').attr('checked', 'true');
		      } 
		      
			  //Show the sidebar if sidebar was "1".
		      if (data.sidebar == 1) {
		        $('#gm-settings0').attr('checked', 'true');
		        $('#map').removeClass('without-sidebar').addClass('with-sidebar');
   	            $('#map-sidebar').fadeIn();
		      }	
            } else if (data.view == 'circles') {  //case: circles view
			  //Check the Google Maps radio button.
		      $('#display-settings1').attr('checked', 'true');
              $('#caption').show();			  
		      
			  //Check the tooltips checkbox if tooltips was "1".
		      if (data.tooltips == 1) {
		        $('#gm-settings2').attr('checked', 'true');
		      } 
		      
			  //Show the sidebar if sidebar was "1".
		      if (data.sidebar == 1) {
		        $('#gm-settings0').attr('checked', 'true');
		        $('#map').removeClass('without-sidebar').addClass('with-sidebar');
   	            $('#map-sidebar').fadeIn();
		      }	
            } else {
			  //case: heatmap view
			  //Check the Heatmap radio button.
			  $('#display-settings2').attr('checked', 'true');
			  
			  //Disable the sidebar and tooltips checkboxes because those options are unhandy in heatmap view.
		      $('#gm-settings0').attr('disabled', 'true');
		      $('#gm-settings2').attr('disabled', 'true');	
		    }
			
			//If there are more than one dimension set up the dimensionbar with the radiobuttons.
			if (data.dimensions.length > 1){
              buildDimBar(data.dimensions, data.visibleDim);
		    } else if	(data.dimensions.length == 1) {
			  //If there is just one dimension we can load it directly and set the map.
		      var dimload = 'dim' + data.dimensions[0].ID;
			  getMap(dimload);
			  setMap();
		    }
		  
		    //If there is at least one dimension we add the button which realigns the map to fit all markers.
		    if (data.dimensions.length > 0) {
		      $('#content-area').append(Drupal.theme('button', Drupal.t("Realign map"), 'set-zoom'));
		      $('#set-zoom').click(function () {
		        setZoom();
		      });
		    }
			
			//We add a click handler to the save button which reads all config parameters and sends the new config to the PHP script.
		    $('#save-state').click(function () {
			  //Sidebar checkbox
		      if($('#gm-settings0').attr('checked')){
	            data.sidebar = 1;
		      }	else {
		        data.sidebar = 0;
		      }
		      
			  //Overview checkbox
		      if($('#gm-settings1').attr('checked')){
	            data.overview = 1;
		      }	else {
		        data.overview = 0;
		      }
		  
		      //Tooltip checkbox
		      if($('#gm-settings2').attr('checked')){
	            data.tooltips = 1;
		      } else {
		        data.tooltips = 0;
		      }
		  
		      //Display mode radiobuttons
		      if($('#display-settings0').attr('checked')){
	            data.view = 'google';
		      }	else if($('#display-settings1').attr('checked')){
	            data.view = 'circles';
		      } else {
		        data.view = 'heat';
		      }
		      
			  //Which dimension is currently selected?
			  if($('input[name="dim-select"]:checked').length == 1) {
			    data.visibleDim = $('input[name="dim-select"]:checked').attr('id');
			  }
			  
			  //Which maptype?
			  if (map.getCurrentMapType() == G_NORMAL_MAP) {
			    data.maptype = 0;
			  }
			  
			  if (map.getCurrentMapType() == G_SATELLITE_MAP) {
			    data.maptype = 'sat';
			  }
			
			  if (map.getCurrentMapType() == G_HYBRID_MAP) {
			    data.maptype = 'hyb';
			  }
			
			  if (map.getCurrentMapType() == G_PHYSICAL_MAP) {
			    data.maptype = 'phy';
			  }
			  
			  //Which zoom and center?
		      data.zoom = map.getZoom();
		      data.center[0] = map.getCenter().lat();
		      data.center[1] = map.getCenter().lng();
		      
			  //Putting it all into a JSON string. This is done by the external JSON script.
		      var jsonString = JSON.stringify(data);
              var path = $('#path').val();
              
			  //AJAX call sending the config back to the PHP-script
              $.ajax({
                type: 'POST', 
                url: path,
	            data: {'function': 'saveconfig', 'mapID': mapID, 'config': jsonString}
              });
	        });
          } else { //case: user is not allowed to save the map config.
		    //We set nosave to true.
		    nosave = true;
			
			//We add the map overview.
		    if(data.overview == 1) {
              var overviewControl = new GOverviewMapControl(new GSize(150,150));
		      map.addControl(overviewControl);
	        }
			
			//We fade in the sidebar.
			if (data.sidebar == 1) {
              $('#map').removeClass('without-sidebar').addClass('with-sidebar');
   	          $('#map-sidebar').fadeIn();
	        }
			
			//As there is no navbar the setmap function needs other variables than the radios and checkboxes on the navbar to set up the map.
			//For that purpose we use the global variables "tooltips" and "google".
			if (data.tooltips == 1) {
			  tooltips = true;
			} else {
			  tooltips = false;
			}
			
			if (data.view == 'google') {
			  google = true;
			} else if (data.view == 'circles') {
			  circles = true;
			} else {
			  heat = true;
			}
			
			//Same functions as in the other case.
	        if (data.dimensions.length > 1){
              buildDimBar(data.dimensions, data.visibleDim);
		    } else if	(data.dimensions.length == 1) {
		      var dimload = 'dim' + data.dimensions[0].ID;
			  getMap(dimload);
			  setMap();
		    }
		  
		    if (data.dimensions.length > 0) {
		      $('#content-area').append(Drupal.theme('button', Drupal.t("Realign map"), 'set-zoom'));
		      $('#set-zoom').click(function () {
		        setZoom();
		      });
		    } 			
          }		  
        }		  
      });
    }
  }
};

/**
 * Hides the checkmark and resets the form elements if the address value is changed.
 */ 
Drupal.behaviors.changeAddress = function () {
  $('#edit-adresse').change(function () {
    $('#edit-adresse-checkmark').css('visibility', 'hidden');
	$('#edit-laenge').val("");
	$('#edit-breite').val("");
  });
};

/**
 * Geocode a location.
 */
Knowledgemapping.geocode = function () {
  //Building the url of the google maps geocoding service. We ask for a response in JSON format. 
  var searchlocation = $('#edit-adresse').val();
  var apikey = $('input[name=apikey]').val();
  var url = "http://maps.google.com/maps/geo?q=" + searchlocation + "&output=json&key=" + apikey + "&callback=?";
  
  //We use jQuery's getJSON function to execute the HTTP-Request
  $.getJSON(url, function (data){
	//If no location was found we inform the user about that
    if (typeof data.Placemark == 'undefined') {
      var error = Drupal.theme('errorBox', Drupal.t("The address %searchlocation could not be located. Please try another address or maybe another spelling of the address.", {"%searchlocation": searchlocation}));
	  $(error).appendTo('body').fadeIn('slow');
	  $('#ok-error').click(Knowledgemapping.removeBox);
	  $('body').append('<div id="dark-background"></div>');
    }	
	//If just one location was found we can proceed easily
    else if (data.Placemark.length == 1) {
      var longitude = data.Placemark[0].Point.coordinates[0];
      var latitude = data.Placemark[0].Point.coordinates[1];
	  var address = data.Placemark[0].address;
	  
	  $('#edit-laenge').val(longitude);
	  $('#edit-breite').val(latitude);
	  $('#edit-adresse').val(address);
	  
	  //Displaying the green checkmark
	  $('#edit-adresse-checkmark').css('visibility', 'visible');  
    }
	//If multiple locations were retrieved we display a box where the user is asked which location he wants to add
	else {
	  var didyoumean = Drupal.theme('didyoumeanBox', data.Placemark);
	  $(didyoumean).appendTo('body').fadeIn('slow');
	  $('#ok-didyoumean').click(function(){
	      if (typeof $('input[name=locations]:checked').val() == 'undefined') {
            var error = Drupal.theme('errorBox', Drupal.t("Please select one of the locations first."));
	        $('#didyoumean').hide();
	        $(error).appendTo('body').show();
	        $('#ok-error').click(function (){
	          $('#errorbox').remove();
	          $('#didyoumean').show();
	        });
          } else {
		    //Putting the data of choice into the hidden fields
            var choice = $('input[name=locations]:checked').val();
            var longitude = data.Placemark[choice].Point.coordinates[0];
            var latitude = data.Placemark[choice].Point.coordinates[1];
	        var address = data.Placemark[choice].address;
	
	        $('#edit-laenge').val(longitude);
	        $('#edit-breite').val(latitude);
	        $('#edit-adresse').val(address);
			
			//Displaying the green checkmark
	        $('#edit-adresse-checkmark').css('visibility', 'visible');  
	
	        Knowledgemapping.removeBox();
          }
	  });
	
	  $('#cancel').click(Knowledgemapping.removeBox);
	  $('body').append('<div id="dark-background"></div>');
	}	  
  });
};

/**
 * Theme a "Did you mean?"-box. All the placemarks which were found have to be provided as a parameter.
 */
Drupal.theme.prototype.didyoumeanBox = function (placemarks){
  var didyoumeanBox = $('<div id="didyoumean"></div>'); 
  didyoumeanBox.append('<span class="heading">' + Drupal.t("Multiple locations were found. Which location did you mean?") + '</span>');
  var options = $('<div id="options"></div>');
  
  //Each placemark gets its radiobutton.
  $.each(placemarks, function (i) {
    options.append('<input type="radio" name="locations" value="' + i + '"/>' + this.address + '<br>');
  });
  
  var buttonOK = Drupal.theme('button', "OK", 'ok-didyoumean');
  var buttonCancel = $(Drupal.theme('button', Drupal.t("Cancel"), 'cancel')).css('margin-left', '6px');
  
  var centerWrapper = $('<div id="didyoumean-center-wrapper"></div>');
  
  //If the language is German we need a wider center wrapper as the word length differs and we want the buttons to be centered.
  if(Drupal.t("Cancel") == "Abbrechen") {
    centerWrapper.width(165);
  }
  var buttons = centerWrapper.append(buttonOK, buttonCancel);
  
  return didyoumeanBox.append(options, buttons).parent().html();
};

/**
 * Theme the navbar content. The checkbox option part.
 */
Drupal.theme.prototype.navgroupCheck = function (id, name, heading, options){
  var tpl = $('<div id="' + id + '" class="nav-group"></div>');
  tpl.append('<h3 class="nav-group-heading nav-group-heading-' + id +'">' + heading + '</h3>');
  
  $.each(options, function (i) {
    tpl.append('<div class="nav-group-check-option"><input type="checkbox" name="' + name + '" id="' + name + i + '" value="' + name + i + '"/><span class="nav-group-check-option-text">' + this + '</span>');
  });
  
  return tpl.parent().html();
};

/**
 * Theme the navbar content. The radiobutton part.
 */
Drupal.theme.prototype.navgroupRadio = function (id, name, heading, options){
  var tpl = $('<div id="' + id + '" class="nav-group"></div>');
  tpl.append('<h3 class="nav-group-heading nav-group-heading-' + id +'">' + heading + '</h3>');
  
  $.each(options, function (i) {
    tpl.append('<div class="nav-group-radio-option"><input type="radio" name="' + name + '" id="' + name + i + '" value="' + i + '"/><span class="nav-group-radio-option-text">' + this + '</span>');
  });
  
  return tpl.parent().html();
};

/**
 * Remove any boxes and set the focus back to the address input.
 */
Knowledgemapping.removeBox = function () {
  $('#errorbox').remove();
  $('#didyoumean').remove();  
  $('#dark-background').remove();
  $('#edit-adresse').focus();
}

/**
 * Set up the navbar.
 */
Knowledgemapping.setUpNavbar = function () {
  //First put together all the elements we need.
  var gmSettings = Drupal.theme('navgroupCheck', 'gm-settings', 'gm-settings', Drupal.t("Map Settings"), new Array(Drupal.t("Sidebar"), Drupal.t("Overview Map"), "Tooltips"));
  var mapstateSettings = Drupal.theme('navgroupRadio', 'display-settings', 'display-settings', Drupal.t("Display Mode"), new Array('Google Maps', Drupal.t("Circles"), 'Heatmap'));
  var navElements = $('<div class="nav-elements"></div>').append(gmSettings, mapstateSettings);
    
  var buttonSave = $(Drupal.theme('button', Drupal.t("Save this state"), 'save-state'));
  navElements.append(buttonSave);
	
  $('#mapnav').append(navElements);
  
  //The first elements don't need any margin on the left
  $('.nav-group-check-option:first').css('margin-left', '0px');
  $('.nav-group-radio-option:first').css('margin-left', '0px');
  
  //If the interface is displayed in german, we want the nav-elements and the headings to be centered correctly
  if(Drupal.t("Map Settings") == "Karteneinstellungen") {
	$('.nav-group-heading-gm-settings').width(159);
	$('.nav-elements').width('750px');
  }
  
  if(Drupal.t("Display mode") == "Anzeigemodus") {
    $('.nav-group-heading-display-settings').width(115);
  }
  
  if(Knowledgemapping.getViewport()[0] <= 1147){
    $('.nav-elements').width('600px');
	$('#gm-settings').css('margin-right', '10px');
	$('.nav-elements').css('font-size', 'xx-small');
	$('#save-state').css('font-size','x-small');
	
	if(Drupal.t("Map Settings") == "Karteneinstellungen") {
	  $('.nav-group-heading-gm-settings').width(112);
    } else {
	  $('.nav-group-heading-gm-settings').width(72);
	}
  
    if(Drupal.t("Display mode") == "Anzeigemodus") {
      $('.nav-group-heading-display-settings').width(84);
    } else {
	  $('.nav-group-heading-display-settings').width(73);
	}
  }
  
  /*if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
    var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
    if (ieversion < 8){
	  var oldIE = true;
	  $('#mapnav').css('marginTop', '-55px');
	  $('.navslider').toggle(function (){
        $('#mapnav').animate({marginTop: '0px'} , 2000);
        setTimeout(function(){
          $('.navslider').removeClass('arrow-down').addClass('arrow-up');
        },2000);
      }, function(){
        $('#mapnav').animate({marginTop: '-55px'} , 2000);
        setTimeout(function(){
          $('.navslider').removeClass('arrow-up').addClass('arrow-down');
        },2000);
      });
	}
  }

  if(!oldIE){
    //Then we add the animation to the arrow by using the toggle and animate functions of jQuery.  
    $('.navslider').toggle(function (){
      $('#mapnav').animate({marginTop: '0px'} , 2000);
      setTimeout(function(){
        $('.navslider').removeClass('arrow-down').addClass('arrow-up');
      },2000);
    }, function(){
      $('#mapnav').animate({marginTop: '-52px'} , 2000);
      setTimeout(function(){
        $('.navslider').removeClass('arrow-up').addClass('arrow-down');
      },2000);
    });
  }*/
  
  //Adding the click event which makes the sidebar appear.  
  $('#gm-settings0').click(function () {
    var checked = this.checked;
    if (checked) {
      $('#map').removeClass('without-sidebar').addClass('with-sidebar');
   	  $('#map-sidebar').fadeIn();
	} else {
      $('#map').removeClass('with-sidebar').addClass('without-sidebar');
      $('#map-sidebar').fadeOut();
	}
  });  
}

/**
 * Theme a map tooltip box with all the artefacts and the information about the unit.
 */
Drupal.theme.prototype.mapTooltip = function (nid, name, leiter, website, artefakte){
  var tooltip = $('<div class="tooltip"></div>');
  
  var title = $('<h3 class="name"><a href="' + $('#nodepath').val() + nid + '" target="_blank">' + Knowledgemapping.formatLink(name, 75) + '</a></h3>');
  
  var unitDescription = $('<div class="unit-description"></div>');
  var manager = $('<div class="unit-leiter-line"><label for="leiter">' + Drupal.t('Manager:') + '</label><span class="leiter">' + leiter + '</span></div>');
  var web = $('<div class="unit-website-line"><label for="website">' + Drupal.t('Website:') + '</label><span class="website"><a href="' + website + '" target="_blank">' + website + '</a></span></div>');
  unitDescription.append(manager, web);
  
  var artefactArea = $('<fieldset class="artefact-set"><legend>' + Drupal.t('Research results') + '</legend></fieldset>');
  var artefactList = $('<ul class="artefacts"></ul>');
  $.each(artefakte, function () {
    artefactList.append(Drupal.theme('artefactLink', this));
  });
  artefactArea.append(artefactList);
  
  tooltip.append(title, unitDescription, artefactArea);
    
  return tooltip.parent().html();
};

/**
 * Theme a artefact link list item.
 */
Drupal.theme.prototype.artefactLink = function (artefakt){
  var link = $('<li><a href="' + $('#nodepath').val() + artefakt.artNID + '" target="_blank">' + Knowledgemapping.formatLink(Drupal.t(artefakt.name), 80) + '</a></li>');
     
  return link.parent().html();
};

/**
 * Theme the dimension select bar.
 */
Drupal.theme.prototype.dimBar = function (dim){
  var tpl = $('<div class="dimradio"><input type="radio" class="dimradio-button" name="dim-select" id="dim' + dim.ID + '"/>' + Drupal.t(dim.name) + '</div>');
      
  return tpl.parent().html();
};

/**
 * Theme the circle view caption.
 */
Drupal.theme.prototype.caption = function (basepath){
  var tpl = $('<div id="caption"><table><tr><th width="70px">' + Drupal.t("Circle") + '</th><th>' + Drupal.t("Number of results") + '</th></tr><tr><td><img src="' + basepath + '/images/circle5.png" alt="circle5"></td><td><=5</td></tr><tr><td><img src="' + basepath + '/images/circle10.png" alt="circle10"></td><td><=10</td></tr><tr><td><img src="' + basepath + '/images/circle15.png" alt="circle15"></td><td><=15</td></tr><tr><td><img src="' + basepath + '/images/circle25.png" alt="circle25"></td><td><=25</td></tr><tr><td><img src="' + basepath + '/images/circleMoreThan25.png" alt="circleMoreThan25"></td><td>>25</td></tr></table></div>');
      
  return tpl.parent().html();
};

/**
 * Format a link to a specified amount of characters.
 */
Knowledgemapping.formatLink = function (text, length) {
  text = Drupal.checkPlain(text);
  if (text.length > length) {
    text = text.substring(0, length);
    var lastSpace = text.lastIndexOf(' ');
    if (lastSpace > 0) {
      text = text.substring(0, lastSpace);
    }
    text += '...';
  }
  return text;
}

/**
 * Determine the size of the Viewport
 */
Knowledgemapping.getViewport = function () {
  var viewportwidth;
  var viewportheight;
  // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 
  if (typeof window.innerWidth != 'undefined'){
    viewportwidth = window.innerWidth,
    viewportheight = window.innerHeight
  }
 
  // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

  else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
    viewportwidth = document.documentElement.clientWidth,
    viewportheight = document.documentElement.clientHeight
  }
 
  // older versions of IE
 
  else {
    viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
    viewportheight = document.getElementsByTagName('body')[0].clientHeight
  }
  
  result = new Array(viewportwidth, viewportheight);
  
  return result;
}