﻿/// <reference path="VEJS/VeJavaScriptIntellisenseHelper.js" />
Type.registerNamespace("tn_standorte");

tn_standorte.Map = function(service, mapArgs) {

    this._service = service;
    this._mapArgs = mapArgs;

    this._map = null;
    this.getLocationsDelegate = Function.createDelegate(this, this._getLocations);
    this.MouseClickHandlerDelegate = Function.createDelegate(this, this._mouseclickhandler);
    this.OnGotRoute = Function.createDelegate(this, this._onGotRoute);
    this.OnGotLocationDetail = Function.createDelegate(this, this._onGetLocationSucceeded);
    this.No3dInstalledDelegate = Function.createDelegate(this, this._no3DInstalled);
    this.TokenErrorHandlerDelegate = Function.createDelegate(this, this._tokenErrorHandler);

    this.tuevLocationLat = null;
    this.tuevLocationLong = null;
    this.tuevLocation = null;
    this.nach = null;
    this.standortDetail = null;

    // Optimale Route Zoom
    this.optimalRouteLatLong = null;
    this.optimalRouteZoom = null;

    this._standorteLayer = null;
    this._oldLoc = null;

    // Sichtbare Pushpins (z.B. für Zoom)
    this._visibleResultSet = null;

    this._firmenname = "-1";
    this._bereich = "-1";
    this._locationId = "-1";

    if (document.getElementById("DropDownListLocations") != null && document.getElementById("DropDownListLocations").value != null && document.getElementById("DropDownListLocations").value != "") {
        this._firmenname = document.getElementById("DropDownListLocations").value;
    }
    if (document.getElementById("DropDownListBereich") != null && document.getElementById("DropDownListBereich").value != null && document.getElementById("DropDownListBereich").value != "") {
        this._bereich = document.getElementById("DropDownListBereich").value;
    }
    if (document.getElementById("HiddenFieldLocationIdGetParameter") != null && document.getElementById("HiddenFieldLocationIdGetParameter").value != null && document.getElementById("HiddenFieldLocationIdGetParameter").value != "") {
        this._locationId = document.getElementById("HiddenFieldLocationIdGetParameter").value;
    }

    // Object für Languagekeys und values
    this._languageValues = new Object();

    this._currentLocs = new Array();
    this._init();

}

