﻿/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is VisKort.
*
* The Initial Developer of the Original Code is
* IT- og Telestyrelsen / Danish National IT and Telecom Agency.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):

* Lars Klindt Mogensen
* Morten Bødtkjer
* Niels Kinnerup
* Thomas Bergstedt
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */

/**
* Class: VisKort.Component.Route
* 
* This class represents searchaddress. The method activate must be called when a 
* a instance is made, so that the needed address marker layer is initiales with the  
* needed events.
*/
VisKort.Component.Route = OpenLayers.Class(VisKort.Component, {

    /** 
    * Property: routeplan_Layer
    * {<OpenLayers.Layer.Vector>} vector layer for drawing of route  
    */
    routeplan_Layer: null,

    /** 
    * Property: route_marker_layer
    * {<OpenLayers.Layer.Markers>} route marker layer  
    */
    route_marker_layer: null,

    /** 
    * Property: icon_start_marker
    * {<OpenLayers.Icon>} start_route_icon  
    */
    icon_start_marker: null,

    /** 
    * Property: icon_end_marker
    * {<OpenLayers.Icon>} stop_route_icon  
    */
    icon_end_marker: null,

    /** 
    * Property: address_start
    * {<String>} From address  
    */
    address_start: null,

    /** 
    * Property: address_end
    * {<String>} End address  
    */
    address_end: null,

    /** 
    * Property: start_end_marker
    * {<OpenLayers.Marker>} Start and end marker for route
    */
    start_end_marker: null,

    /** 
    * Property: route_boundingbox
    * {<OpenLayers.Bounds>} Boundingbox for route
    */
    route_boundingbox: null,

    /** 
    * Constructor: VisKort.Component.Route
    */
    initialize: function() {

    },

    /**
    * Method: startup
    * Use this if something needs to be Initialize on startup
    */
    startup: function() {

    },

    /** 
    * Method: activate
    * Things to do when activated. If layers need initials the layers are
    * added again
    */
    activate: function() {
        if (!this.route_marker_layer) {
            this.loadData();
        }
    },

    /** 
    * Method: deActivate
    * Gets called when the tab for this class is unselected
    * Destoyes markers and route vector
    */
    deActivate: function() {
        if (this.route_marker_layer) {
            this.RemoveRuteMarkers();
        }
        if (this.routeplan_Layer) {
            this.routeplan_Layer.removeFeatures(this.routeplan_Layer.features);
        }

        var util_instance = new VisKort.Utils();
        util_instance.ResetPrintInfo();
    },

    /**
    * Method: loadData
    * Initialize the layers to use for route
    */
    loadData: function() {

        var size = new OpenLayers.Size(21, 25);
        var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);

        this.icon_start_marker = new OpenLayers.Icon('/Viskort/App_Themes/' + this.application.active_theme + '/Images/OpenLayers/Routeware_start.png', size, offset);
        this.icon_end_marker = new OpenLayers.Icon('/Viskort/App_Themes/' + this.application.active_theme + '/Images/OpenLayers/Routeware_stop.png', size, offset);

        this.route_marker_layer = new OpenLayers.Layer.Markers("RuteAdresse", { displayInLayerSwitcher: false });

        this.map.addLayer(this.route_marker_layer);

        this.routeplan_Layer = new OpenLayers.Layer.Vector("Ruteplan", { displayInLayerSwitcher: false });
        this.map.addLayer(this.routeplan_Layer);
    },

    /**
    * Method: Reset_Route_Info
    * Resets the route tab to default except the address fields
    */
    Reset_Route_Info: function() {
        try {
            var fromDIV = document.getElementById(from_div);
            fromDIV.innerHTML = "<br />Indtast en fra/til adresse og klik på \"find rute\"." +
            "<br /><br />Du kan indtaste en fuldstændig adresse eller blot dele af en. <br />" +
            "Eksempler herpå er hhv<br /><br /><i>Bredgade 10, 1260 København og<br />" +
            "Smallegade 35<br /></i><br />";
            var to_DIV = document.getElementById(to_div);
            to_DIV.innerHTML = "";
            var adrFromHF = document.getElementById(addressFrom);
            adrFromHF.value = "";
            var adrToHF = document.getElementById(addressTo);
            adrToHF.value = "";
            var adrFR = document.getElementById(found_Result);
            adrFR.value = "";
            var printCont = document.getElementById(print_container);
            printCont.style.visibility = "hidden";
        } catch (e) {
        }
    },

    /**
    * Method: Set_Route_From 
    * Used when one address is found but the other still needs to be found 
    * Parameters:
    * adr - <String> fromaddress
    */
    Set_Route_From: function(adr) {
        new VisKort.Utils().disableStandardLayers(viskort.components['address'].map);
        var fromText = document.getElementById(from_textbox)
        fromText.value = adr;
        var adrFromHF = document.getElementById(addressFrom);
        adrFromHF.value = "";

        var to_DIV = document.getElementById(to_div);
        to_DIV.innerHTML = "";
        var fromDIV = document.getElementById(from_div);
        fromDIV.innerHTML = "<br />Indtast en fra/til adresse og klik på \"find rute\"." +
            "<br /><br />Du kan indtaste en fuldstændig adresse eller blot dele af en. <br />" +
            "Eksempler herpå er hhv<br /><br /><i>Bredgade 10, 1260 København og<br />" +
            "Smallegade 35<br /></i><br />";
        var printCont = document.getElementById(print_container);
        printCont.style.visibility = "hidden";
        var util_instance = new VisKort.Utils();
        util_instance.ResetPrintInfo();
    },

    /**
    * Method: Set_Route_From 
    * Used when one address is found but the other still needs to be found 
    * Parameters:
    * adr - <String> toaddress
    */
    Set_Route_To: function(adr) {
        new VisKort.Utils().disableStandardLayers(viskort.components['address'].map);
        var toText = document.getElementById(to_textbox);
        toText.value = adr;
        var adrFromHF = document.getElementById(addressFrom);
        adrFromHF.value = "";

        var to_DIV = document.getElementById(to_div);
        to_DIV.innerHTML = "";
        var fromDIV = document.getElementById(from_div);
        fromDIV.innerHTML = "<br />Indtast en fra/til adresse og klik på \"find rute\"." +
            "<br /><br />Du kan indtaste en fuldstændig adresse eller blot dele af en. <br />" +
            "Eksempler herpå er hhv<br /><br /><i>Bredgade 10, 1260 København og<br />" +
            "Smallegade 35<br /></i><br />";
        var printCont = document.getElementById(print_container);
        printCont.style.visibility = "hidden";
        var util_instance = new VisKort.Utils();
        util_instance.ResetPrintInfo();
    },

    /**
    * Method: CreateRuteMarker
    * Creates route marker depending on which type specified
    *
    * Parameters: 
    * type - <Int> 0- any number
    * east_x - <Number> UTM32 Easting coordinate 
    * north_y - <Number> UTM32 Northing coordinate
    */
    CreateRuteMarker: function(type, east_x, north_y) {
        if (type == 0) {
            this.start_end_marker = new OpenLayers.Marker(new OpenLayers.LonLat(east_x, north_y), this.icon_start_marker);
            this.route_marker_layer.addMarker(this.start_end_marker);
        } else {
            this.start_end_marker = new OpenLayers.Marker(new OpenLayers.LonLat(east_x, north_y), this.icon_end_marker);
            this.route_marker_layer.addMarker(this.start_end_marker);
        }
    },

    /**
    * Method: RemoveRuteMarkers
    * Clears the route markers from map. 
    */
    RemoveRuteMarkers: function() {
        try {
            this.route_marker_layer.clearMarkers();
        } catch (err) {
        }
    },

    /**
    * Method: RouteEndAddressSearch
    * Initialize the handler for return of the UpdatePanel_Routebox_1 asyncron postback
    */
    RouteEndAddressSeach: function() {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.EndRequestHandlerRoute);
    },

    /**
    * Eventhandler: EndRequestHandlerRoute
    * Handles endrequest for asycronpost for route finding
    */
    EndRequestHandlerRoute: function(sender, args) {
        var adFrom = document.getElementById(addressFrom);
        var adTo = document.getElementById(addressTo);
        var foundResult = document.getElementById(found_Result);

        if (args.get_error() == undefined && (adFrom.text != "" || adTo.text != "")) {
            var pmFrom = adFrom.value.split("#");
            var pmTo = adTo.value.split("#");
            // Is the route found
            if (foundResult.value != "") {
                // Set textbox and header
                viskort.components['route'].SetRoutePlan(pmFrom[0].split(":"), pmTo[0].split(":"), pmFrom[1], pmFrom[2], pmTo[1], pmTo[2]);
                // Clear hiddenfieldValue
                adFrom.value = "";
                adTo.value = "";
                foundResult.value = "";
            } else {
                // Start address search_type
                if (pmFrom.length == 7) {
                    viskort.components['route'].SetRouteAddress(pmFrom[0], pmFrom[1], pmFrom[2], pmFrom[3], pmFrom[4], pmFrom[5], pmFrom[6]);
                }
                // End address search_type
                if (pmTo.length == 7) {
                    viskort.components['route'].SetRouteAddress(pmTo[0], pmTo[1], pmTo[2], pmTo[3], pmTo[4], pmTo[5], pmTo[6]);
                }

                // Start place search_type
                if (pmFrom.length == 4) {
                    viskort.components['route'].SetRoutePlace(pmFrom[0], pmFrom[1], pmFrom[2], pmFrom[3]);
                }
                // End place search_type
                if (pmTo.length == 4) {
                    viskort.components['route'].SetRoutePlace(pmTo[0], pmTo[1], pmTo[2], pmTo[3]);
                }
            }
        }
        if (args.get_error() && args.get_error().name === 'Sys.WebForms.PageRequestManagerTimeoutException') {
            // Sets errorHandled = true to avoid an error message box from the AJAX library
            args.set_errorHandled(true);
        }
    },

    /**
    * Method: EnterKeypress_route
    * Keypressdown event for address from and to textbox
    *
    * Parameters:
    * buttonName -<ID>
    * e - <Event>
    */
    EnterKeypress_route: function(buttonName, e) {

        if (e.which || e.keyCode) {
            if ((e.which == 13) || (e.keyCode == 13)) {
                var btn2 = document.getElementById(buttonName);

                try {

                    btn2.click();
                    Event.stop(e);
                } catch (err) {

                }
                return false;
            }
            else {
                return true;
            }
        }
    },

    EnterKeypress_route2: function(buttonName, e) {
        if (e.which || e.keyCode) {
            if ((e.which == 13) || (e.keyCode == 13)) {
                var btn2 = document.getElementById(buttonName);

                try {

                    btn2.click();
                    Event.stop(e);
                } catch (err) {

                }
                return false;
            }
            else {
                return true;
            }
        }
    },

    /**
    * Method: SetInfoToPrint
    * Sets the route info to print
    *
    * Parameters:
    * routeInfo - <String> Generel route info
    * routedesp - <String> Travel description
    * list_of_route_coordinats - <String> ':'sperated list of north/easting coordinats
    * theme - <String> Name of theme 
    */
    SetRouteInfoToPrint: function(routeInfo, routedesp, list_of_route_coordinats, theme) {
        var util_instance = new VisKort.Utils();
        // Reset printinfo
        util_instance.ResetPrintInfo();
        // Set printinfo
        util_instance.SetPrintInfo(routeInfo);

        util_instance.SetPrintDetailInfo(routedesp);
        var print_coordinat = document.getElementById("print_marker_coordinats");
        if (print_coordinat) {
            print_coordinat.innerHTML = theme + ":";
            print_coordinat.innerHTML += list_of_route_coordinats;
        }
    },

    /**
    * Method: Drawrute
    * Draws a route from a liste of points
    *
    * Parameters: 
    * route_x_y - <String> ':'sperated list of north/easting points 
    */
    DrawRute: function(route_x_y) {
        var print_route = "";
        if (this.application.pagemode == "popup") {
            var print_cointainer = document.getElementById(print_container);
            if (print_cointainer) {
                print_cointainer.style.visibility = "visible";

                var from_adr = document.getElementById(from_textbox).value;
                var to_adr = document.getElementById(to_textbox).value;
                this.CreateLink_to_Travelplan(from_adr, to_adr, print_cointainer);
                print_route = "Fra adresse: " + from_adr + "<br />Til adresse: " + to_adr;
            }
        }

        // Set printinfo
        var route_desp = document.getElementById(from_div);
        if (route_desp) {

            this.SetRouteInfoToPrint(print_route, route_desp.innerHTML, route_x_y, this.application.active_theme);
        }

        // Remove old routeplan if any
        this.RemoveRuteMarkers();
        this.routeplan_Layer.removeFeatures(this.routeplan_Layer.features);

        var points = route_x_y.split(":");

        if (points.length > 1) {
            try {
                this.CreateRuteMarker(0, points[0], points[1]);
                this.CreateRuteMarker(1, points[points.length - 2], points[points.length - 1]);
                var points_list = new Array();

                var lineList = new Array();
                var count = 0;
                var lineCount = 0;

                for (var i = 0; i < points.length; i += 2) {
                    points_list[count] = new OpenLayers.Geometry.Point(points[i], points[i + 1]);
                    count++;
                    if (count == 1000) {
                        lineList[lineCount] = new OpenLayers.Geometry.LineString(points_list);
                        lineCount++;
                        points_list = new Array();
                        count = 0;
                        points_list[count] = new OpenLayers.Geometry.Point(points[i - 2], points[i - 1]);
                        count++;
                    }
                }

                lineList[lineCount] = new OpenLayers.Geometry.LineString(points_list);

                var ruteplan_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
                ruteplan_style.fillOpacity = 0.5;
                ruteplan_style.graphicOpacity = 1;

                var style_blue = OpenLayers.Util.extend({}, ruteplan_style);
                style_blue.strokeColor = "blue";
                style_blue.fillColor = "blue";
                style_blue.strokeWidth = "3"

                var rute_line_feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiLineString(lineList), null, style_blue);

                this.routeplan_Layer.addFeatures(rute_line_feature);
                this.routeplan_Layer.numZoomLevels = "11;"
                this.routeplan_Layer.setVisibility(true);
                this.route_marker_layer.setVisibility(true);
                this.route_boundingbox = rute_line_feature.geometry.getBounds()

                this.FindzoomBounding();
            } catch (err) {

            }
        }
    },

    /**
    * Method: ShowErrorMsgRouteIframe
    * Shows error msg when the address isn't unique or an error occurred
    *
    * Parameters:
    * address1 - <String>
    * address2 - <String>
    * ErrorMsg - <String>
    */
    ShowErrorMsgRouteIframe: function(address1, address2, errorMsg) {
        if (errorMsg == "") {
            alert("En eller begge adresser \"" + address1 + "\"\n\"" + address2 + "\" er ikke unikke.\nKlik på linket \"Vis i stort vindue\" for at se og vælge blandt de fundne adresser.");
        } else {
            alert("En eller begge adresser kunne ikke findes.\n" + errorMsg.toString().replace("<br/>", "\n") + "\nKlik på linket \"Vis i stort vindue\" for at rette søgningen til.");
        }
    },

    /*
    * Method: FindzoomBounding
    * Finds boundingbox for route vector and zoomes to it 
    */
    FindzoomBounding: function() {

        var extraWidth = this.route_boundingbox.getWidth() * 0.1;
        var extraHeight = this.route_boundingbox.getHeight() * 0.1;
        var maxExtentBounds = this.map.getMaxExtent();

        this.route_boundingbox.left = Math.max(this.route_boundingbox.left - extraWidth, maxExtentBounds.left);
        this.route_boundingbox.right = Math.min(this.route_boundingbox.right + extraWidth, maxExtentBounds.right);
        this.route_boundingbox.bottom = Math.max(this.route_boundingbox.bottom - extraHeight, maxExtentBounds.bottom);
        this.route_boundingbox.top = Math.min(this.route_boundingbox.top + extraHeight, maxExtentBounds.top);
        this.map.zoomToExtent(this.route_boundingbox);

    },

    /**
    * Method: SetRouteAddress
    * Sets infobox for address and startes finding the route if
    * the other address is found
    *
    * Parameters:
    * place_address - <String> streetname:nr:postal_identifer:postal_distict:municipality
    * east_coordinat - <Number> UTM32 Easting coordinat 
    * north_coordinat - <Number> UTM32 Northing coordinat
    * textbox - <ClientID>
    * from_to_call - <String> inidicats which addresspoint (start "1" or end "anything")
    * address_hiddenfield1 - <ClientID>
    * address_hiddenfield2 - <ClientID>
    */
    SetRouteAddress: function(place_address, east_coordinat, north_coordinat, textbox, from_to_call, address_hiddenfield1, address_hiddenfield2) {

        var streetname = ""
        var nr = ""
        var postal_identifer = "";
        var postal_district = "";
        var municipality = "";
        var elements = place_address.split(":");

        // Hidden_fields
        var addressfield = document.getElementById(address_hiddenfield1);
        var otheraddressfield = document.getElementById(address_hiddenfield2);

        if (elements.length == 5) {
            streetname = elements[0];
            nr = elements[1];
            postal_identifer = elements[2];
            postal_district = elements[3];
            municipality = elements[4];
        }

        // Set textseachBox      
        var address_textbox = document.getElementById(textbox);
        address_textbox.value = streetname + " " + nr + ", " + postal_identifer + " " + postal_district;

        // Make resultfield
        if (from_to_call == "1") {
            display_info = "<br /><div class='Route_Div_Result'><img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme + "/Images/OpenLayers/Routeware_start.png' /> \"Fra\" adresse: <br /> " + streetname + " " + nr + ",<br />" +
            postal_identifer + " " + postal_district + "<br /> </div>";
            display_div = document.getElementById(from_div);
            display_div.innerHTML = "";
            display_div.innerHTML = display_info;
            // Set hiddenfield
            addressfield.value = place_address + "#" +
            east_coordinat + "#" + north_coordinat + "#" + textbox + "#" + 1 + "#" + address_hiddenfield1 +
            "#" + address_hiddenfield2;
        } else {
            display_info = "<br /><div class='Route_Div_Result'><img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme + "/Images/OpenLayers/Routeware_stop.png' /> \"Til\" adresse: <br /> " + streetname + " " + nr + ",<br />" +
            postal_identifer + " " + postal_district + "<br /> </div>";
            display_div = document.getElementById(to_div);
            display_div.innerHTML = "";
            display_div.innerHTML = display_info;
            // Set hiddenfield
            addressfield.value = place_address + "#" +
            east_coordinat + "#" + north_coordinat + "#" + textbox + "#" + 0 + "#" + address_hiddenfield1 +
            "#" + address_hiddenfield2;
        }

        // Check for finished address search
        if (otheraddressfield.value != "") {
            var header_div = document.getElementById("HeaderInfo");
            var data1 = addressfield.value.split('#');
            var data2 = otheraddressfield.value.split('#');
            var toDiv = document.getElementById(to_div);

            if (from_to_call == "1") {
                header_div.innerHTML = "Aktuelt vises: Ruten";
                toDiv.innerHTML = "";
                this.SetRoutePlan(data1[0].split(":"), data2[0].split(":"), data1[1], data1[2], data2[1], data2[2]);
            }
            else {
                header_div.innerHTML = "Aktuelt vises: Ruten"
                toDiv.innerHTML = "";
                this.SetRoutePlan(data2[0].split(":"), data1[0].split(":"), data2[1], data2[2], data1[1], data1[2]);
            }
        }
    },

    /**
    * Method: SetRoutePlace
    * 
    * 
    * Parameters: 
    * place_address - <String> placename:municipality
    * easting_coordinat - <Number> UTM32 Easting coordinat 
    * northing_coodinat - <Number> UTM32 Northing coordinat
    * route_from - <String> inidicats which placepoint (start "fromadr" or end "toadr")
    */
    SetRoutePlace: function(place_address, easting_coordinat, northing_coordinat, route_from) {

        var placename = "";
        var municipality = "";
        var elements = place_address.split(":");
        if (elements.length == 2) {
            placename = elements[0];
            municipality = elements[1];
        }
        var addressfromhiddenfield = document.getElementById(addressFrom);
        var addressTohiddenfield = document.getElementById(addressTo);

        if (route_from == "fromadr") {
            var address_textbox = document.getElementById(from_textbox);
            address_textbox.value = placename;

            display_info = "<br /><div class='Route_Div_Result'><img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme + "/Images/OpenLayers/Routeware_start.png' /> \"Fra\" sted: <br /> " + placename + ", " + municipality + "<br /> </div>";
            display_div = document.getElementById(from_div);
            display_div.innerHTML = "";
            display_div.innerHTML = display_info;

            // Set hiddenfield       
            addressfromhiddenfield.value = place_address + "#" + easting_coordinat + "#" + northing_coordinat + "#" + route_from;
        }
        else {
            var address_textbox = document.getElementById(to_textbox);
            address_textbox.value = placename;

            display_info = "<br /><div class='Route_Div_Result'><img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme + "/Images/OpenLayers/Routeware_start.png' /> \"Til\" sted: <br /> " + placename + ", " + municipality + "<br /> </div>";
            display_div = document.getElementById(to_div);
            display_div.innerHTML = "";
            display_div.innerHTML = display_info;

            // Set hiddenfield
            addressTohiddenfield.value = place_address + "#" + easting_coordinat + "#" + northing_coordinat + "#" + route_from;
        }

        // Check for finished address search
        if (addressfromhiddenfield.value != "" && addressTohiddenfield.value != "") {
            var header_div = document.getElementById("HeaderInfo");
            var data1 = "";
            var data2 = "";
            header_div.innerHTML = "Aktuelt vises: Ruten";
            var toDiv = document.getElementById(to_div);
            toDiv.innerHTML = "";
            if (route_from == "fromadr") {
                data1 = addressfromhiddenfield.value.split('#');
                data2 = addressTohiddenfield.value.split('#');
                this.SetRoutePlan(data1[0].split(":"), data2[0].split(":"), data1[1], data1[2], data2[1], data2[2]);
            } else {
                data1 = addressTohiddenfield.value.split('#');
                data2 = addressfromhiddenfield.value.split('#');
                this.SetRoutePlan(data2[0].split(":"), data1[0].split(":"), data2[1], data2[2], data1[1], data1[2]);
            }
        }

    },

    /**
    * Method: SetRoutePlan
    * Finds the routeplan
    * 
    * Parameters:
    * addressFrom - <String> fromaddress data list
    * addressTo - <String> toaddress data list
    * from_east_x - <Number> UTM32 Easting coordinate
    * from_north_y - <Number> UTM32 Northing coordinate
    * to_east_x - <Number> UTM32 Easting coordinate
    * to_north_y - <Number> UTM32 Northing coordinate
    */
    SetRoutePlan: function(addressFrom, addressTo, from_east_x, from_north_y, to_east_x, to_north_y) {
        this.activate();
        var list = from_east_x + ":" + from_north_y + ":" + to_east_x + ":" + to_north_y;
        if (addressFrom.length == 2) {
            this.address_start = "<img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme +
            "/Images/OpenLayers/Routeware_start.png' />Fra <b>" + addressFrom[0] + " " + addressFrom[1] + "</b><br /><br />";
        } else {
            this.address_start = "<img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme +
            "/Images/OpenLayers/Routeware_start.png' />Fra <b>" + addressFrom[0] + " " + addressFrom[1] + " , <br />" + addressFrom[2] + " " + addressFrom[3] + "</b><br /><br />";
        }
        if (addressTo.length == 2) {
            this.address_end = "<img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme +
        "/Images/OpenLayers/Routeware_stop.png' />Til <b>" + addressTo[0] + " " + addressTo[1] + "</b><br /><br />";
        } else {
            this.address_end = "<img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme +
        "/Images/OpenLayers/Routeware_stop.png' />Til <b>" + addressTo[0] + " " + addressTo[1] + " , <br />" + addressTo[2] + " " + addressTo[3] + "</b><br /><br />";
        }

        display_div = document.getElementById(from_div);
        display_div.innerHTML = "";
        display_div.innerHTML = "Finder rute.....";

        this.RequestInfo(list);
    },

    /**
    * Method: CreateLink_to_Travelplan
    * Creates link to the "www.rejseplan.dk" with address to and from
    * 
    * Parameters: 
    * from_address - <String>
    * to_address - <String>
    * print_container - <ID> Div container
    */
    CreateLink_to_Travelplan: function(from_adress, to_address, print_container) {
        var travelplan = new VisKort.Utils.LinkGenerator.Rejseplanen("OneLink", false);
        var divElemTravelplan = travelplan.getDivElement({ fromAddress: from_adress, toAddress: to_address }, "Route_LinkTravel");
        print_container.appendChild(divElemTravelplan);
    },

    /**
    * Method: Print_Travel_Plan
    * Start a printdialog and a newpage with the contents of the "from_div" to print
    */
    Print_Travel_Plan: function() {
        var print_dialog_box = true;
        if (document.getElementById != null) {
            var newpage = '<HTML>\n<HEAD>\n';
            newpage += '\n</HEAD>\n<BODY class="Route_Print_Page" onfocus=window.close()>\n';

            var print_info = document.getElementById(from_div);

            if (print_info != null) {
                newpage += print_info.innerHTML;
            }
            else {
                // no info to print
                return;
            }

            newpage += '\n</BODY>\n</HTML>';

            var print_preview = window.open("", "print");
            print_preview.document.open();
            print_preview.document.write(newpage);
            print_preview.document.close();
            if (print_dialog_box) {
                print_preview.print();
            }
        }
        return;
    },

    /**
    * Method: GetXmlHttpRequest 
    * Creates a new XMLHttpRequest instance
    *
    * Returns:
    * <XMLHttpRequest> ajax request object
    */
    GetXmlHttpRequest: function() {
        var ajaxreq = false;
        if (window.XMLHttpRequest) {
            ajaxreq = new XMLHttpRequest();
        } // branch for IE/Windows ActiveX version
        else if (window.ActiveXObject) {
            ajaxreq = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return ajaxreq;
    },

    /**
    * Method: RequestInfo 
    * Handels ajax asyncron postback for address
    *
    * Parameters:
    * parameters - (String) arguments for request 
    */
    RequestInfo: function(parameters) {
        var ajaxreq = this.GetXmlHttpRequest();
        if (ajaxreq) {
            ajaxreq.onreadystatechange = function ProgressResponse() {
                if (ajaxreq.readyState == 4) {
                    if (ajaxreq.status == 200) {
                        var error
                        error = ajaxreq.responseXML.documentElement.getElementsByTagName("ERROR");
                        if (error.length == 0) {
                            try {
                                var dictionList = "";
                                nodes_diction = ajaxreq.responseXML.documentElement.childNodes[0].childNodes;
                                for (var j = 0; j < nodes_diction.length; j++) {
                                    dictionList += nodes_diction[j].nodeValue;
                                }
                                var pointsList = "";
                                nodes_coordinats = ajaxreq.responseXML.documentElement.childNodes[1].childNodes;
                                for (var i = 0; i < nodes_coordinats.length; i++) {
                                    pointsList += nodes_coordinats[i].nodeValue;
                                }
                                display_div = document.getElementById(from_div);
                                display_div.innerHTML = "";
                                display_div.innerHTML = "<b>Rutebeskrivelse</b><br /><br />" + viskort.components['route'].address_start + viskort.components['route'].address_end + dictionList;
                                viskort.components['route'].DrawRute(pointsList);
                            } catch (e) {

                            }
                        }
                        else {
                            display_div = document.getElementById(from_div);
                            display_div.innerHTML = "";
                            display_div.innerHTML = error[0].firstChild.nodeValue;
                        }
                    }
                }
            };
            var url = "ProxyRoute.ashx?parameters=" + parameters;
            ajaxreq.open("Get", url, true); //asyncron
            ajaxreq.send(null); // null for Firefox
        }
        else {
            alert("Kunne ikke oprette Ajax request");
        }
    },
    CLASS_NAME: "VisKort.Component.Route"
});
