﻿/* ***** 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.Address
* 
* 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.Address = OpenLayers.Class(VisKort.Component, {

	/** 
	* Property: address_markers_layer 
	* {<OpenLayers.Layer.Markers>} address marker layer  
	*/
	address_markers_layer: null,

	/** 
	* Property: icon_addressMarker  
	* {<OpenLayers.Icon>} address icon  
	*/
	icon_addressMarker: null,

	/**
	* Property: nearest_boundingbox 
	* {<OpenLayers.Bounds>} boundingbox for findnearest layer
	*/
	nearest_boundingbox: null,

	/** 
	* Property: listName  
	* {String} name of themes to find nearest on 
	*/
	listName: null,

	/** 
	* Property: marker  
	* {<OpenLayers.Marker>} address marker 
	*/
	marker: null,

	/** 
	* Property: ListOfFileNames  
	* {Array} array of name to show find nearest for  
	*/
	ListOfFileNames: new Array(),

	/**
	* Property: find_nearest_status
	* (bool) on/off findnearest
	*/
	find_nearest_status: 1,
	/** 
	* Constructor: VisKort.Component.Address
	*/
	initialize: function (find_nearst_on_off)
	{
		this.find_nearest_status = find_nearst_on_off;
	},

	/** 
	* Method: activate
	* Initiales the needed address layers to use
	*/
	activate: function ()
	{
		if (!this.address_markers_layer) {
			this.loadData();
		}
	},

	/** 
	* Method: deActivate
	* Gets called when the tab for this class is unselected
	*/
	deActivate: function ()
	{
		if (this.address_markers_layer) {
			this.ClearaddressMarkers();
		}
		var util_instance = new VisKort.Utils();
		util_instance.ResetPrintInfo();
	},

	/**
	* Method: loadData
	* Initials the needed layers for this class
	*/
	loadData: function ()
	{
		var size = new OpenLayers.Size(21, 25);
		var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);

		this.icon_addressMarker = new OpenLayers.Icon('/Viskort/App_Themes/' + this.application.active_theme + '/Images/OpenLayers/marker-default.png', size, offset);
		this.address_markers_layer = new OpenLayers.Layer.Markers("Adresse_1");
		this.address_markers_layer.displayInLayerSwitcher = false;
		this.map.addLayer(this.address_markers_layer);
	},

	/**
	* Method: AddressEndAddressSearch
	* Initails the handler for return of the UpdatePanel_Address asyncron postback
	*/
	AddressEndAddressSearch: function ()
	{
		Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.EndRequestHandler);
	},

	/**
	* EventHandler: EndRequestHandler
	* Handles endrequest for asycronpost for address finding
	*/
	EndRequestHandler: function (sender, args)
	{
		addressparameters = document.getElementById(addressElements);

		var util_instance = new VisKort.Utils();
		util_instance.ResetPrintInfo();

		if (args.get_error() == undefined && addressparameters.value != "") {
			parameters = addressparameters.value.split("#");
			if (parameters.length == 3) {
				viskort.components['address'].ShowAddressOnMap(parameters[0], parameters[1], parameters[2]);
				// Clear hiddenaddressfieldValue
				addressparameters.value = "";
			} else if (parameters.length == 2) {
				var elements = parameters[0].split(":");
				if (elements.length == 3 && elements[0].toLowerCase().indexOf("google") == 0) {
					viskort.components['address'].ShowPlaceOnMap(elements[1] + ":" + elements[2], parameters[1], true);
				} else if (elements.length == 3 && elements[0].toLowerCase().indexOf("localsearch") == 0) {
					viskort.components['address'].ShowPlaceOnMap(elements[1] + ":" + elements[2], parameters[1], false);
				} else {
					viskort.components['address'].ShowPlaceOnMap(parameters[0], parameters[1]);
				}
				// Clear hiddenaddressfieldValue
				addressparameters.value = "";
			}

		}
		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);
			alert("Søgning tog for lang tid");
		}
	},

	/**
	* Method: Reset_address_userControl 
	* Reset the address usercontrol to default
	*/
	Reset_address_userControl: function ()
	{
		try {
			var header_text = document.getElementById("HeaderInfo");
			header_text.innerHTML = "Aktuelt vises: Hele Danmark";

			var address_text = document.getElementById(result_div);
			address_text.innerHTML = "<br />Indtast adresse i feltet ovenfor og klik på &quot;Søg&quot;." +
            "<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 />Hvis der findes mere end en adresse" +
            " som matcher det indtastede præsenteres en liste af fundne adresser.<br />" +
            "Klik herefter på en af de listede adresser, hvorved denne vises i kortet."
			if (this.find_nearest_status != "0") {
				var find_nearest_div = document.getElementById(search_div);
				find_nearest_div.style.visibility = "hidden";
			}
			this.ClearaddressMarkers();
		} catch (e) {
		}
	},

	/**
	* Method: EnterKeyPress_address
	* Keypressdown event for address textboxs
	*
	* Parameters:
	* buttonName -<ID>
	* e - <Event>
	*/
	EnterKeyPress_address: function (buttonName, e)
	{
		if (e.which || e.keyCode) {
			if ((e.which == 13) || (e.keyCode == 13)) {
				var btn = document.getElementById(buttonName);

				try {

					btn.click();
					Event.stop(e);
				} catch (err) {

				}
				return false;
			}
			else {
				return true;
			}
		}
	},

	/**
	* Method: ClearaddressMarkers
	* Clears the address marker layer
	*/
	ClearaddressMarkers: function ()
	{
		this.address_markers_layer.clearMarkers();
	},

	/**
	* Method: ShowAddressOnMapWithMarker 
	* Show input address on map with marker and actives find nearest
	*
	* Parameters: 
	* east_koodinat - <Number> UTM32 Easting coordinate
	* north_koordinat - <Number> UTM32 Northing coordinate
	* zoomlevel - <Int> 0-11
	* popuptext - <String>
	* pantoNorthing - <Number> UTM32 Northing coordinate
	* pantoEasting - <Number> UTM32 Easting coordinate
	* showPopup - <Int> 0-1
	*/
	ShowAddressOnMapWithMarker: function (east_koordinat, north_koordinat, zoomlevel, popuptext, pantoNorthing, pantoEasting, showPopup)
	{
		this.ClearaddressMarkers();
		// convert point into destination coordinate system
		var markerLonLat = new OpenLayers.LonLat(east_koordinat, north_koordinat)
		if (viskort.applicationModeGlobal) {
			markerLonLat = viskort.convertLonLat(markerLonLat, 'EPSG:25832', 'EPSG:102113');
		}
		this.marker = new OpenLayers.Marker(markerLonLat, this.icon_addressMarker);
		this.marker.popuptext = popuptext;
		this.address_markers_layer.addMarker(this.marker);

		if (popuptext != "" && showPopup == 1) {
			this.application.infoBox.showCustomInfo(new OpenLayers.LonLat(east_koordinat, north_koordinat), popuptext);
		}

		// Set the markerpoint as center on the map.
		if (pantoNorthing != 0.0 && pantoEasting != 0.0) {
			// Panto point
			var panPoint = new OpenLayers.LonLat(pantoEasting, pantoNorthing);
			if (viskort.applicationModeGlobal) {
				panPoint = viskort.convertLonLat(panPoint, 'EPSG:25832', 'EPSG:102113');
			}
			var util = new VisKort.Utils();
			zoomlevel = util.checkzoomLevel(zoomlevel);
			this.map.setCenter(panPoint, zoomlevel);

		} else {
			// Set the markerpoint as center on the map.
			var markerPoint = new OpenLayers.LonLat(east_koordinat, north_koordinat);
			if (viskort.applicationModeGlobal) {
				markerPoint = viskort.convertLonLat(markerPoint, 'EPSG:25832', 'EPSG:102113');
			}
			var util = new VisKort.Utils();
			zoomlevel = util.checkzoomLevel(zoomlevel);
			this.map.setCenter(markerPoint, zoomlevel);

		}
		if (this.find_nearest_status != "0") {
			var findnearest_DIV = document.getElementById(search_div);
			findnearest_DIV.style.visibility = "visible";
			this.ActiveSearch_nearest();
		}

	},

	/**
	* Method: ShowAddressOnMap
	* Creates info for address and links to route and municipality tab
	* 
	* Parameters: 
	* placeAddress - <String> "streetname nr postalcode postaldistrict municipality
	* east_coordinat - <Number> UTM32 Easting coordinate
	* north_coordinat - <Number> UTM32 Northing coordinate
	*/
	ShowAddressOnMap: function (placeAddress, east_coordinat, north_coordinat)
	{

		var elements = placeAddress.split(':');
		var streetname = "";
		var nr = "";
		var postal_identifer = "";
		var postal_district = "";
		var municipality_name = "";

		if (elements.length == 5) {
			streetname = elements[0];
			nr = elements[1];
			postal_identifer = elements[2];
			postal_district = elements[3];
			municipality_name = elements[4];
		}

		var address_textbox = document.getElementById(adr_TextBox);
		var address_text = streetname + " " + nr + ", " + postal_identifer + " " + postal_district;
		address_textbox.value = address_text;

		// Set printinfo
		var util_instance = new VisKort.Utils();
		util_instance.SetPrintInfo(address_text);

		// Set east & north coordinats
		document.getElementById(easting_x).value = east_coordinat;
		document.getElementById(northing_y).value = north_coordinat;

		// RoutePlan
		var routeplan = new VisKort.Utils.LinkGenerator.Route(false);
		var divElemRoute = routeplan.getDivElement({ address: address_text }, "Address_Link_from_to_Route");

		// Link Google RoutePlan
		var googleplan = new VisKort.Utils.LinkGenerator.GoogleRoutePlan("TwoLinks", false);
		var divElemGooglePlan = googleplan.getDivElement({ address: address_text }, "Address_Link_from_to_GooglePlan");

		// Travelplan
		var travelplan = new VisKort.Utils.LinkGenerator.Rejseplanen("TwoLinks", false);
		var divElemTravelplan = travelplan.getDivElement({ address: address_text }, "Address_Link_from_to_Travelplan");

		// Link Municipality
		var municipality_link = new VisKort.Utils.LinkGenerator.Municipality();
		var divElemMunicipality = municipality_link.getDivElement({ municipality: municipality_name }, "Address_Link_municipality");

		// Make resultfield
		display_info = "<br /><div class='Address_div_result' ><img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme + "/Images/OpenLayers/marker-default.png' />" + streetname + " " + nr + ",<br />" +
        postal_identifer + " " + postal_district + "<br /></div>";


		var header_div = document.getElementById("HeaderInfo");
		header_div.innerHTML = "Aktuelt vises: " + streetname + " " + nr + ", " + postal_identifer + " " + postal_district + " (Kommune: " + municipality_name + ")";

		display_div = document.getElementById(result_div);
		display_div.innerHTML = "";
		display_div.innerHTML = display_info;
		display_div.appendChild(divElemMunicipality);
		if (viskort.routeWareEnabled)
			display_div.appendChild(divElemRoute);
		if (viskort.googleRouteEnabled)
			display_div.appendChild(divElemGooglePlan);
		if (viskort.rejsePlanEnabled)
			display_div.appendChild(divElemTravelplan);

		this.ShowAddressOnMapWithMarker(east_coordinat, north_coordinat, this.application.zoomlevels - 1, streetname + " " + nr + ", " + postal_identifer + " " + postal_district, 0.0, 0.0, 0);
	},

	/**
	* Method: ShowPlaceOnMap
	* Shows a place on the map and sets a marker in center of the boundingbox
	*
	* Parameteres:
	* placeAddress - <String> 
	*
	*/
	ShowPlaceOnMap: function (placeAddress, bbox, isGoogleSearch)
	{
		var elements = placeAddress.split(":");
		var placename = "";
		var municipalityname = "";
		if (elements.length == 2) {
			placename = elements[0];
			municipalityname = elements[1];
		}
		// Show mapheader
		var header_div = document.getElementById("HeaderInfo");
		header_div.innerHTML = "Aktuelt vises: " + placename;

		// set textbox
		var addressBoxRef = document.getElementById(adr_TextBox)
		if (addressBoxRef == null)
			addressBoxRef = document.getElementById(adrGoogle_TextBox);

		addressBoxRef.value = placename;

		// Set printinfo
		var util_instance = new VisKort.Utils();
		util_instance.SetPrintInfo(placename);

		// Make resultfield
		display_info = "<br /><div class='Address_div_result' ><img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme + "/Images/OpenLayers/marker-default.png' />" + placename + "<br /><br /></div";

		// Link Municipality
		var municipality_link = new VisKort.Utils.LinkGenerator.Municipality();
		var divElemMunicipality = municipality_link.getDivElement({ municipality: municipalityname }, "Address_Link_municipality");

		// Link RoutePlan
		var routeplan = new VisKort.Utils.LinkGenerator.Route(false);
		var divElemRoute = routeplan.getDivElement({ address: placename }, "Address_Link_from_to_Route");

		// Link Google RoutePlan
		var googleplan = new VisKort.Utils.LinkGenerator.GoogleRoutePlan("TwoLinks", false);
		var divElemGooglePlan = googleplan.getDivElement({ address: placename }, "Address_Link_from_to_GooglePlan");

		// Link TravelPlan
		var travelplan = new VisKort.Utils.LinkGenerator.Rejseplanen("TwoLinks", false);
		var divElemTravelplan = travelplan.getDivElement({ address: placename }, "Address_Link_from_to_Travelplan");

		display_div = document.getElementById(result_div);
		display_div.innerHTML = "";
		display_div.innerHTML = display_info;
		display_div.appendChild(divElemMunicipality);
		if (viskort.routeWareEnabled)
			display_div.appendChild(divElemRoute);
		if (viskort.googleRouteEnabled)
			display_div.appendChild(divElemGooglePlan);
		if (viskort.rejsePlanEnabled)
			display_div.appendChild(divElemTravelplan);

		// zoom to bbox //#NKI:Ved søgning med AWS fejler "Skjoldenæsvej 69, 4174"
		if (bbox != "") {
			var bboxcoordinats = bbox.split(':');
			var boundingbox = new OpenLayers.Bounds(bboxcoordinats[0], bboxcoordinats[1], bboxcoordinats[2], bboxcoordinats[3]);

			if (viskort.applicationModeGlobal) {
				var min = new OpenLayers.LonLat(bboxcoordinats[0], bboxcoordinats[1]);
				var max = new OpenLayers.LonLat(bboxcoordinats[2], bboxcoordinats[3]);

				if (isGoogleSearch) {
					var minConverted = viskort.convertLonLat(min, 'EPSG:4326', 'EPSG:102113');
					var maxConverted = viskort.convertLonLat(max, 'EPSG:4326', 'EPSG:102113');
					boundingbox = new OpenLayers.Bounds(minConverted.lon, minConverted.lat, maxConverted.lon, maxConverted.lat);
				}
				else {
					var minConverted = viskort.convertLonLat(min, 'EPSG:25832', 'EPSG:102113');
					var maxConverted = viskort.convertLonLat(max, 'EPSG:25832', 'EPSG:102113');
					boundingbox = new OpenLayers.Bounds(minConverted.lon, minConverted.lat, maxConverted.lon, maxConverted.lat);
					boundingbox.left -= 1;
					boundingbox.top -= 1;
				}
			}

			try {
				this.map.zoomToExtent(boundingbox, true);
			} catch (Exception) {
				//this exception occur, when setting exten on google maps layer
				// however, this function DO have effect!
				// Because of this, the exception is ignored
			}
			var lotlat = this.map.getCenter();
			this.ClearaddressMarkers();
			this.marker = new OpenLayers.Marker(lotlat, this.icon_addressMarker);
			this.address_markers_layer.addMarker(this.marker);
			// Active findnearest            
			if (this.find_nearest_status != "0") {
				// Set point for findnearest
				document.getElementById(easting_x).value = lotlat.lon;
				document.getElementById(northing_y).value = lotlat.lat;
				var findnearest_DIV = document.getElementById(search_div);
				findnearest_DIV.style.visibility = "visible";
				this.ActiveSearch_nearest();
			}
		}
	},

	/**
	* Method: Address_from_parameters 
	* Used when address page is called with parameters sets address info and links
	* 
	* Parameters:
	* streetname - <String>
	* nr - <String>
	* postal_identifer - <String>
	* postal_district - <String>
	* municipality_name - <String>
	* east_coordinat - <Number> UTM32 Easting coordinate 
	* north_coordinat - <Number> UTM32 Northing coordinate
	* resultdiv - 
	* zoomlevel - <Int> 0-11
	* pantoNorth - <Number> UTM32 Northing coordinate
	* pantoEast - <Number> UTM32 Easting coordinate
	*/
	Address_from_parameters: function (streetname, nr, postal_identifer, postal_district, municipality_name, east_coordinat, north_coordinat, textbox, resultdiv, zoomlevel, pantoNorth, pantoEast)
	{

		if (zoomlevel == -1) {
			zoomlevel = this.application.zoomlevels - 1;
		}

		var address_text = streetname + " " + nr + ", " + postal_identifer + " " + postal_district;
		// Set textseachBox
		address_textbox = document.getElementById(textbox);
		address_textbox.value = address_text;

		// Set printinfo
		var util_instance = new VisKort.Utils();
		util_instance.SetPrintInfo(address_text);

		// Set east & north coordinats
		document.getElementById(easting_x).value = east_coordinat;
		document.getElementById(northing_y).value = north_coordinat;

		// Link RoutePlan
		var routeplan = new VisKort.Utils.LinkGenerator.Route(false);
		var divElemRoute = routeplan.getDivElement({ address: address_text }, "Address_Link_from_to_Route");

		// Link Google RoutePlan
		var googleplan = new VisKort.Utils.LinkGenerator.GoogleRoutePlan("TwoLinks", false);
		var divElemGooglePlan = googleplan.getDivElement({ address: address_text }, "Address_Link_from_to_GooglePlan");

		// Link TravelPlan
		var travelplan = new VisKort.Utils.LinkGenerator.Rejseplanen("TwoLinks", false);
		var divElemTravelplan = travelplan.getDivElement({ address: address_text }, "Address_Link_from_to_Travelplan");

		// Link Municipality
		var municipality_link = new VisKort.Utils.LinkGenerator.Municipality();
		var divElemMunicipality = municipality_link.getDivElement({ municipality: municipality_name }, "Address_Link_municipality");

		// Make resultfield
		display_info = "<br /><div class='Address_div_result'><img alt='' class='floatRight' src='/Viskort/App_Themes/" + this.application.active_theme + "/Images/OpenLayers/marker-default.png' />" + streetname + " " + nr + ",<br />" +
        postal_identifer + " " + postal_district + "<br /></div>";

		var header_div = document.getElementById("HeaderInfo");
		header_div.innerHTML = "Aktuelt vises: " + streetname + " " + nr + ", " + postal_identifer + " " + postal_district + " (Kommune: " + municipality_name + ")";

		display_div = document.getElementById(resultdiv);
		display_div.innerHTML = "";
		display_div.innerHTML = display_info;
		display_div.appendChild(divElemMunicipality);
		if (viskort.routeWareEnabled)
			display_div.appendChild(divElemRoute);
		if (viskort.googleRouteEnabled)
			display_div.appendChild(divElemGooglePlan);
		if (viskort.rejsePlanEnabled)
			display_div.appendChild(divElemTravelplan);

		this.ShowAddressOnMapWithMarker(east_coordinat, north_coordinat, zoomlevel, streetname + " " + nr + ", " + postal_identifer + " " + postal_district, pantoNorth, pantoEast, 0);
	},

	/**
	* Method: ShowAddressOnMapWithcoordinats 
	* Shows address on map with coordinats and descriction
	*
	* Parameters:
	* north - <Number> UTM32 Northing coordinate
	* east - <Number> UTM32 Easting coordinate
	* desp - <String>
	* zoomlevel - <Int> 0-11
	* pantoNorth - <Number> UTM32 Northing coordinate
	* pantoEast - <Number> UTM32 Easting coordinate
	*/
	ShowAddressOnMapWithcoordinats: function (northing, easting, desp, zoomlevel, pantoNorth, pantoEast)
	{
		if (zoomlevel == -1) {
			zoomlevel = this.application.zoomlevels - 1;
		}
		if (this.application.pagemode == "popup") {
			// Set coordinat to use to find nearest location
			document.getElementById(easting_x).value = easting;
			document.getElementById(northing_y).value = northing;
		}
		this.ShowAddressOnMapWithMarker(easting, northing, zoomlevel, desp, pantoNorth, pantoEast, 1);
	},

	/**
	* Method: ShowAddressOnMapWithcoordinatsIframe 
	* Show coordinate on map with description for iframe
	*
	* Parameters:
	* north - <Number> UTM32 Northing coordinate
	* east - <Number> UTM32 Easting coordinate
	* desp - <String>
	* zoomlevel - <Int>
	* pantoNorth - <Number> UTM32 Northing coordinate
	* pantoEast - <Number> UTM32 Easting coordinate
	*/
	ShowAddressOnMapWithcoordinatsIframe: function (north_koordinat, east_koordinat, desp, zoomlevel, pantoNorthing, pantoEasting)
	{
		if (zoomlevel == -1) {
			zoomlevel = this.application.zoomlevels - 1;
		}

		this.ClearaddressMarkers();
		// convert point into destination coordinate system
		var markerLonLat = new OpenLayers.LonLat(east_koordinat, north_koordinat)
		if (viskort.applicationModeGlobal) {
			markerLonLat = viskort.convertLonLat(markerLonLat, 'EPSG:25832', 'EPSG:102113');
		}
		this.marker = new OpenLayers.Marker(markerLonLat, this.icon_addressMarker);
		this.marker.popuptext = desp;
		this.address_markers_layer.addMarker(this.marker);

		this.application.infoBox.showCustomInfo(new OpenLayers.LonLat(east_koordinat, north_koordinat), desp);

		// Set the markerpoint as center on the map.
		if (pantoNorthing != 0.0 && pantoEasting != 0.0) {
			// Panto point
			var panPoint = new OpenLayers.LonLat(pantoEasting, pantoNorthing);
			if (viskort.applicationModeGlobal) {
				panPoint = viskort.convertLonLat(panPoint, 'EPSG:25832', 'EPSG:102113');
			}

			var util = new VisKort.Utils();
			zoomlevel = util.checkzoomLevel(zoomlevel);
			this.map.setCenter(panPoint, zoomlevel);

		} else {
			// Set the markerpoint as center on the map.
			var markerPoint = new OpenLayers.LonLat(east_koordinat, north_koordinat);
			if (viskort.applicationModeGlobal) {
				markerPoint = viskort.convertLonLat(markerPoint, 'EPSG:25832', 'EPSG:102113');
			}
			var util = new VisKort.Utils();
			zoomlevel = util.checkzoomLevel(zoomlevel);
			this.map.setCenter(markerPoint, zoomlevel);
		}

	},

	/**
	* Method: ShowErrorMsgIframe
	* Shows error msg when the address isn't unique
	*
	* Parameters:
	* address - <String>
	* ErrorMsg - <String>
	*/
	ShowErrorMsgIframe: function (address, ErrorMsg)
	{

		if (ErrorMsg == "") {
			alert("Adressen " + address + " er ikke unik.\nKlik på linket \"Vis i stort vindue\" for at se og vælge blandt de fundne adresser.");
		} else {
			alert("Adressen kunne ikke findes pga. " + ErrorMsg + "\nKlik på linket \"Vis i stort vindue\" for at rette søgning til.");
		}
	},

	/**
	* Method: ShowAddressOnMapIframe
	* Show address on iframe
	*
	* Parameters:
	* streetname - <String>
	* nr - <String>
	* postal_identifer - <String>
	* postal_district - <String>
	* municipality - <String>
	* east - <Number> UTM32 Easting coordinate
	* north - <Number> UTM32 Northing coordinate
	* zoomlevel - <Int> 0-11
	* pantoNorth - <Number> UTM32 Northing coordinate
	* pantoEast - <Number> UTM32 Easting coordinate
	*/
	ShowAddressOnMapIframe: function (streetname, nr, postal_identifer, postal_district, municipality, east_koordinat, north_koordinat, zoomlevel, pantoNorthing, pantoEasting)
	{
		if (zoomlevel == -1) {
			zoomlevel = this.application.zoomlevels - 1;
		}
		var desp = streetname + " " + nr + ", <br />" + postal_identifer + " " + postal_district;
		// Set printinfo
		var util_instance = new VisKort.Utils();
		util_instance.SetPrintInfo(desp);

		this.ClearaddressMarkers();
		// convert point into destination coordinate system
		var markerLonLat = new OpenLayers.LonLat(east_koordinat, north_koordinat)
		if (viskort.applicationModeGlobal) {
			markerLonLat = viskort.convertLonLat(markerLonLat, 'EPSG:25832', 'EPSG:102113');
		}
		this.marker = new OpenLayers.Marker(markerLonLat, this.icon_addressMarker);
		this.marker.popuptext = desp;
		this.address_markers_layer.addMarker(this.marker);

		this.application.infoBox.showCustomInfo(new OpenLayers.LonLat(east_koordinat, north_koordinat), desp);

		// Set the markerpoint as center on the map.
		if (pantoNorthing != 0.0 && pantoEasting != 0.0) {
			// Panto point
			var panPoint = new OpenLayers.LonLat(pantoEasting, pantoNorthing);
			if (viskort.applicationModeGlobal) {
				panPoint = viskort.convertLonLat(panPoint, 'EPSG:25832', 'EPSG:102113');
			}

			var util = new VisKort.Utils();
			zoomlevel = util.checkzoomLevel(zoomlevel);
			this.map.setCenter(panPoint, zoomlevel);
		} else {
			// Set the markerpoint as center on the map.
			var markerPoint = new OpenLayers.LonLat(east_koordinat, north_koordinat);
			if (viskort.applicationModeGlobal) {
				markerPoint = viskort.convertLonLat(markerPoint, 'EPSG:25832', 'EPSG:102113');
			}

			var util = new VisKort.Utils();
			zoomlevel = util.checkzoomLevel(zoomlevel);
			this.map.setCenter(markerPoint, zoomlevel);

		}
	},

	/*
	* Method: ShowPlaceOnMapIframe
	*
	* Parameters: 
	* placename - <String> name of place
	* municipality - <String>
	* east - <Number> UTM32 Easting coordinate
	* north - <Number> UTM32 Northing coordinate
	* zoomlevel - <Int> 0-11
	* pantoNorth - <Number> UTM32 Northing coordinate
	* pantoEast - <Number> UTM32 Easting coordinate
	* bbox - <String> boundingbox no for use in this version
	*/
	ShowPlaceOnMapIframe: function (placename, municipality, east_koordinat, north_koordinat, zoomlevel, pantoNorthing, pantoEasting, bbox)
	{
		if (zoomlevel == -1) {
			zoomlevel = this.application.zoomlevels - 1;
		}
		var desp = placename + ", <br />" + municipality;

		// Set printinfo
		var util_instance = new VisKort.Utils();
		util_instance.SetPrintInfo(desp);

		this.ClearaddressMarkers();
		// convert point into destination coordinate system
		var markerLonLat = new OpenLayers.LonLat(east_koordinat, north_koordinat)
		if (viskort.applicationModeGlobal) {
			markerLonLat = viskort.convertLonLat(markerLonLat, 'EPSG:25832', 'EPSG:102113');
		}
		this.marker = new OpenLayers.Marker(markerLonLat, this.icon_addressMarker);
		this.marker.popuptext = desp;
		this.address_markers_layer.addMarker(this.marker);

		this.application.infoBox.showCustomInfo(new OpenLayers.LonLat(east_koordinat, north_koordinat), desp);

		// Set the markerpoint as center on the map.
		if (pantoNorthing != 0.0 && pantoEasting != 0.0) {
			// Panto point
			var panPoint = new OpenLayers.LonLat(pantoEasting, pantoNorthing);
			if (viskort.applicationModeGlobal) {
				panPoint = viskort.convertLonLat(panPoint, 'EPSG:25832', 'EPSG:102113');
			}
			var util = new VisKort.Utils();
			zoomlevel = util.checkzoomLevel(zoomlevel);
			this.map.setCenter(panPoint, zoomlevel);

		} else {
			// Set the markerpoint as center on the map.
			var markerPoint = new OpenLayers.LonLat(east_koordinat, north_koordinat);
			if (viskort.applicationModeGlobal) {
				markerPoint = viskort.convertLonLat(markerPoint, 'EPSG:25832', 'EPSG:102113');
			}

			var util = new VisKort.Utils();
			zoomlevel = util.checkzoomLevel(zoomlevel);
			this.map.setCenter(markerPoint, zoomlevel);
		}
	},

	/**
	* Method: Click_address
	* Click event for address marker
	* Parameters:
	* event - <Event>
	*/
	Click_address: function (event)
	{
		this.application.infoBox.showCustomInfo(this.lonlat, this.popuptext);
		OpenLayers.Event.stop(event);
	},

	/*
	* Method: ActiveSearch_nearest 
	* Initials the activesearch div 
	* that are available on given page. If no layers are found
	* the findnearest would be hidden.
	*/
	ActiveSearch_nearest: function ()
	{
		var layers = this.map.layers;
		var list_count = 0;
		this.ListOfFileNames = new Array();
		for (var i = 0; i < layers.length; i++) {
			if (layers[i].poiListID) {
				this.ListOfFileNames[list_count] = layers[i].poiListID
				this.ListOfFileNames[list_count + 1] = layers[i].name;
				list_count += 2;
			}
		}
		if (list_count == 0) {
			var findnearest_DIV = document.getElementById(search_div);
			findnearest_DIV.style.visibility = "hidden";
		}
	},

	/**
	* Method: Find_nearest
	* Find neareste from an address northing-easting coordinat
	*/
	Find_nearest: function ()
	{
		var pm1 = document.getElementById(easting_x).value;
		var pm2 = document.getElementById(northing_y).value;
		var drop_count = document.getElementById(search_nearest_count_drop);
		var drop_list = document.getElementById(search_nearest_drop);
		var listID = drop_list[drop_list.selectedIndex].value;
		var layername = "";
		this.listName = drop_list[drop_list.selectedIndex].text;

		for (var i = 0; i < this.ListOfFileNames.length; i += 2) {
			if (listID == this.ListOfFileNames[i]) {
			    layername = this.ListOfFileNames[i + 1];
				break;
			}
		}

		var places_to_find = drop_count.value;

		this.ClearaddressMarkers();
		var utils = new VisKort.Utils();
		utils.ShowLayers(this.map, ["Adresse_1", this.listName]);
		this.address_markers_layer.addMarker(this.marker);
		//this.RequestInfo(pm1 + ":" + pm2 + ":" + 1 + ":" + listID + ":" + filename + ":" + places_to_find);
		this.RequestInfo(pm1 + ":" + pm2 + ":" + 1 + ":" + listID + ":" + places_to_find);

	},

	/**
	* Method: Draw_nearest_points
	* Draws the nearest point
	* 
	* Parameters:
	* x - <Number> UTM32 Easting coordinate
	* y - <Number> UTM32 Northing coordinate
	* index - <Int> 1-10 index for images to show
	*/
	Draw_nearest_points: function (x, y, index)
	{
		var size = new OpenLayers.Size(40, 40);
		var offset = 0;
		var icon_nearest = new OpenLayers.Icon('/Viskort/MapImages/' + index + '.gif', size, offset);

		// convert point into destination coordinate system
		var markerLonLat = new OpenLayers.LonLat(x, y)
		if (viskort.applicationModeGlobal) {
			markerLonLat = viskort.convertLonLat(markerLonLat, 'EPSG:25832', 'EPSG:102113');
		}
		var marker = new OpenLayers.Marker(markerLonLat, icon_nearest);
		this.address_markers_layer.addMarker(marker);
	},

	/**
	* Method: FindzoomBounding: 
	* Finds address_marker_layer boundingbox and zoomes to it 
	*/
	FindzoomBounding: function ()
	{
		this.nearest_boundingbox = this.address_markers_layer.getDataExtent()
		var extraWidth = this.nearest_boundingbox.getWidth() * 0.1;
		var extraHeight = this.nearest_boundingbox.getHeight() * 0.1;
		var maxExtentBounds = this.map.getMaxExtent();

		this.nearest_boundingbox.left = Math.max(this.nearest_boundingbox.left - extraWidth, maxExtentBounds.left);
		this.nearest_boundingbox.right = Math.min(this.nearest_boundingbox.right + extraWidth, maxExtentBounds.right);
		this.nearest_boundingbox.bottom = Math.max(this.nearest_boundingbox.bottom - extraHeight, maxExtentBounds.bottom);
		this.nearest_boundingbox.top = Math.min(this.nearest_boundingbox.top + extraHeight, maxExtentBounds.top);

		try {
			this.map.zoomToExtent(this.nearest_boundingbox, true);
		} catch (Exception) {
			//this exception occur, when setting exten on google maps layer
			// however, this function DO have effect!
			// Because of this, the exception is ignored
		}

	},

	/**
	* 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) {
						error = ajaxreq.responseXML.documentElement.getElementsByTagName("ERROR");

						if (error.length == 0) {
							nodes = ajaxreq.responseXML.documentElement.childNodes;
							var list_points = new Array();
							var obj_getinfoWMS = new VisKort.Utils.GetInfoWMS();
							var resultDIV = document.getElementById(result_div);

							for (var j = 0; j < nodes.length; j++) {
								x = nodes[j].attributes[0].nodeValue;
								y = nodes[j].attributes[1].nodeValue;
								list_points.push(x);
								list_points.push(y);
								viskort.components['address'].Draw_nearest_points(x, y, j + 1);
							}

							// zoom to marker extent
							viskort.components['address'].FindzoomBounding();

							var resultDIV = document.getElementById(result_div);

							var find_nearest_div = document.getElementById('Find_nearest_info');
							if (find_nearest_div) {
								resultDIV.removeChild(find_nearest_div);
							}

							var print_coordinat_div = document.getElementById("print_find_nearest");

							var newdiv = document.createElement("div")
							newdiv.className = "Address_Find_nearest_Msg";
							newdiv.id = "Find_nearest_info";
							resultDIV.appendChild(newdiv);


							// Find info for find nearest here
							var layer = viskort.components['address'].map.getLayersByName(viskort.components['address'].listName)[0];
							if (obj_getinfoWMS && list_points.length > 1 && layer != null) {
								obj_getinfoWMS.ResetDetailPrintInfo();
								obj_getinfoWMS.ResetPrintFindnearestCoordinats();
								obj_getinfoWMS.GetFeutureInfo(viskort.components['address'].map, list_points, layer, resultDIV);
								for (var i = 0; i < list_points.length; i += 2) {
									if (i == list_points.length - 2) {
										print_coordinat_div.innerHTML += list_points[i] + ":" + list_points[i + 1];
									} else {
										print_coordinat_div.innerHTML += list_points[i] + ":" + list_points[i + 1] + ":";
									}
								}
							}
						}
						else {
							// error
						}
					}
				}
			};
			var url = "ProxyAddress.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.Address"
});