tn_standorte.Map.prototype = {

    _init: function() {

        try {
            this._map = new VEMap(this._mapArgs.DivID);
            this._map.SetClientToken(_token);
            this._map.LoadMap(this._mapArgs.Center, this._mapArgs.Zoomlevel, this._mapArgs.Style, this._mapArgs.Fixed, this._mapArgs.Mode);
            this._map.SetScaleBarDistanceUnit(this._mapArgs.Scale);

            this._standorteLayer = new VEShapeLayer();
            this._map.AddShapeLayer(this._standorteLayer);

        }
        catch (ex) {
            //This block will catch VE JavaScript exceptions
            alert("The following exception has occurred: " + ex.name + ", " + ex.message);
        }

        this._map.AttachEvent("onchangeview", this.getLocationsDelegate);
        this._map.AttachEvent("onclick", this.MouseClickHandlerDelegate);

        this._map.AttachEvent("ontokenerror", this.TokenErrorHandlerDelegate);
        this._map.AttachEvent("ontokenexpire", this.TokenErrorHandlerDelegate);

        // Falls virtual earth 3d nicht installiert ist...
        this._map.AttachEvent('onmodenotavailable', this.No3dInstalledDelegate);

        // Eigenen CSS Stylesheet verwenden (/style/tuevnord.css)
        this._map.ClearInfoBoxStyles();

        this._getLocations();

        //Enable printing
        var printOpt = new VEPrintOptions(true);
        this._map.SetPrintOptions(printOpt);


    },

    _tokenErrorHandler: function() {

        alert(location_webResx.txt_VeTokenError);
    },

    _no3DInstalled: function() {
        window.open("VE3DInstall.aspx?lng=" + location_webResx._lng, "VE3DInstall", "width=450, height=200, toolbar=no, scrollbars=yes, menubar=no, resizable=yes, status=yes");
    },

    // zeigt Land
    _showCountry: function() {
        var dropDownListCountry = document.getElementById("DropDownListCountry");
        var selectedCountry = dropDownListCountry.selectedIndex;

        if (dropDownListCountry != null && dropDownListCountry[selectedCountry].value != null && dropDownListCountry[selectedCountry].value != "") {

            var country = dropDownListCountry[selectedCountry].value.split("_");

            if (country.length > 2) {
                var focus = new VELatLong(parseFloat(country[1]), parseFloat(country[2]));
                var zoom = parseInt(country[3]);
                if (this._map.GetMapMode() == VEMapMode.Mode3D) {
                    this._map.SetPitch(-90); // Neigung zurücksetzen
                    this._map.SetHeading(0); // Kompassrichtung zurücksetzen
                }
                this._map.SetCenterAndZoom(focus, zoom);
            }
            else {
                alert("Error during zooming.");
            }
        }

    },

    // Button "LinkButtonShowMinimap"
    // zeigt Minimap
    _showMiniMap: function() {
        this._map.ShowMiniMap(586, 359);
    },

    // Button "LinkButtonHideMinimap"
    // versteckt Minimap
    _hideMiniMap: function() {
        this._map.HideMiniMap();
    },

    // "DropDownListLocations"
    // legt this._firmenname für Webserviceaufruf "_getLocations" fest
    _setFirmenname: function() {
        var selectedFirma = document.getElementById("DropDownListLocations").selectedIndex;
        this._firmenname = document.getElementById("DropDownListLocations")[selectedFirma].value; ;
        this._bereich = "-1";
        this._getLocations();
    },

    // "DropDownListBereich"
    // legt this._bereich für Webserviceaufruf "_getLocations" fest
    _setBereich: function() {
        var selectedBereich = document.getElementById("DropDownListBereich").selectedIndex;
        this._bereich = document.getElementById("DropDownListBereich")[selectedBereich].value;
        this._getLocations();
    },

    // Webserviceaufruf "GetVisiblePins"
    // holt Pushpininformationen aus Datenbank -> result -> Callbackfunktion "_onGetVisiblePinsSucceeded()"
    _getLocations: function() {
        var view = this._map.GetMapView();

        var topLeft = view.TopLeftLatLong;
        var bottomRight = view.BottomRightLatLong;
        var topRight = null;
        var bottomLeft = null;

        if (view.TopRightLatLong != null)
            topRight = view.TopRightLatLong;
        else
            topRight = new VELatLong(topLeft.Latitude, bottomRight.Longitude);

        if (view.BottomLeftLatLong != null)
            bottomLeft = view.BottomLeftLatLong;
        else
            bottomLeft = new VELatLong(bottomRight.Latitude, topLeft.Longitude);

        var zoom = this._map.GetZoomLevel();

        try {

            if (this._locationId != "-1") {
                this._service.GetPin(
                this._locationId,
                location_webResx._lng,
                Function.createDelegate(this, this._onGetVisiblePinsSucceeded));
            }
            else {
                this._service.GetVisiblePins(
                topLeft.Latitude,
                topLeft.Longitude,
                bottomRight.Latitude,
                bottomRight.Longitude,
                topRight.Latitude,
                topRight.Longitude,
                bottomLeft.Latitude,
                bottomLeft.Longitude,
                zoom, this._firmenname,
                this._bereich,
                location_webResx._lng,
                Function.createDelegate(this, this._onGetVisiblePinsSucceeded));
            }
        }
        catch (ex) {
            alert("Webservice is currently not available, \nplease try again later.");
        }
    },

    // Callbackfunktion des Webserviceaufrufs GetVisiblePins
    // Erzeugt VEShape vom Typ Pushpin aus result
    _onGetVisiblePinsSucceeded: function(result, context, operation) {

        this._standorteLayer.DeleteAllShapes();

        var shapes = new Array();
        if (result != null && result.length > 0) {
            for (var i = 0; i < result.length; i++) {
                // VEShape-Objekt mit Koordinaten für Pins
                var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(result[i].Loc.Lat, result[i].Loc.Lon));
                //shape.SetZIndex(2000, null);
                shape.SetZIndex(2000);
                shape.Id = result[i].Id;
                shape.SetDescription(result[i].Description);
                var icon = new VECustomIconSpecification();
                //icon.Image = "images/pushpins/pushpin_cd_conform.png"; // corporate design konform
                icon.Image = "images/pushpins/pushpin_xxs.png";
                icon.ImageOffset = new VEPixel(0, -10);
                //icon.ImageOffset = new VEPixel(-10, -32);
                icon.TextContent = " "; //BugFix BLANK
                shape.SetCustomIcon(icon);
                shapes.push(shape);
            }
            this._standorteLayer.AddShape(shapes);
            this._visibleResultSet = result;
            
            if (this._locationId != "-1" && shapes.length == 1) {
                this._zoomToTuevPushpin(shapes[0].Id);
                this._locationId = "-1";
            }
        }
    },

    // Mausklick auf PushPin
    // Heranzoomen, Daten des angeklickten PushPins über Webservice holen
    _mouseclickhandler: function(e) {
        if (this._standorteLayer != null) {

            if (this._map.GetShapeByID(e.elementID) != null) {
                var wantedShape = this._map.GetShapeByID(e.elementID);

                var wantedClusterArea = null;


                // Bei TÜV Pushpins (GUID = "1001")
                if (wantedShape.guid.substring(7, 11) == "1001") {

                    this._zoomToTuevPushpin(wantedShape.Id);

                }
                // Andere Pushpins (z.B. Routenplaner)
                else {
                    wantedClusterArea = new Array();

                    currentClusterArea = new VELatLong(wantedShape.Latitude, wantedShape.Longitude);
                    wantedClusterArea.push(currentClusterArea);
                    this._setMapViewByShapes(wantedClusterArea, singleZoomlevel);
                }
            }
        }
    },

    _zoomToTuevPushpin: function(pushpinId) {

        var wantedClusterArea = null;
        var otherPinLoc = null; //andere Pins, die im geclusterten Pin enthalten sind
        var singleZoomlevel = -1; // enthält zoomlevel eines einzelnen Pushpins

        // Um alle geclusterten Pins auf der Karte sehen zu können, 
        // wird die NW und SE Position des Clustered Arrays benötigt.
        for (var i = 0; i < this._visibleResultSet.length; i++) {
            if (pushpinId == this._visibleResultSet[i].Id) {

                wantedClusterArea = new Array();

                //Koordinaten für die Routen in die entsprechenden Variablen schreiben
                this.tuevLocationLat = this._visibleResultSet[i].Loc.Lat;
                this.tuevLocationLong = this._visibleResultSet[i].Loc.Lon;

                // Standortdetail über Webservice aus DB holen für das Anzeigen im Routenfeld (Route nach)
                this._service.GetLocationDetail(pushpinId, this.OnGotLocationDetail);

                for (var iOtherLoc = 0; iOtherLoc < this._visibleResultSet[i].OtherPinLoc.length; iOtherLoc++) {
                    if (this._visibleResultSet[i].OtherPinLoc.length == 1) { // Wenn nur noch 1 Pushpin über ist, Zoomlevel in "singleZoomLevel" speichern
                        singleZoomlevel = this._visibleResultSet[i].Zoomlevel;
                    }
                    otherPinLoc = new VELatLong(this._visibleResultSet[i].OtherPinLoc[iOtherLoc].Lat, this._visibleResultSet[i].OtherPinLoc[iOtherLoc].Lon);
                    wantedClusterArea.push(otherPinLoc);
                }

                this._setMapViewByShapes(wantedClusterArea, singleZoomlevel);
            }
        }


    },

    _setMapViewByShapes: function(shapes, singleZoomLevel) {
        if (shapes != null) {
            if (shapes.length == 1 && singleZoomLevel >= 0) {
                this._map.SetCenterAndZoom(new VELatLong(shapes[0].Latitude, shapes[0].Longitude), singleZoomLevel);
            }
            else {
                this._map.SetMapView(shapes);
            }
        }
    },

    // Callbackfunktion des Webserviceaufrufs GetLocationDetail
    // Füllt Zielort (Routenplaner) und Hiddenfields mit Details des angeklickten PushPins
    _onGetLocationSucceeded: function(result, context, operation) {
        document.getElementById("TextBoxStandort").value = result.Name + "\r\n" + result.Street + "\r\n" + result.Areacode + " " + result.City + "\r\n" + result.CountryName;
        document.getElementById("HiddenFieldStandortName").value = result.Name;
        document.getElementById("HiddenFieldStandortStr").value = result.Street;
        document.getElementById("HiddenFieldStandortPlz").value = result.Areacode;
        document.getElementById("HiddenFieldStandortOrt").value = result.City;
        document.getElementById("HiddenFieldStandortLand").value = result.CountryName;

        switchElements("showRoutefinder", "showFinder", RouteOrFinderSwitch);
    },

    // Button "Route"
    // prüft Formularfelder, berechnet Route
    _routeHandler: function() {
        var textboxStr = document.getElementById("TextBoxZielStr");
        var textboxPlz = document.getElementById("TextBoxZielPlz");
        var textboxOrt = document.getElementById("TextBoxZielOrt");
        var textboxLand = document.getElementById("TextBoxZielLand");
        var dropDownListCountry = document.getElementById("DropDownListCountry");

        var options = null;

        // Überprüfung ob Standort angeklickt wurde
        if (this.tuevLocationLat != null) {

            this.nach = "";

            // Überprüfung der Formularfelder (leer, Tipp, normaler Inhalt, Komma setzen)
            if (((textboxStr.value != "") && (textboxStr.value != location_webResx.txt_Street)) || ((textboxPlz.value != "") && (textboxPlz.value != location_webResx.txt_Areacode)) || ((textboxOrt.value != "") && (textboxOrt.value != location_webResx.txt_City))) {

                this.nach = "";

                if ((textboxStr.value != "") && (textboxStr.value != location_webResx.txt_Street)) {
                    this.nach += textboxStr.value;
                }

                if ((textboxPlz.value != "") && (textboxPlz.value != location_webResx.txt_Areacode)) {
                    if (this.nach != "") {
                        this.nach += ", " + textboxPlz.value;
                    }
                    else {
                        this.nach += textboxPlz.value;
                    }
                }

                if ((textboxOrt.value != "") && (textboxOrt.value != location_webResx.txt_City)) {
                    if (this.nach != "") {
                        this.nach += ", " + textboxOrt.value;
                    }
                    else if (textboxPlz.value != "") {
                        this.nach += " " + textboxOrt.value;
                    }
                    else {
                        this.nach += textboxOrt.value;
                    }
                }


                if (textboxLand.value == location_webResx.txt_Country && dropDownListCountry[dropDownListCountry.selectedIndex].text != location_webResx.txt_World) {
                    textboxLand.value = dropDownListCountry[dropDownListCountry.selectedIndex].text;
                }

                if (textboxLand.value != "" && textboxLand.value != location_webResx.txt_Country) {
                    if (this.nach == "") {
                        this.nach += textboxLand.value;
                    }
                    else {
                        this.nach += ", " + textboxLand.value;
                    }
                }

                this.tuevLocation = new VELatLong(this.tuevLocationLat, this.tuevLocationLong);

                // VERouteOptions erzeugen und Optionen für Route festlegen
                options = new VERouteOptions();
                options.RouteCallback = this.OnGotRoute;
                options.ShowDisambiguation = true;
                options.UseTraffic = true;
                options.SetBestMapView = true;
                options.DistanceUnit = VERouteDistanceUnit.Kilometer;


                // Status von Buttons ändern
                document.getElementById("ButtonRoute").disabled = true;
                document.getElementById("ButtonRoute").value = location_webResx.txt_calculating;
                document.getElementById("ButtonRouteReset").value = location_webResx.txt_Cancel;

                if (this._map.GetMapMode() == VEMapMode.Mode3D) {
                    this._map.SetPitch(-90); // Neigung zurücksetzen
                    this._map.SetHeading(0); // Kompassrichtung zurücksetzen
                }

                // Routeanfrage an _map-Objekt
                if (document.getElementById("RadioButtonNach").checked) {
                    this._map.GetDirections([this.tuevLocation, this.nach], options);
                }
                else if (document.getElementById("RadioButtonVon").checked) {
                    this._map.GetDirections([this.nach, this.tuevLocation], options);
                }
            }

            else {
                if (document.getElementById("RadioButtonNach").checked) {
                    alert(location_webResx.txt_NoDestination_msg);
                }
                if (document.getElementById("RadioButtonVon").checked) {
                    alert(location_webResx.txt_NoStartingPoint_msg);
                }
            }
        }

        else {
            alert(location_webResx.txt_NoLocation_msg);
            return false;
        }

    },

    // Callbackfunktion vom _routeHandler
    _onGotRoute: function(route) {

        if (route != null) {
            this.optimalRouteLatLong = this._map.GetCenter();
            this.optimalRouteZoom = this._map.GetZoomLevel();

            var stringDistanceUnit = "km";

            // Gesamtlänge der Route in Hiddenfield schreiben (wird für Druckergebnis benötigt)
            document.getElementById("HiddenFieldDistance").value = route.Distance.toFixed(2);

            // Label von/nach setzen
            this._vonNachHandler();

            // Unroll route
            var legs = route.RouteLegs;


            document.getElementById("HiddenFieldTime").value = route.Time; // Time setzen

            // Gesamtdauer
            var timeArray = secToTime(route.Time);
            var gesamtZeitString = timeArray.toString;


            var turns = "<input type='button' id='btn_drucken' style='margin-bottom: 5px;' value='" + location_webResx.txt_Print + "' onclick='printRoute(" + this.tuevLocationLat + "," + this.tuevLocationLong + ");'/>"
            turns += "<input type='button' id='btn_gesamteRoute' style='margin-bottom: 5px;' value='" + location_webResx.txt_Whole_Route + "' onclick='map._getOptimalRoute();'/>";
            turns += "<p class='menublock' style='margin: 0;'>" + location_webResx.txt_Distance_label + " " + route.Distance.toFixed(2) + " " + stringDistanceUnit + " ";
            turns += location_webResx.txt_Length_label + " " + gesamtZeitString + " </p>";
            turns += "<table id='ergebnisRoute' style='margin: 0; border: solid #dbdbda 1px; width: 100%; border-collapse: collapse;'>";

            var numTurns = 0;
            var leg = null;

            // Zusammenstellen der Wegbeschreibung
            for (var i = 0; i < legs.length; i++) {

                // Get this leg so we don't have to derefernce multiple times               
                leg = legs[i];  // Leg is a VERouteLeg object                                 

                // Unroll each intermediate leg               
                var turn = null;  // The itinerary leg                                 
                for (var j = 0; j < leg.Itinerary.Items.length; j++) {
                    turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object

                    var turnTimeArray = secToTime(turn.Time);

                    if (numTurns % 2 == 0) {
                        turns += "<tr style='background-color: #f1f1f0'>";
                    }
                    else {
                        turns += "<tr>";
                    }
                    if (numTurns > 0) {
                        turns += "<td style='padding-left: 5px;'>" + numTurns + "</td>";
                    }
                    else {
                        turns += "<td></td>";
                    }
                    if (turn.Distance != 0) {
                        turns += "<td style='padding-left: 5px;'><a class='routelink' href='javascript:map._showRoutePin(" + turn.LatLong.Latitude + "," + turn.LatLong.Longitude + ")'>" + turn.Text + " (" + turn.Distance.toFixed(2) + " " + stringDistanceUnit + " - ca. " + turnTimeArray.toString + ")</a></td>";
                    }
                    else {
                        turns += "<td style='padding-left: 5px;'><a class='routelink' href='javascript:map._showRoutePin(" + turn.LatLong.Latitude + "," + turn.LatLong.Longitude + ")'>" + turn.Text + "</a></td>";
                    }
                    turns += "</tr>";
                    numTurns++;
                }
            }
            turns += "</table>";

            // Route in DIV-Container ausgeben
            document.getElementById("routeErgebnis").innerHTML = turns;
        }
        // Status von Buttons ändern
        document.getElementById("ButtonRoute").disabled = false;
        document.getElementById("ButtonRoute").value = location_webResx.txt_Route;
        document.getElementById("ButtonRouteReset").value = location_webResx.txt_Reset;
    },
    // einzelnen Pushpin (Schritt) einer Route zeigen (Link aus Routenbeschreibung)
    _showRoutePin: function(wantedLat, wantedLong) {
        var wantedLatLong = null;

        if ((wantedLat != null || wantedLat != "") && (wantedLong != null || wantedLong != "")) {

            if (this._map.GetMapMode() == VEMapMode.Mode3D) {
                this._map.SetPitch(-90); // Neigung zurücksetzen
                this._map.SetHeading(0); // Kompassrichtung zurücksetzen
            }
            
            wantedLatLong = new VELatLong(wantedLat, wantedLong);
            this._map.SetCenterAndZoom(wantedLatLong, 15);
            window.scrollTo(0, 0);
            if (this._map.GetMapStyle() != VEMapStyle.Shaded && this._map.GetMapStyle() != VEMapStyle.Road) {
                this._map.SetMapStyle(VEMapStyle.Shaded);
                alert(location_webResx.txt_SwitchedToRoadView_msg);
            }
        }
    },

    // Optimale Position/Zoom für Route
    _getOptimalRoute: function() {
        this._map.SetCenterAndZoom(this.optimalRouteLatLong, this.optimalRouteZoom);
    },

    // Button "Zurücksetzen"
    // setzt Variablen und Formularfelder zurück
    _resetRoute: function() {

        if (document.getElementById("ButtonRoute").disabled == false) {

            this.tuevLocationLat = null;
            this.tuevLocationLong = null;
            this.nach = null;
            document.getElementById("routeErgebnis").innerHTML = "";
            document.getElementById("TextBoxStandort").value = "";
            document.getElementById("TextBoxZielStr").value = location_webResx.txt_Street;
            document.getElementById("TextBoxZielPlz").value = location_webResx.txt_Areacode;
            document.getElementById("TextBoxZielOrt").value = location_webResx.txt_City;
            document.getElementById("TextBoxZielLand").value = location_webResx.txt_Country;
        }

        // Status von Buttons ändern
        document.getElementById("ButtonRoute").disabled = false;
        document.getElementById("ButtonRoute").value = location_webResx.txt_Route;
        document.getElementById("ButtonRouteReset").value = location_webResx.txt_Reset;

        this._map.DeleteRoute();
    },

    _findLocation: function() {
        var locationAddress = "";
        var textBoxFinderStreet = document.getElementById("TextBoxFinderStreet");
        var textBoxFinderAreacode = document.getElementById("TextBoxFinderAreacode");
        var textBoxFinderCity = document.getElementById("TextBoxFinderCity");
        var textBoxFinderCountry = document.getElementById("TextBoxFinderCountry");
        var dropDownListCountry = document.getElementById("DropDownListCountry");

        // Überprüfung der Formularfelder (leer, Tipp, normaler Inhalt, Komma setzen)
        if (((textBoxFinderStreet.value != "") && (textBoxFinderStreet.value != location_webResx.txt_Street))
                || ((textBoxFinderAreacode.value != "") && (textBoxFinderAreacode.value != location_webResx.txt_Areacode))
                || ((textBoxFinderCity.value != "") && (textBoxFinderCity.value != location_webResx.txt_City))
                || ((textBoxFinderCountry.value != "") && (textBoxFinderCountry.value != location_webResx.txt_Country))) {

            if ((textBoxFinderStreet.value != "") && (textBoxFinderStreet.value != location_webResx.txt_Street)) {
                locationAddress += textBoxFinderStreet.value;
            }

            if ((textBoxFinderAreacode.value != "") && (textBoxFinderAreacode.value != location_webResx.txt_Areacode)) {
                if (locationAddress != "") {
                    locationAddress += ", " + textBoxFinderAreacode.value;
                }
                else {
                    locationAddress += textBoxFinderAreacode.value;
                }
            }

            if ((textBoxFinderCity.value != "") && (textBoxFinderCity.value != location_webResx.txt_City)) {
                if (locationAddress != "") {
                    locationAddress += ", " + textBoxFinderCity.value;
                }
                else if (textBoxFinderAreacode.value != "") {
                    locationAddress += " " + textBoxFinderCity.value;
                }
                else {
                    locationAddress += textBoxFinderCity.value;
                }
            }


            if (textBoxFinderCountry.value == location_webResx.txt_Country && dropDownListCountry[dropDownListCountry.selectedIndex].text != location_webResx.txt_World) {
                textBoxFinderCountry.value = dropDownListCountry[dropDownListCountry.selectedIndex].text;
            }

            if (textBoxFinderCountry.value != "" && textBoxFinderCountry.value != location_webResx.txt_Country) {
                if (locationAddress == "") {
                    locationAddress += textBoxFinderCountry.value;
                }
                else {
                    locationAddress += ", " + textBoxFinderCountry.value;
                }
            }

            if (this._map.GetMapMode() == VEMapMode.Mode3D) {
                this._map.SetPitch(-90); // Neigung zurücksetzen
                this._map.SetHeading(0); // Kompassrichtung zurücksetzen
            }

            try {
                this._map.Find(null,    //What
                //adstreet + ", " + adcode + ", " + adcity + ", " + adcountry, //Where
                          locationAddress,
                          null,     //findType
                          null,     //shapeLayer
                          0,        //startIndex
                          10,       //numberOfResults
                          true,     //showResults
                          true,     //createResults
                          true,     //useDefaultDisambiguation 
                          true,     //setBestMapView
                          null); //callback

            }
            catch (e) {
                alert(e.message);
            }
        }
        else {
            alert(location_webResx.txt_NoFindLocation_msg);
        }

    },

    _resetFinder: function() {
        document.getElementById("TextBoxFinderStreet").value = location_webResx.txt_Street;
        document.getElementById("TextBoxFinderAreacode").value = location_webResx.txt_Areacode;
        document.getElementById("TextBoxFinderCity").value = location_webResx.txt_City;
        document.getElementById("TextBoxFinderCountry").value = location_webResx.txt_Country;
        // Status von Buttons ändern
        //document.getElementById("ButtonRoute").disabled = false;
        //document.getElementById("ButtonRoute").value = location_webResx.txt_Route;
        //document.getElementById("ButtonRouteReset").value = location_webResx.txt_Reset;
        this._showCountry();
    },

    // RadioButtonVon, RadioButtonNach
    // passt Label im Bereich des Routenplaners an
    _vonNachHandler: function() {
        if (document.getElementById("RadioButtonNach").checked) {
            document.getElementById("LabelVon").innerText = location_webResx.txt_from_label;
            document.getElementById("LabelNach").innerText = location_webResx.txt_Route_destination_label;
        }
        if (document.getElementById("RadioButtonVon").checked) {
            document.getElementById("LabelVon").innerText = location_webResx.txt_to_label;
            document.getElementById("LabelNach").innerText = location_webResx.txt_Route_startpoint_label;
        }
    },
    // Formularfelder: TextBoxZielOrt, TextBoxZielPlz, TextBoxZielStr
    // Werden bei Mausklick "geleert", wenn der Inhalt dem boxTip entspricht (z.B. "Straße" "Plz" "Ort")
    _textboxZielClickHandler: function(wantedTextbox, boxTip) {
        if (wantedTextbox.value == boxTip) {
            wantedTextbox.value = "";
        }
    },
    // Formularfelder: TextBoxZielOrt, TextBoxZielPlz, TextBoxZielStr
    // Werden bei Verlassen mit boxTip gefüllt, wenn das Feld leer ist (z.B. "Straße" "Plz" "Ort")
    _textboxZielBlurHandler: function(wantedTextbox, boxTip) {
        if (wantedTextbox.value == "") {
            wantedTextbox.value = boxTip;
        }
    },
    Dispose: function() {

        if (this._map != null) {

            this._map.Dispose();
        }

        this._mapArgs = null;
        this._map = null;
        this._standorteLayer = null;
        this._service = null;


    }
}

