/*
Dateiname: map24.js
Diese Datei beinhaltet die benötigten Javascripts für die Anfahrtsseiten

Die Seite funktioniert wie folgt:
1. Zunächst wird die Seite geladen. Die Karte wird geladen und die Schaltflächen sind deaktiviert
2. Sobald die Seite geladen ist, erscheint die Europa-Karte
3. Karte oomt auf Ostfriesland
4. Wenn in der Verwaltung im OMS die 1. ZOOM-Stufe freigegeben wurde, erfolgt ein Zoom der Karte auf den Ort des Objektes
5. Wenn in der Verwaltung im OMS der Label freigegeben wurde, wird in der Karte ein Kreis und ein Label an der Position des Objektes angezeigt.
6. Die Schaltflächen werden freigegeben

Wenn "Route berechnen" angeklickt wird:
1. Die Schaltflächen werden deaktiviert und der Text der Schaltflächen in "bitte warten" geändert
2. Das Warte-Symbol wird eingeblendet
3. Die berechnete Route wird in der Karte angezeigt
4. Das Warte-Symbol wird ausgeblendet
6. Die Schaltfläche wird freigegeben und der Text in "Route berechnen" geändert

////////////////////////////////////
Version: 3.0.0
////////////////////////////////////
02.12.08
- nötige Änderungen für unser-bensersiel: alle PHP-Variablen fliegen aus dieser Datei raus und werden erst bei Bedarf gesetzt
  siehe unserBensersiel.ajax.php case "getObjRoute":

////////////////////////////////////
Version: 2.0.0 (bis hier alte nordseetraum-Seiten-Version)
////////////////////////////////////
18.-19.06.08
- neue map24-Version zwingt uns dazu, dieses Skript umzuschreiben
- KEINE prototype $ verwenden!!!!

////////////////////////////////////
Version: 1.0.2
////////////////////////////////////
20.05.08
- Pin in der Anfahrt kann duch die Variable $pin definiert werden
- Value des 4 Buttonskann durch die Vraiable $value_button4 geetzt werden

08.06.07
- Browserabfrage für IE7 erweitert

03.05.07
- Sonderzeichen &#39; im Label wird durch ' ersetzt

15.03.07
- nl2br für Seitentitel

09.03.07
- Ersteinrichtung

//////////////////////////////////////////////////////////////////////
//
// Variablen initialisieren (Pflichtvariablen auf Werte überprüfen)
//
//////////////////////////////////////////////////////////////////////
*/
var map = null;
var pin = "http://www.nordseetraum.de/konfiguration/gfx/pin.gif";
var value_button4 = "Hausname an/aus";

// dynamische Variablen
var zoom_status = 0;
var label_status = 0;
var label_textcolor = new Array();
var label_bordercolor = new Array();
var label_bgcolor = new Array();
var label_x = 0;
var label_y = 0;
var label_content = "";
var location_x = 0;
var location_y = 0;
var zoom_x = 0;
var zoom_y = 0;
var zoom_min = 0;
var mapHeight = 0;
var mapWidth = 0;

///////////////////////////////////////
//
// ROUTING BEGINN
//
///////////////////////////////////////
//Declare global variables
var geocoder = null;
var router = null;
var routePoints = [];
var routeID = null;

// Ablauf bei Klick auf "Route berechnen"
function froute()
{
   // Schaltflächen deaktivieren
   fbt_status();

   // Route berechnen
   calculateRouteAddr();
}

function calculateRouteAddr()
{
   //Retrieve start and destination of the route from the input fields
   var start = Map24.trim(document.getElementById('start_address').value);
   var destination = Map24.trim(document.getElementById('dest_address').value);

   //Check if the start and the destination form fields are empty
   if( start == "" ) { alert("Bitte geben Sie eine Startadresse ein"); fbt_status(); return; }
   if( destination == "" ) { alert("Please enter destination address!"); fbt_status(); return; }

   //Create a geocoder stub
   var geocoder = new Map24.GeocoderServiceStub();

   //Geocode the start point of the route
   geocoder.geocode
   ({
      SearchText: start,
      //Define the name of the callback function that is called when the result is available on the client.
      CallbackFunction: setRouteEndPoint,
      //Set a parameter that is passed to the callback function. The parameter defines that this is the start point.
      CallbackParameters: {position: "start"}
   });

   //Geocode the destination point of the route
   geocoder.geocode
   ({
      SearchText: destination,
      CallbackFunction: setRouteEndPoint,
      CallbackParameters: {position: "destination"}
   });
}

