var map = null;
var pin = "http://www.nordseetraum.de/konfiguration/gfx/pin.gif";

// dynamische Variablen
var address = "";
var overview_status = 0;
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;

// bestimmt die Daten eines ausgewählten Objektes und lädt die Anfahrt neu
function map24Select() {
   $('infoText').update('Bitte haben Sie einen Moment Geduld!');
   $('info').show();

   var ajaxCon = new Ext.data.Connection({});
   ajaxCon.request({
   	url: 'http://www.heyken-vermietung.de/inc/ajax/heyken.ajax.php',
   	success: function(r, o){
   		eval(r.responseText);

         window.setTimeout("$('info').hide();",10000);

         map24ApiLoaded();
   	},
   	failure: function(r, o)
   	{
   		alert('Fehler map24-Anfahrt nach Auswahl eines Objektes');
   	},
   	params: {action: 'map24Select', objID: Ext.getDom('objID').getValue()}
   });
}


// lädt die Karte neu
function map24Reset() {
   // Eingabefeld löschen
   $("map24Start").value = "";

   // Karte neu laden
   map24ApiLoaded();
}

// 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();
}

// 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: "http://www.nordseetraum.de/konfiguration/gfx/pin.gif"
   });
   //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
   if(label_status == 1)window.setTimeout("addMap24Label()", 2000);
}

// 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: "map24" } );
   /*
   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() {
   var ajaxCon = new Ext.data.Connection({});
   ajaxCon.request({
   	url: 'http://www.heyken-vermietung.de/inc/ajax/heyken.ajax.php',
   	success: function(r, o){
   		eval(r.responseText);
         var m = Ext.getDom('map24');
         m.style.width = mapWidth + 'px';
         m.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 );

   	},
   	failure: function(r, o)
   	{
   		alert('Fehler map24-Anfahrt');
   	},
   	params: {action: 'goMap24'}
   });
}
///////////////////////////////////////
//
// ROUTING BEGINN
//
///////////////////////////////////////
//Declare global variables
var geocoder = null;
var router = null;
var routePoints = [];
var routeID = null;

// Ablauf bei Klick auf "Route berechnen"
function map24Route() {
   // Route berechnen
   calculateRouteAddr();
}

function calculateRouteAddr() {
   //Retrieve start and destination of the route from the input fields
   var map24Start = Map24.trim(document.getElementById('map24Start').value);
   var map24Dest = Map24.trim(document.getElementById('map24Dest').value);

   //Check if the start and the destination form fields are empty
   if( map24Start == "" ) { alert("Bitte geben Sie eine Startadresse ein"); return; }
   if( map24Dest == "" ) { alert("Please enter destination address!"); return; }

   $('infoText').update('Bitte haben Sie einen Moment Geduld!');
   $('info').show();

   //Create a geocoder stub
   var geocoder = new Map24.GeocoderServiceStub();

   //Geocode the start point of the route
   geocoder.geocode
   ({
      SearchText: map24Start,
      //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: "map24Start"}
   });

   //Geocode the destination point of the route
   geocoder.geocode
   ({
      SearchText: map24Dest,
      CallbackFunction: setRouteEndPoint,
      CallbackParameters: {position: "map24Dest"}
   });
}

//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["map24Start"] != "undefined" && typeof routePoints["map24Dest"] != "undefined")
   calculateRoute();
}

//Calculate the route.
function calculateRoute() {
   router = new Map24.RoutingServiceStub();
   router.calculateRoute
   ({
      Start: routePoints["map24Start"],
      Destination: routePoints["map24Dest"],
      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]
   });
   window.setTimeout("$('info').hide();",4000);
}
///////////////////////////////////////
//
// ROUTING ENDE
//
///////////////////////////////////////

///////////////////////////////////////
//
// sonstige Funktionen
//
///////////////////////////////////////
// Label ein-/ausblenden
var statusLabel = 1;
function map24ToggleLabels() {
   if(statusLabel == 1) {
      myLabel.hide();
      statusLabel = 0;
   } else {
      myLabel.show();
      statusLabel = 1;
   }
}

// 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);
}