tn_standorte.Map.registerClass('tn_standorte.Map', null, Sys.IDisposable);

if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

// Route drucken
// holt Elemente, die die Route betreffen, erzeugt Popup, ruft Druckdialog auf, schließt Fenster
function printRoute(latitude, longitude) {
    var route = document.getElementById("ergebnisRoute");
    var standortName = document.getElementById("HiddenFieldStandortName");
    var entfernung = document.getElementById("HiddenFieldDistance");
    var dauer = document.getElementById("HiddenFieldTime");
    var standortStr = document.getElementById("HiddenFieldStandortStr");
    var standortPlz = document.getElementById("HiddenFieldStandortPlz");
    var standortOrt = document.getElementById("HiddenFieldStandortOrt");
    var standortLand = document.getElementById("HiddenFieldStandortLand");
    
    var stringDistanceUnit = "km";
    
    var timeArray = secToTime(dauer.value);
    var stringTimeValue = timeArray.toString;
    
    var w = window.open('', 'popup', 'width=800,height=600,scrollbars=yes');

    var latLongStrings = getLatLongStrings(latitude, longitude);
    
    with (w.document) {
        open();
        write(""
        + "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
        + "<html xmlns='http://www.w3.org/1999/xhtml'>"
        + "<head>"
        + "<link href='style/tuevnord_print.css' rel='stylesheet' type='text/css' />"
        + "</head>"
        + "<body style='background-image: none; background-color: #ffffff;' onload='window.print();'>"
        + "<div style='width: 100%; text-align: right;'><img src='images/tuev_logo.gif' alt='tuev_logo' /></div>"
        + "<table style='font-family: Arial; font-size: 10pt; margin-left: 10px;'>"
        + "<tr>"
        + "<td style='border: 0px;' colspan='2'>"
        + "<input type='button' value='" + location_webResx.txt_Print + "' onclick='window.print();'/>"
        + "<input type='button' value='" + location_webResx.txt_Close + "' onclick='window.close();'/><br/>"
        + "<p class='textblockheader'>" + location_webResx.txt_Route_Finder + "</p>"
        + "<span class='menuboxHead' style='width: 100%;'>" + location_webResx.txt_Your_route_label+" " + standortName.value + "</span>"
        + "</td>"
        + "</tr>"
        + "<tr>"
        + "<td style='border: 0px;' colspan='2' style='padding-left: 0px; padding-right: 0px;'>"

        + "<table class='routeDetails' style='width: 100%;'>"
        + "<tr>"

        + "<td>"
        + "<p class='menublock'>"
        + standortStr.value + "<br/>"
        + standortPlz.value + " " + standortOrt.value + "<br/>"
        + standortLand.value
        + "</p>"
        + "</td>"

        + "<td style='padding-right: 0px;'>"
        + "<p class='menublock' style='text-align: right;'>"
        + "<img src='images/windrose.gif' alt='windrose'/>"
        + "</p>"
        + "</td>"

        + "<td style='padding-left: 2px;'>"
        + "<p class='menublock' style='text-align: left;'>"
        + location_webResx.txt_Geocodes_label + "<br/>" + latLongStrings.LatitudeString + "<br/>" + latLongStrings.LongitudeString
        + "</p>"
        + "</td>"

        + "<td>"
        + "<p class='menublock'>"
        + location_webResx.txt_Distance_label + " " + entfernung.value + " " + stringDistanceUnit + "<br/>"
        + location_webResx.txt_Length_label + " " + stringTimeValue
        + "</p>"
        + "</td>"

        + "</tr>"
        + "</table>"

        + "</td>"
        + "</tr>"
	    + route.innerHTML + '</table><br/>'
	    + '</body></html>'
	    );
        close();
    }
}