//Callback function that is called when the geocoding result is available.
//The locations parameter contains an array with multiple alternative geocoding results.
//The params parameter passes the value of CallbackParameters that specifies which route
//end point is returned (start or destination point).
function setRouteEndPoint(locations, params)
{
   //Access the geocoded address and add it to the routePoints array.
   //The geocoded address is stored at the first position in the locations array.
   routePoints[ params.position ] = locations[0];

   //After both the start and the destination addresses are geocoded, this function calls the calculateRoute() function.
   if( typeof routePoints["start"] != "undefined" && typeof routePoints["destination"] != "undefined")
   calculateRoute();
}

//Calculate the route.
function calculateRoute()
{
   router = new Map24.RoutingServiceStub();
   router.calculateRoute
   ({
      Start: routePoints["start"],
      Destination: routePoints["destination"],
      CallbackFunction: displayRoute,
      ShowRoute: false
   });
   routePoints = [];
}

//Callback function used to access the calculated route of type Map24.WebServices.Route.
//This function is called after the client has received the result from the routing service.
function displayRoute( route )
{

   //Remember the routeId. It is used e.g. to hide the route.
   routeID = route.RouteID;
   router.showRoute
   ({
      RouteId: routeID,
      Color: ['#0080FF', 150]
   });

   /*
   //Access the assumed time needed for traversing the route in hours
   var totalTime = ((route.TotalTime)/(60*60) ).toPrecision(3)
   //Access the total lenght of the route in kilometers
   var totalLength = (route.TotalLength/1000)
   //Create table with description of the route
   var div_content = "Total Time: " + totalTime + " h<br>" ;
   div_content += "Total Length: "+ totalLength +" km<br>";
   div_content += "<br>";

   //Iterate through the route segments and output the step-by-step textual description of the route
   for(var i = 0; i < route.Segments.length; i++)
   {
      for(var j = 0; j < route.Segments[i].Descriptions.length; j++)
      {
         //The route description contains tags for further evaluation. For example, the [M24_STREET] tag is used
         //to denote a street in the description. Add the following line of code to replace these tags by a blank:
         div_content += (i+1) + ". " + route.Segments[i].Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '' ) + "<br>";
      }
   }
   document.getElementById('routeDescription').innerHTML = div_content;
   document.getElementById("button_hide_route").disabled = false;
   document.getElementById("button_remove_route").disabled = false;
   document.getElementById("print").disabled = false;
   */

   // Schaltflächen reaktivieren
   fbt_status();

}
///////////////////////////////////////
//
// ROUTING ENDE
//
///////////////////////////////////////

// Label ein-/ausblenden
var status_label = 1;
function fshowhide_label()
{
   if(status_label == 1)
   {
      myLabel.hide();
      status_label = 0;
   }
   else
   {
      myLabel.show();
      status_label = 1;
   }
}

// Schaltflächen aktivieren/deaktivieren
var bt_status = 0;
function fbt_status()
{
   if(bt_status==0)
   {
      document.getElementById("img_loading").style.visibility = "hidden";
      // Schaltflächen reaktivieren
      document.getElementById("bt_reset").value = "zurücksetzen";
      document.getElementById("bt_reset").disabled = false;
      document.getElementById("bt_submit").value = "Route berechnen";
      document.getElementById("bt_submit").disabled = false;
      document.getElementById("bt_print").value = "Diese Seite drucken";
      document.getElementById("bt_print").disabled = false;
      document.getElementById("bt_showlabel").value = value_button4;
      document.getElementById("bt_showlabel").disabled = false;
      bt_status = 1;
   }
   else
   {
      document.getElementById("img_loading").style.visibility = "visible";
      // Schaltflächen seaktivieren
      document.getElementById("bt_reset").value = "bitte warten...";
      document.getElementById("bt_reset").disabled = true;
      document.getElementById("bt_submit").value = "bitte warten...";
      document.getElementById("bt_submit").disabled = true;
      document.getElementById("bt_print").value = "bitte warten...";
      document.getElementById("bt_print").disabled = true;
      document.getElementById("bt_showlabel").value = "bitte warten...";
      document.getElementById("bt_showlabel").disabled = true;
      bt_status = 0;
   }
}

