﻿/* ***** 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.Municipality
* 
* This class represents municipality. The method activate must be called when a 
* a instance is made, so that the needed address marker layer is initialized with the  
* needed events.
*/
VisKort.Component.Municipality = OpenLayers.Class(VisKort.Component, {

    /** 
    * Property: municipalityList 
    * {<Array>} double array with list of municipality names
    * and municipality codes for each region  
    */
    municipalityList: new Array(),

    /** 
    * Property: region_wfs 
    * {<OpenLayers.Layer>} WFS region layer    
    */
    region_wfs: null,

    /** 
    * Property: regionList 
    * {<Array>} Array with wfs municipality layer for each
    * region    
    */
    regionList: new Array(5),

    /**
    * Property: defaulton_themes
    * {<Array>} Array with defaulton municipality themes
    */
    defaultOn_themes: new Array(),

    /**
    * Property: municipalityThemes
    * {<Array>} Array with names of wms layers to show, when zooming to a 
    * municiplaity.
    *
    */
    municipalityThemes: new Array(),

    /**
    * Property: regionThemes
    * {<Array>} Array with names of wms layers to show, when a 
    * region is choosen. Not in use.
    */
    regionThemes: new Array(),

    /**
    * Property: boundingBox
    * {<OpenLayers.Bounds>} Holds a boundingbox for either a region or 
    * municipality when it's found.
    */
    boundingBox: "",

    /** 
    * Constructor: VisKort.Component.Municipality
    */
    initialize: function(municipality_themes) {

    },

    /** 
    * Method: startup
    * Could be call on startup when somethings need to be initials first
    */
    startup: function() {

    },

    /** 
    * Method: activate
    * Initiales the needed municipalitys layers if their not 
    * activate
    */
    activate: function() {
        if (!this.region_wfs || this.regionList[0]) {
            this.loadData();
        }

    },

    setThemes: function() {
        var layers = this.map.layers;

        if (layers) {
            var count = 0;
            this.municipalityThemes = new Array();
            for (var i = 0; i < layers.length; i++) {
                if (layers[i].visibility == true && layers[i].isBaseLayer == false && layers[i].CLASS_NAME != "OpenLayers.Layer.WFS" && layers[i].CLASS_NAME != "OpenLayers.Marker") {
                    this.municipalityThemes[count] = layers[i].name;
                    count++;
                }
            }
        }
    },

    /** 
    * Method: deActivate
    * Gets called when the tab for this class is unselected
    */
    deActivate: function() {
        var util_instance = new VisKort.Utils();
        util_instance.ResetPrintInfo();
    },

    /**
    * Method: loadData
    * Initials the needed layers for this class
    */
    loadData: function() {
        var layers = this.map.layers;
        /*var count = 0;
        var layers = this.map.layers;
        for (i = 0; i < layers.length; i++) {
        if (layers[i].name == "Kommuner") {
        this.municipalityThemes[count] = layers[i].name;
        count++;
        }
        }*/

        // RegionEventSetUP
        this.region_wfs = this.map.getLayersByName("RegionWFS")[0];
        if (this.region_wfs) {

            // There shuld be no events for print page
            if (this.pagemode.toLowerCase() != "print") {
                // Region_Click_Event
                this.region_wfs.events.register("click", this.region_wfs, this.Click_region);
            }
            // Region_Hover_Event
            var hover_region = new OpenLayers.Control.SelectFeature(this.region_wfs, { hover: true });
            hover_region.onSelect = this.ToolTip_region.bind(this);
            this.map.addControl(hover_region);
            hover_region.activate();

        }

        // Municipality setup must be add in the rigth order
        this.regionList[0] = this.map.getLayersByName("Hovedstaden")[0];
        this.regionList[1] = this.map.getLayersByName("Midtjylland")[0];
        this.regionList[2] = this.map.getLayersByName("Nordjylland")[0];
        this.regionList[3] = this.map.getLayersByName("Sjælland")[0];
        this.regionList[4] = this.map.getLayersByName("Syddanmark")[0];


        if (this.regionList[0] && this.regionList[1] && this.regionList[2] && this.regionList[3] && this.regionList[4]) {
            var listhover = new Array("hoverMunicipality", "hoverMunicipality1", "hoverMunicipality2", "hoverMunicipality3", "hoverMunicipality4");
            for (var i = 0; i < 5; i++) {
                // There shuld be no events for print page
                if (this.pagemode.toLowerCase() != "print") {
                    this.regionList[i].events.register("click", this.regionList[i], this.Click_municipality);
                }
                listhover[i] = new OpenLayers.Control.SelectFeature(this.regionList[i], { hover: true });
                listhover[i].onSelect = this.ToolTip_Municipality.bind(this);
                this.map.addControl(listhover[i]);
                listhover[i].activate();
            }
        }

        if (this.municipalityList.length < 1) {
            // initials municipality list
            this.MakeMunicipalityList();
        }
    },

    /**
    * Method: MakeMunicipalityList
    * Initials the municipality list's
    */
    MakeMunicipalityList: function() {
        ListHS = ["Albertslund", "165", "Allerød", "201", "Ballerup", "151", "Bornholms", "400", "Brøndby", "153",
        "Christiansø", "411", "Dragør", "155", "Egedal", "240", "Fredensborg", "210", "Frederiksberg", "147",
        "Frederikssund", "250", "Furesø", "190", "Gentofte", "157", "Gladsaxe", "159", "Glostrup", "161",
        "Gribskov", "270", "Halsnæs", "260", "Helsingør", "217", "Herlev", "163", "Hillerød", "219",
        "Hvidovre", "167", "Høje-Taastrup", "169", "Hørsholm", "223", "Ishøj", "183", "København", "101",
        "Lyngby-Taarbæk", "173", "Rudersdal", "230", "Rødovre", "175", "Tårnby", "185",
        "Vallensbæk", "187"];

        ListSJ = ["Faxe", "320", "Greve", "253", "Guldborgsund", "376", "Holbæk", "316", "Kalundborg", "326",
        "Køge", "259", "Lejre", "350", "Lolland", "360", "Næstved", "370", "Odsherred", "306",
        "Ringsted", "329", "Roskilde", "265", "Slagelse", "330", "Solrød", "269", "Sorø", "340",
        "Stevns", "336", "Vordingborg", "390"];

        ListSD = ["Assens", "420", "Billund", "530", "Esbjerg", "561", "Fanø", "563", "Fredericia", "607",
        "Faaborg-Midtfyn", "430", "Haderslev", "510", "Kerteminde", "440", "Kolding", "621", "Langeland", "482",
        "Middelfart", "410", "Nordfyns", "480", "Nyborg", "450", "Odense", "461", "Svendborg", "479",
        "Sønderborg", "540", "Tønder", "550", "Varde", "573", "Vejen", "575", "Vejle", "630",
        "Ærø", "492", "Aabenraa", "580"];

        ListMJ = ["Favrskov", "710", "Hedensted", "766", "Herning", "657", "Holstebro", "661", "Horsens", "615",
        "Ikast-Brande", "756", "Lemvig", "665", "Norddjurs", "707", "Odder", "727",
        "Randers", "730", "Ringkøbing-Skjern", "760", "Samsø", "741", "Silkeborg", "740",
        "Skanderborg", "746", "Skive", "779", "Struer", "671",
        "Syddjurs", "706", "Viborg", "791", "Århus", "751"];

        ListNJ = ["Brønderslev", "810", "Frederikshavn", "813", "Hjørring", "860", "Jammerbugt", "849",
        "Læsø", "825", "Mariagerfjord", "846", "Morsø", "773", "Rebild", "840", "Thisted", "787",
        "Vesthimmerlands", "820", "Aalborg", "851"];

        this.municipalityList[0] = ListHS;
        this.municipalityList[1] = ListMJ;
        this.municipalityList[2] = ListNJ;
        this.municipalityList[3] = ListSJ;
        this.municipalityList[4] = ListSD;
    },

    /**
    * Method: ValidMunicipalityCode
    * Validates a municipality code
    *
    * Parameters:
    * code - (String) 4 digit code for municipality
    *
    * Returns:
    * (Boolean) result of validating 
    */
    ValidMunicipalityCode: function(code) {
        var found = false;
        for (var i = 0; i < this.municipalityList.length; i++) {
            for (var j = 0; j < this.municipalityList[i].length; j++) {
                if (this.municipalityList[i][j] == code) {
                    found = true;
                    break;
                }
            }
        }
        return found;
    },


    /**
    * Method: FindBreadCrumData
    * Returns array with region_code, region_name and municipality_name
    * 
    * Parameter: 
    * municipality_code - (String) 3 digit code for municipality
    *
    * Returns:
    * (Array) Array with regioncode, regionname and municipalityname
    */
    FindBreadCrumData: function(municipality_code) {
        var dropdown = document.getElementById(region_drop);
        var region_code = "";
        var region_name = "";
        var municipality_name = "";
        for (var i = 0; i < dropdown.length - 1; i++) {
            for (var j = 0; j < this.municipalityList[i].length; j++) {
                if (this.municipalityList[i][j] == municipality_code) {
                    region_code = dropdown[i + 1].value;
                    region_name = dropdown[i + 1].text;
                    municipality_name = this.municipalityList[i][j - 1];
                    break;
                }
            }
        }
        return new Array(region_code, region_name, municipality_name);
    },

    /**
    * Method: FindActivMunicipalityLayer
    * Finds the name of the wfs layer that the municipality code 
    * belongs to.
    * 
    * Parameter: 
    * code - (String) 3 digit code for munipality
    *
    * Returns:
    * (OpenLayers.Layer) wfs layer for the active municipality 
    */
    FindActivMunicipalityLayer: function(code) {
        var index_layer = 0;
        for (var i = 0; i < this.municipalityList.length; i++) {
            for (var j = 0; j < this.municipalityList[i].length; j++) {
                if (this.municipalityList[i][j] == code) {
                    index_layer = i;
                    break;
                }
            }
        }
        return this.regionList[index_layer];
    },

    /**
    * Method: Municipality.ShowMapRegions
    * Description: Used when popupmap is called with the parameter ActivepaneID=k
    */
    ShowMapRegions: function() {
        this.activate();
        this.setThemes();
        if (this.municipalityList.length < 1) {
            this.MakeMunicipalityList();
        }
        else {
            this.RequestInfo("", 6);
        }

        var breadCrum = document.getElementById("HeaderInfo");
        breadCrum.innerHTML = "Aktuelt vises: <a href=\"javascript:viskort.components['municipality'].ShowMapRegions()\">Danmark</a>";
        this.ResetInfoboxs("All");

        //Util showlayers
        if (this.region_wfs) {
            new VisKort.Utils().disableStandardLayers(viskort.components['municipality'].map);
            new VisKort.Utils().activateLayers(viskort.components['municipality'].map,[this.region_wfs.name]);
        } else {
            //new VisKort.Utils().ShowLayers(viskort.components['municipality'].map, []);
        }
        // Denmark region view
        this.map.zoomToMaxExtent();
    },

    /**
    * Method: ShowMunicipality 
    * Show muncipality either if a municipality wfs layer is clicked or select in the dropdownboxs
    *
    * Parameteres:
    * bounds - <OpenLayers.Bound> boundingbox for municipality only used when callType is clicked
    * municipality_code - <String> 3 digit code for municipality
    * municipality_name - <String>
    * region_code - <String> 4 digit code for region
    * region_name - <String>
    * callType - <String> Use clicked when a municipality is clicked on map
    */
    ShowMunicipality: function(bounds, municipality_code, municipality_name, region_code, region_name, callType) {

        var breadCrum = document.getElementById("HeaderInfo");

        if (callType == "clicked") {
            breadCrum.innerHTML = "Aktuelt vises: <a href=\"javascript:viskort.components['municipality'].ShowMapRegions()\">Danmark</a> : <a href=\"javascript:viskort.components['municipality'].ShowMunicipalityInRegion('" + bounds + "','" + region_code + "','" + region_name + "','Selected')\">" +
            region_name + "</a> : " + municipality_name;
            this.map.zoomToExtent(bounds);
            //Util showlayers 
            new VisKort.Utils().ShowLayers(viskort.components['municipality'].map, this.municipalityThemes);
        }
        else {
            // Selected
            if (municipality_name != "Kommuner") {
                breadCrum = document.getElementById("HeaderInfo");
                var list = this.FindBreadCrumData(municipality_code);
                if (breadCrum != null && breadCrum != "" && list.length > 2) {
                    breadCrum.innerHTML = "Aktuelt vises: <a href=\"javascript:viskort.components['municipality'].ShowMapRegions()\">Danmark</a> : " +
                    "<a href=\"javascript:viskort.components['municipality'].ShowMunicipalityInRegion('" + null + "','" + list[0] + "','" + list[1] + "','Selected')\">" + list[1] + "</a> : " + list[2] + " Kommune";
                }
                this.RequestInfo(municipality_code, 1);
            }
            else {
                var dropdown = document.getElementById(region_drop);
                var parameters = dropdown[dropdown.selectedIndex].value + "," + dropdown[dropdown.selectedIndex].text;
                this.ResetInfoboxs("M");
                this.RequestInfo(parameters, 4);
            }
        }
    },

    /**
    * Method: ZoomToRegionOnMap
    * Zooms to region when the dropdownbox for region changes value
    */
    ZoomToRegionOnMap: function() {
        var reg_drop = document.getElementById(region_drop);
        this.SetDropDownboxRegion(reg_drop[reg_drop.selectedIndex].value);
        this.ShowMunicipalityInRegion(null, reg_drop[reg_drop.selectedIndex].value, reg_drop[reg_drop.selectedIndex].text, "Selected");
    },

    /**
    * Method: ZoomToMunicipalityOnMap
    * Zooms to municipality when the dropdownbox for municipality changes value
    */
    ZoomToMunicipalityOnMap: function() {
        var mun_drop = document.getElementById(municipality_drop);
        this.SetDropDownboxMunicipality(mun_drop[mun_drop.selectedIndex].value, null);
        this.ShowMunicipality(null, mun_drop[mun_drop.selectedIndex].value, mun_drop[mun_drop.selectedIndex].text, null, null, "Selected");
    },

    /*
    * Method: ShowMunicipality
    * Used when popupmap is call with a parameter
    * "MunicipalityCode". Sets breadcrum, infobox, dropdownbox and zoomes to
    * the municipality and actives the themes in the municipalityThemes array thats is 
    * initails in map.js.
    * 
    * Parameters:
    * municipality_code - <String> 3 digit code for municipality
    */
    ShowMunicipality_Popup: function(municipality_code) {
        this.setThemes();
        if (this.municipalityList.length < 1) {
            // Initials municipality array
            this.MakeMunicipalityList();
        }

        if (this.ValidMunicipalityCode(municipality_code)) {
            var breadCrum = document.getElementById("HeaderInfo");
            this.SetDropDownboxMunicipality(municipality_code, null);

            // Make breadCrum
            var list = this.FindBreadCrumData(municipality_code);
            if (breadCrum != null && breadCrum != "" && list.length > 2) {
                breadCrum.innerHTML = "Aktuelt vises: <a href=\"javascript:viskort.components['municipality'].ShowMapRegions()\">Danmark</a> : " +
                "<a href=\"javascript:viskort.components['municipality'].ShowMunicipalityInRegion('" + null + "','" + list[0] + "','" + list[1] + "','Selected')\">" + list[1] + "</a> : " + list[2] + " Kommune";
            }
            this.RequestInfo("" + municipality_code, 1);
        } else {
            this.ShowMapRegions();
        }
    },

    /*
    * Method: ShowMunicipalityInRegion
    * Zooms to a map_extent for a region and activtes
    * municipality layer for the given region.
    * Can be call in two ways.
    * 1)When a user click a region the function must be called
    * ShowMunicipalityInRegion(bounds, region_code, region_name,"clicked")
    * 2) When a user select a region in the dropdownbox or click the regionname in the breadcrum
    * ShowMunicipalityInRegion(null, region_code, region_name,"select")
    *
    * Parameters: 
    * bounds - <OpenLayers.Bound> boundingbox for region is only used when region is clicked
    * region_code - <String> 4 digit code for region
    * region_name - <String>
    * callType - <String> (clicked,selected)
    */
    ShowMunicipalityInRegion: function(bounds, region_code, region_name, callType) {

        var breadCrum = document.getElementById("HeaderInfo");

        if (callType == "clicked") {
            new VisKort.Utils().ShowLayers(viskort.components['municipality'].map, [region_name]);
            breadCrum.innerHTML = "Aktuelt vises: <a href=\"javascript:viskort.components['municipality'].ShowMapRegions()\">Danmark</a> : <a href=\"javascript:viskort.components['municipality'].ShowMunicipalityInRegion('" + bounds + "','" + region_code + "' ,'" + region_name + "','Selected')\" >" + region_name + "</a>";
            this.map.zoomToExtent(bounds);
        }
        else {
            // Selected
            if (region_name != "Regioner") {
                this.SetDropDownboxRegion(region_code);
                this.ResetInfoboxs("M");
                var parameters = region_code + "," + region_name;
                this.RequestInfo(parameters, 5);
            } else {
                this.ShowMapRegions();
            }
        }
    },

    /**
    * Method: ShowMunicipalityIframe
    * Used to show a municipality in an iframe when this is called with parameters
    *
    * Parameters: 
    * municipalyti_code - <String> 3 digit code for municipality
    */
    ShowMunicipalityIframe: function(municipality_code) {
        this.activate();
        this.setThemes();
        if (this.municipalityList.length < 1) {
            this.MakeMunicipalityList();
        }
        if (this.ValidMunicipalityCode(municipality_code)) {
            // Zooms to municipality
            this.RequestInfo(municipality_code, 2);

        } else {
            alert("Kommune kode findes ikke");
        }
    },

    /**
    * EventHandler: ToolTip_region
    * Handels hover event on region wfs layer
    *
    * Parameters:
    * event - (Event) 
    */
    ToolTip_region: function(feature) {

        try {
            var region_div = document.getElementById(this.region_wfs.id);
            region_div.title = "Region: " + feature.attributes.REGIONNAVN;
        } catch (e) {
            alert("Ingen tooltip for region")
        }
    },

    /**
    * EventHandler: ToolTip_Municipality
    * Handels hover event on municipality wfs layer
    *
    * Parameters:
    * event - (Event) 
    */
    ToolTip_Municipality: function(feature) {
        try {
            var code = feature.attributes.KOMMUNE_NR.split(".", 1);
            var layerToShow = this.FindActivMunicipalityLayer(code);
            var municipality_div = document.getElementById(layerToShow.id);
            municipality_div.title = feature.attributes.Myndigheds;
        } catch (e) {
            alert("Ingen tooltip for region")
        }
    },

    /**
    * EventHandler: Click_region
    * Handels click event on region wfs layer
    *
    * Parameters:
    * event - (Event) 
    */
    Click_region: function(event) {
        if (this.selectedFeatures.length == 1) {
            viskort.components['municipality'].ResetInfoboxs("M");
            viskort.components['municipality'].SetRegionInfobox(this.selectedFeatures[0]);
            viskort.components['municipality'].SetDropDownboxRegion(this.selectedFeatures[0].attributes.REGION_NR.split(".", 1)[0]);
            viskort.components['municipality'].ShowMunicipalityInRegion(this.selectedFeatures[0].geometry.getBounds(), this.selectedFeatures[0].attributes.REGION_NR.split(".", 1)[0], this.selectedFeatures[0].attributes.REGIONNAVN, "clicked");
        }
        else {
        }
        OpenLayers.Event.stop(event);
    },

    /**
    * EventHandler: Click_municipality
    * Handels click event on municipality wfs layer
    *
    * Parameters:
    * event - (Event) 
    */
    Click_municipality: function(event) {
        if (this.selectedFeatures.length == 1) {
            viskort.components['municipality'].SetMunicipalityInfoBox(this.selectedFeatures[0])
            viskort.components['municipality'].SetDropDownboxMunicipality(this.selectedFeatures[0].attributes.KOMMUNE_NR.split(".", 1), this.selectedFeatures[0].attributes.REGION_N_1.split(".", 1));
            viskort.components['municipality'].ShowMunicipality(this.selectedFeatures[0].geometry.getBounds(), this.selectedFeatures[0].attributes.KOMMUNE_NR.split(".", 1), this.selectedFeatures[0].attributes.Myndigheds, this.selectedFeatures[0].attributes.REGION_N_1.split(".", 1), this.selectedFeatures[0].attributes.REGIONNA_1, "clicked");
        }
        else {
        }
        OpenLayers.Event.stop(event);
    },

    /**
    * 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 municipality
    *
    * Parameters:
    * parameters - (String) arguments for request 
    * type - (Int) type of request
    */
    RequestInfo: function(parameters, type) {
        var ajaxreq = this.GetXmlHttpRequest();
        if (ajaxreq) {
            ajaxreq.onreadystatechange = function ProgressResponse() {
                if (ajaxreq.readyState == 4) {
                    if (ajaxreq.status == 200) {
                        var error = "";
                        switch (type) {

                            case 1: // Finds and (sets region/municipality infoboxes and zoomes to municipality boundingBox)
                                error = ajaxreq.responseXML.documentElement.getElementsByTagName("ERROR");
                                if (error.length == 0) {
                                    if (ajaxreq.responseXML.documentElement.childNodes.length == 3) {
                                        var region_div = document.getElementById("RegionInfoBox");
                                        region_div.style.visibility = "visible";
                                        region_div.innerHTML = ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue;

                                        var municipality_div = document.getElementById("MunicipalityInfoBox");
                                        municipality_div.style.visibility = "visible";
                                        municipality_div.innerHTML = ajaxreq.responseXML.documentElement.childNodes[1].firstChild.nodeValue;

                                        // Set printinfo
                                        var util_instance = new VisKort.Utils();
                                        util_instance.SetPrintInfo(ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue + "<br />" + ajaxreq.responseXML.documentElement.childNodes[1].firstChild.nodeValue);

                                        var result = ajaxreq.responseXML.documentElement.childNodes[2].firstChild.nodeValue;
                                        var coodinarts = result.split(",");
                                        if (coodinarts.length == 4) {
                                            boundingBox = new OpenLayers.Bounds(coodinarts[0], coodinarts[1], coodinarts[2], coodinarts[3]);
                                        } else {
                                            boundingBox = new OpenLayers.Bounds(100000, 6000000, 1000000, 6400000);
                                        }
                                        viskort.components['municipality'].map.zoomToExtent(boundingBox);
                                        //Util showlayers
                                        new VisKort.Utils().ShowLayers(viskort.components['municipality'].map, viskort.components['municipality'].municipalityThemes);
                                    }
                                }
                                break;

                            case 2: // Finds and zoomes to municipality boundingbox
                                error = ajaxreq.responseXML.documentElement.getElementsByTagName("ERROR");
                                if (error.length == 0) {
                                    if (ajaxreq.responseXML.documentElement.childNodes.length == 1) {
                                        var result = ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue;
                                        var coodinarts = result.split(",");
                                        if (coodinarts.length == 4) {
                                            boundingBox = new OpenLayers.Bounds(coodinarts[0], coodinarts[1], coodinarts[2], coodinarts[3]);
                                        } else {
                                            boundingBox = new OpenLayers.Bounds(100000, 6000000, 1000000, 6400000);
                                        }
                                        viskort.components['municipality'].map.zoomToExtent(boundingBox);
                                        //Util showlayers
                                        new VisKort.Utils().ShowLayers(viskort.components['municipality'].map, viskort.components['municipality'].municipalityThemes);
                                    }
                                }
                                break;

                            case 3: // Finds and sets region infobox
                                error = ajaxreq.responseXML.documentElement.getElementsByTagName("ERROR");
                                if (error.length == 0) {
                                    if (ajaxreq.responseXML.documentElement.childNodes.length == 1) {
                                        var region_div = document.getElementById("RegionInfoBox");
                                        region_div.style.visibility = "visible";
                                        region_div.innerHTML = ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue;

                                        // Set printinfo
                                        // var municipality_div = document.getElementById("MunicipalityInfoBox");
                                        var util_instance = new VisKort.Utils();
                                        util_instance.SetPrintInfo(ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue);
                                    }
                                }
                                break;

                            case 4: // Finds and zoomes to region boundingbox and sets breadcrums
                                error = ajaxreq.responseXML.documentElement.getElementsByTagName("ERROR");
                                if (error.length == 0) {
                                    if (ajaxreq.responseXML.documentElement.childNodes.length == 1) {
                                        var result = ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue;
                                        var coodinarts = result.split(",");
                                        if (coodinarts.length == 4) {
                                            boundingBox = new OpenLayers.Bounds(coodinarts[0], coodinarts[1], coodinarts[2], coodinarts[3]);
                                        } else {
                                            boundingBox = new OpenLayers.Bounds(100000, 6000000, 1000000, 6400000);
                                        }
                                        viskort.components['municipality'].map.zoomToExtent(boundingBox);
                                        var breadCrum = document.getElementById("HeaderInfo");
                                        region_code = parameters.split(',')[0];
                                        region_name = parameters.split(',')[1];
                                        breadCrum.innerHTML = "Aktuelt vises: <a href=\"javascript:viskort.components['municipality'].ShowMapRegions()\">Danmark</a> : <a href=\"javascript:viskort.components['municipality'].ShowMunicipalityInRegion('" + boundingBox + "','" + region_code + "','" + region_name + "','Selected')\">" + region_name + "</a>";
                                        //Util showlayers
                                        new VisKort.Utils().ShowLayers(viskort.components['municipality'].map, [region_name]);
                                    }
                                }
                                break;
                            case 5: // Finds and sets region infobox and zoom to region boundingbox
                                error = ajaxreq.responseXML.documentElement.getElementsByTagName("ERROR");
                                if (error.length == 0) {
                                    if (ajaxreq.responseXML.documentElement.childNodes.length == 2) {
                                        var region_div = document.getElementById("RegionInfoBox");
                                        region_div.style.visibility = "visible";
                                        region_div.innerHTML = ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue;

                                        // Set printinfo
                                        var util_instance = new VisKort.Utils();
                                        util_instance.SetPrintInfo(ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue);

                                        var result = ajaxreq.responseXML.documentElement.childNodes[1].firstChild.nodeValue;
                                        var coodinarts = result.split(",");
                                        if (coodinarts.length == 4) {
                                            boundingBox = new OpenLayers.Bounds(coodinarts[0], coodinarts[1], coodinarts[2], coodinarts[3]);
                                        } else {
                                            boundingBox = new OpenLayers.Bounds(100000, 6000000, 1000000, 6400000);
                                        }
                                        viskort.components['municipality'].map.zoomToExtent(boundingBox);
                                        region_code = parameters.split(',')[0];
                                        region_name = parameters.split(',')[1];
                                        var breadCrum = document.getElementById("HeaderInfo");
                                        breadCrum.innerHTML = "Aktuelt vises: <a href=\"javascript:viskort.components['municipality'].ShowMapRegions()\">Danmark</a> : <a href=\"javascript:viskort.components['municipality'].ShowMunicipalityInRegion('" + boundingBox + "','" + region_code + "','" + region_name + "','Selected')\">" + region_name + "</a>";
                                        //Util showlayers
                                        new VisKort.Utils().ShowLayers(viskort.components['municipality'].map, [region_name]);
                                    }
                                }
                                break;
                            case 6: // Resets dropdownbox for region and municipality
                                error = ajaxreq.responseXML.documentElement.getElementsByTagName("ERROR");
                                if (error.length == 0) {
                                    if (ajaxreq.responseXML.documentElement.childNodes.length == 1) {
                                        var result = ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue;
                                        var list = result.split(",");
                                        var dropdownRegionBox = document.getElementById(region_drop);
                                        var dropdownMunicipalityBox = document.getElementById(municipality_drop);
                                        // Resets regionbox
                                        dropdownRegionBox.selectedIndex = 0;
                                        // Resets municipalitysbox
                                        dropdownMunicipalityBox.innerHTML = "";
                                        var opt = document.createElement("option");
                                        opt.text = "Kommuner";
                                        opt.value = "Kommuner";
                                        dropdownMunicipalityBox.options.add(opt)
                                        for (var i = 0; i < list.length; i = i + 2) {
                                            opt = document.createElement("option");
                                            opt.text = list[i];
                                            opt.value = list[i + 1];
                                            dropdownMunicipalityBox.options.add(opt)
                                        }
                                    }
                                }
                                break;
                            case 7: // Set region printinfo
                                error = ajaxreq.responseXML.documentElement.getElementsByTagName("ERROR");
                                if (error.length == 0) {
                                    if (ajaxreq.responseXML.documentElement.childNodes.length == 1) {
                                        // Set printinfo
                                        var util_instance = new VisKort.Utils();
                                        util_instance.SetPrintInfo(ajaxreq.responseXML.documentElement.childNodes[0].firstChild.nodeValue);
                                    }
                                }
                                break;
                            default:
                                viskort.components['municipality'].ShowMapRegions();
                                break;
                        }
                    }
                    else {
                        alert("Data kunne ikke hentes:\n");
                    }
                }
            };
            var url = "ProxyMunicipality.ashx?parameters=" + parameters + "&choose=" + type;
            ajaxreq.open("GET", url, true); //asyncron
            ajaxreq.send(null); // null for Firefox
        }
        else {

            alert("Kunne ikke oprette Ajax request");
        }
    },

    /**
    * Method: MunicipalityLink 
    * Call when a municipality link is click in another tab
    *
    * Parameters:
    * name - <String> 
    */
    MunicipalityLink: function(name) {
        this.activate();
        this.setThemes();
        if (this.municipalityList.length < 1) {
            this.MakeMunicipalityList();
        }
        var code = this.FindMunicipalityCode(name);

        if (this.application.active_theme.toLowerCase() == "borgerdk") {

            if (this.ValidMunicipalityCode(code)) {

                var breadCrum = document.getElementById("HeaderInfo");
                this.SetDropDownboxMunicipality(code, null);

                // Make breadCrum
                var list = this.FindBreadCrumData(code);
                if (breadCrum != null && breadCrum != "" && list.length > 2) {
                    breadCrum.innerHTML = "Aktuelt vises: <a href='javascript:viskort.components['municipality'].ShowMapRegions()'>Danmark</a> : " +
                    "<a href=\"javascript:viskort.components['municipality'].ShowMunicipalityInRegion('" + null + "','" + list[0] + "','" + list[1] + "','Selected')\">" + list[1] + "</a> : " + list[2] + " Kommune";
                }
                this.RequestInfo("" + code, 1);
            } else {
                this.ShowMapRegions();
            }
        } else {
            this.RequestInfo(code, 2); // Only show's municipality
        }
    },

    /**
    * Method: FindMunicipalityCode
    * Finds municipality code for given municipality name. 
    *
    * Parameters:
    * municipality_name - <String>
    */
    FindMunicipalityCode: function(municipality_name) {
        var code = "165"; //zoom to a standard municipality
        for (var i = 0; i < this.municipalityList.length; i++) {
            for (var j = 0; j < this.municipalityList[i].length; j += 2) {
                if (this.municipalityList[i][j].toLowerCase() == municipality_name.toLowerCase()) {
                    return this.municipalityList[i][j + 1];
                }
            }
        }
        return null;
    },

    /**
    * Method: SetDropDownboxMunicipality
    * Set dropdownbox for municipality and given region dropdownbox
    * 
    * Parameters:
    * municipality_code - <String> 3 digit code for municipality
    * region_code - <String> 4 digit code for region
    */
    SetDropDownboxMunicipality: function(municipality_code, region_code) {
        var dropdown = document.getElementById(region_drop);
        var dropdown2 = document.getElementById(municipality_drop);

        // Finds region_code
        if (region_code == null) {
            for (var i = 0; i < dropdown.length - 1; i++) {
                for (var j = 0; j < this.municipalityList[i].length; j++) {
                    if (this.municipalityList[i][j] == municipality_code) {
                        region_code = dropdown[i + 1].value;
                    }
                }
            }
        }

        // Set Region dropdownbox
        for (i = 0; i < dropdown.length; i++) {
            if (dropdown[i].value == region_code) {
                dropdown.selectedIndex = dropdown[i].index;
                break;
            }
        }

        var indextemp;
        switch (region_code) {
            case "1084":
                indextemp = 0;
                break;
            case "1082":
                indextemp = 1;
                break;
            case "1081":
                indextemp = 2;
                break;
            case "1085":
                indextemp = 3;
                break;
            case "1083":
                indextemp = 4;
                break;
            default:
                indextemp = -1;
                break;
        }
        if (indextemp != -1) {
            dropdown2.innerHTML = "";
            var opt = document.createElement("option");
            opt.text = "Kommuner";
            opt.value = "Kommuner";
            dropdown2.options.add(opt)
            try {
                for (j = 0; j < this.municipalityList[indextemp].length; j = j + 2) {
                    opt = document.createElement("option");
                    opt.text = this.municipalityList[indextemp][j];
                    opt.value = this.municipalityList[indextemp][j + 1];

                    dropdown2.options.add(opt)
                }
            } catch (e) {
                // error
            }
        }

        for (i = 0; i < dropdown2.length; i++) {
            if (dropdown2[i].value == municipality_code) {
                dropdown2.selectedIndex = dropdown2[i].index;
                break;
            }
        }
    },

    /**
    * Method: SetDropDownboxRegion
    * Set dropdownbox for region and updates the municipality dropdownbox
    * with municipality for the given region.
    * 
    * Parameters:
    * region_code - <String> 4 digit code for region
    */
    SetDropDownboxRegion: function(region_code) {
        var dropdown = document.getElementById(region_drop);
        var dropdown2 = document.getElementById(municipality_drop);

        // Set Region dropdownbox
        for (var i = 0; i < dropdown.length; i++) {
            if (dropdown[i].value == region_code) {
                dropdown.selectedIndex = dropdown[i].index;
                break;
            }
        }

        // Updates municipality dropdownlist
        var index;
        switch (region_code) {
            case "1084":
                index = 0;
                break;
            case "1082":
                index = 1;
                break;
            case "1081":
                index = 2;
                break;
            case "1085":
                index = 3;
                break;
            case "1083":
                index = 4;
                break;
            default:
                index = -1;
                break;
        }
        if (index != -1) {
            dropdown2.innerHTML = "";
            var opt = document.createElement("option");
            opt.text = "Kommuner";
            opt.value = "Kommuner";
            dropdown2.options.add(opt)
            try {
                for (var j = 0; j < this.municipalityList[index].length; j = j + 2) {
                    opt = document.createElement("option");
                    opt.text = this.municipalityList[index][j];
                    opt.value = this.municipalityList[index][j + 1];
                    dropdown2.options.add(opt)
                }
            } catch (e) {
            }
        }
    },

    /**
    * Method: SetRegionInfobox
    * Used to set region infobox when a region is clicked on the map
    *
    * Parameters:
    * feature - <OpenLayers.Feature> region feature
    */
    SetRegionInfobox: function(feature) {
        var region_name = "Region ";
        if (feature.attributes.REGIONNAVN != undefined && feature.attributes.REGIONNAVN != "") {
            region_name += feature.attributes.REGIONNAVN;
        }

        var addressField = "";
        if (feature.attributes.PostAdress != undefined && feature.attributes.Postnummer != undefined && feature.attributes.PostAdress != "" && feature.attributes.Postnummer != "") {
            addressField += feature.attributes.PostAdress + "<br />" + feature.attributes.Postnummer + "<br />";
        }
        if (feature.attributes.E_post != undefined && feature.attributes.E_post != "") {
            addressField += "<a class='Print_no_display' href=mailto:" + feature.attributes.E_post + ">E-mail</a><br class='Print_no_display' />";
        }
        if (feature.attributes.Hjemmeside != undefined && feature.attributes.Hjemmeside != "") {
            addressField += "<a class='Print_no_display' href='" + feature.attributes.Hjemmeside + "' target='_blank'>Hjemmeside</a><br class='Print_no_display' />";
        }

        var tlfField = "";
        if (feature.attributes.Telefax != undefined && feature.attributes.Telefax != "") {
            tlfField += "Telefax: " + feature.attributes.Telefax + "<br />";
        }

        if (feature.attributes.Telefontid != undefined && feature.attributes.Telefon != undefined && feature.attributes.Telefontid != "" && feature.attributes.Telefon != "") {

            times = feature.attributes.Telefontid.split(",");
            tlfHours = "";
            for (var i = 0; i < times.length; i++) {
                tlfHours += times[i] + "<br />";
            }
            tlfField += "Tlf. " + feature.attributes.Telefon + "<br /><br /><b>Telefontider:</b> <br />" + tlfHours;
        }
        else if (feature.attributes.Telefon != undefined && feature.attributes.Telefon != "") {
            tlfField += "Tlf. " + feature.attributes.Telefon + "<br />";
        }

        var openField = "";
        if (feature.attributes.Traffetid != undefined && feature.attributes.Traffetid != "") {
            times = feature.attributes.Traffetid.split(",");
            openHours = "";
            for (i = 0; i < times.length; i++) {
                openHours += times[i] + "<br />";
            }
            openField = "<b>Åbningstider</b><br />" + openHours;
        }
        var region_div = document.getElementById("RegionInfoBox");
        region_div.style.visibility = "visible";
        var info_div = "<b> " + region_name + "</b>" +
        "<br />" + addressField + "<br />" + tlfField + "<br />" + openField;
        region_div.innerHTML = info_div;
        // set print info
        var util_instance = new VisKort.Utils();
        util_instance.SetPrintInfo(info_div);
    },

    /**
    * Method: SetMunicipalityInfoBox
    * Used to set municipality infobox when a municipality is clicked on the map
    *
    * Parameters:
    * feature - <OpenLayers.Feature> municipality feature
    */
    SetMunicipalityInfoBox: function(feature) {
        var municipality_name = "";
        if (feature.attributes.Myndigheds != undefined) {
            municipality_name = feature.attributes.Myndigheds;
        } else {
            municipality_name = "Kommune";
        }

        var addressField = "";
        if (feature.attributes.PostAdress != undefined && feature.attributes.Postnummer != undefined && feature.attributes.PostAdress != "" && feature.attributes.Postnummer != "") {
            addressField = feature.attributes.PostAdress + "<br />" + feature.attributes.Postnummer + "<br />";
        }
        if (feature.attributes.E_post != undefined && feature.attributes.E_post != "") {
            addressField += "<a class='Print_no_display' href=mailto:" + feature.attributes.E_post + ">E-mail</a><br class='Print_no_display' />";
        }
        if (feature.attributes.Hjemmeside != undefined && feature.attributes.Hjemmeside != "") {
            addressField += "<a class='Print_no_display' href='" + feature.attributes.Hjemmeside + "' target='_blank'>Hjemmeside</a><br class='Print_no_display' />";
        }

        var tlfField = "";
        if (feature.attributes.Telefax != undefined && feature.attributes.Telefax != "") {
            tlfField += "Telefax: " + feature.attributes.Telefax + "<br />";
        }
        if (feature.attributes.Telefontid != undefined && feature.attributes.Telefon != undefined && feature.attributes.Telefontid != "" && feature.attributes.Telefon != "") {
            times = feature.attributes.Telefontid.split(",");
            tlfHours = "";
            for (var i = 0; i < times.length; i++) {
                tlfHours += times[i] + "<br />";
            }
            tlfField += "Tlf. " + feature.attributes.Telefon + "<br /><br /><b>Telefontider:</b> <br />" + tlfHours;
        }
        else if (feature.attributes.Telefon != undefined && feature.attributes.Telefon != "") {
            tlfField += "Tlf. " + feature.attributes.Telefon + "<br />";
        }

        var openField = "";
        if (feature.attributes.Traffetid != undefined && feature.attributes.Traffetid != "") {
            times = feature.attributes.Traffetid.split(",");
            openHours = "";
            for (i = 0; i < times.length; i++) {
                openHours += times[i] + "<br />";
            }
            openField = "<b>Åbningstider:</b><br />" + openHours;
        }

        var municipality_div = document.getElementById("MunicipalityInfoBox");
        if (municipality_div) {
            municipality_div.style.visibility = "visible";

            var info_div = "<b>" + municipality_name + "</b>" +
            "<br />" + addressField + "<br />" + tlfField + "<br />" + openField;

            municipality_div.innerHTML = info_div;
        }
        var region_div = document.getElementById("RegionInfoBox");
        if (region_div) {
            if (region_div.innerHTML.length < 1) {
                this.RequestInfo(feature.attributes.KOMMUNE_NR.split(".", 1)[0], 3);
            } else {
                var util_instance = new VisKort.Utils();
                util_instance.SetPrintInfo(region_div.innerHTML + "" + municipality_div.innerHTML);
            }
        }
    },

    /**
    * Method: ResetInfoboxs
    * Can reset the the municipality and region infobox.
    *
    * Parameter:
    * choose - <String> M for reset municipality infobox or anything else for reset both.
    */
    ResetInfoboxs: function(choose) {
        var region_div = document.getElementById("RegionInfoBox");
        var municipality_div = document.getElementById("MunicipalityInfoBox");
        if (choose == "M") {
            municipality_div.style.visibility = "hidden";
            municipality_div.innerHTML = "";

            var reg_drop = document.getElementById(region_drop);
            this.RequestInfo(reg_drop[reg_drop.selectedIndex].value, 7);
        } else {
            region_div.style.visibility = "hidden";
            region_div.innerHTML = "";
            municipality_div.style.visibility = "hidden";
            municipality_div.innerHTML = "";

            // Set printinfo
            var util_instance = new VisKort.Utils();
            util_instance.ResetPrintInfo();
        }
    },

    CLASS_NAME: "VisKort.Component.Municipality"

});