// rechnet Sekunden in Tage, Stunden, Minuten, Sekunden um 
// gibt ein Assoziatives Array zurück
function secToTime(sec) {

    //var gesamt = route.Time * 1000;
    var gesamt = sec * 1000;

    var tage = Math.floor(gesamt / (24 * 3600 * 1000));
    var stunden = Math.floor((gesamt - 24 * 3600 * 1000 * tage) / (3600 * 1000));
    var minuten = Math.floor((gesamt - 24 * 3600 * 1000 * tage - 3600 * 1000 * stunden) / (60 * 1000));
    var sekunden = Math.round((gesamt - 24 * 3600 * 1000 * tage - 3600 * 1000 * stunden - 60 * 1000 * minuten) / 1000);

    var time = new Array();
    
    time = new Object();
    time["days"] = tage;
    time["hrs"] = stunden;
    time["mins"] = minuten;
    time["secs"] = sekunden;
    time["toString"] = "";
    // "Tage" nur anzeigen wenn mehr als 0
    if (tage > 0) {
        time["toString"] += tage + "d ";
    }
    // "Stunden" nur anzeigen wenn mehr als 0
    if (stunden > 0) {
        // Führende "0" anfügen
        if (stunden < 10 && tage > 0) {
            stunden = "0" + stunden;
        }
        time["toString"] += stunden + "h ";
    }

    // Führende "0" anfügen
    if (minuten < 10 && stunden > 0) {
        minuten = "0" + minuten; 
    }
    if (sekunden < 10) {
        sekunden = "0" + sekunden;
    }    

    time["toString"] += minuten + "m " + sekunden + "s"; 

    return time;
}

// Liefert korrekte Strings für Längen-/Breitengrade
// Latitude < 0 = S | Latitude >= 0 = N
// Longitude < 0 = W | Longitude >= 0 = W
function getLatLongStrings(latitude, longitude) {
    
    var latitudeString = "";
    var longitudeString = "";

    var returnObject = null;
    
    try {
        latitude = parseFloat(latitude);
        longitude = parseFloat(longitude);
        returnObject = new Object();
    }
    catch (ex) {

    }

    if (latitude < 0) {
        latitudeString = "S " + (latitude.toFixed(2)*-1) + "°";
    }
    else if (latitude >= 0) {
        latitudeString = "N " + latitude.toFixed(2) + "°";
    }

    if (longitude < 0) {
        longitudeString = "W " + (longitude.toFixed(2)*-1) + "°";
    }
    else if (longitude >= 0) {
        longitudeString = "E " + longitude.toFixed(2) + "°";
    }
    returnObject["LatitudeString"] = latitudeString;
    returnObject["LongitudeString"] = longitudeString;

    return returnObject;

}