// Funktionen zum Umrechnen der alten RGB-Werte (map24 Version 1.x) in HEX-Werte (map24 Version 2.x)
function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(N)
{
   if (N==null) return "00";
   N=parseInt(N); if (N==0 || isNaN(N)) return "00";
   N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
   return "0123456789ABCDEF".charAt((N-N%16)/16)
   + "0123456789ABCDEF".charAt(N%16);
}

// Beim Erstaufruf Label anzeigen
var myLabel = null;
function addMap24Label()
{
    //Create a label. You have to define longitude and latitude and the text of the label.
    //You can define the text color (Color field) and background color (Background array).
    //In the second position of the Background array you can define the opacity (here: 200).
    //After the constructor is called the label is invisible initially.
    
    var vColor = RGBtoHex(label_textcolor[0],label_textcolor[1],label_textcolor[2]);
    var vFrameColor = RGBtoHex(label_bordercolor[0],label_bordercolor[1],label_bordercolor[2]);
    var vBackground = RGBtoHex(label_bgcolor[0],label_bgcolor[1],label_bgcolor[2]);

    myLabel = new Map24.Label({
      Anchor: "CENTER",
      Longitude: label_x,
      Latitude: label_y,
      Text: label_content,
      Color: "#"+vColor,
      FrameColor: "#"+vFrameColor,
      Background: "#"+vBackground
    });

    //Call commit() on the label. By default, the label is shown on the map. If false is passed
    //to commit, the map object is not shown on the map by default.
    myLabel.commit();
    
    // Buttons reaktivieren
    fbt_status();
}

// Beim Erstaufruf Pin anzeigen
var myLoc = null;
function addLocation()
{
   //Create a new location.
   myLoc = new Map24.Location({
      Longitude: location_x,
      Latitude: location_y,
      Description: "",
      LogoURL: pin
   });
   //Commit the location. Only after calling commit() it is possible
   //to execute further operations on the location such as hide and show.
   myLoc.commit();

   // Label anzeigen
   (label_status == 1)?
   window.setTimeout("addMap24Label()", 2000):
   fbt_status();

}

// 1. Zoom-Stufe
function centerMapAboveGivenCoordinate()
{
   Map24.MapApplication.center( { Coordinate:new Map24.Coordinate(zoom_x, zoom_y), MinimumWidth: zoom_min } );
}

// Zoom auf Ostfriesland
function centerMapAboveOstfriesland()
{
   Map24.MapApplication.center( { Coordinate:new Map24.Coordinate(455.3872375488281, 3210.488037109375), MinimumWidth: 130000 } );

   // 1. Zoom-Stufe aktivieren
   if(zoom_status == 1)
      window.setTimeout("centerMapAboveGivenCoordinate()", 3000);

   // Pin anzeigen
   window.setTimeout("addLocation()", 5000);
}

//Callback function called when the API is loaded. The map can now be shown.
function map24ApiLoaded()
{
   //Initialize mapping client and show map.
   Map24.MapApplication.init( { NodeName: "maparea" } );
   /*
   IE7 unter Vista funktioniert nicht mit dem Java-Applet, daher erst mal ohne Angabe auf "auto"
   (!navigator.javaEnabled())
   Map24.MapApplication.setMapType( "Static" ):
   Map24.MapApplication.setMapType( "Applet" );
   */

   // Zoom auf Ostfriesland
   window.setTimeout("centerMapAboveOstfriesland()", 3000);
}

function goMap24()
{
   // DIV-Style
   //document.getElementById('maparea').style.width = mapWidth + "px";
   document.getElementById('maparea').style.height = mapHeight + "px";

   //Load core and wrapper APIs and specify a callback method. This method is called when the API is loaded and the map
   //can be shown.
   Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );
}

// lädt die Karte neu
function fstart()
{
   // Eingabefeld löschen
   document.getElementById("start_address").value = "";
   
   // Zieladresse zurücksetzen
   document.getElementById("dest_address").value = document.getElementById("destAddress").value;

   // Buttons deaktivieren
   fbt_status();

   // Karte neu laden
   map24ApiLoaded();
}
