﻿(function() {

    OpenLayers.Feature.Vector.style['default'].strokeWidth = '2';
    Proj4js.defs["EPSG:32633"] = "+title=Zone33NOR +proj=utm +zone=33 +ellps=WGS84 +datum=WGS84 +units=m +no_defs";

    var createYahooHybrid = function() {
        return new OpenLayers.Layer.Yahoo(
        "Yahoo Hybrid",
        { 'type': YAHOO_MAP_HYB, 'sphericalMercator': true });
    };

    var createYahooStreet = function() {
        return new OpenLayers.Layer.Yahoo(
        "Yahoo Street",
        { 'sphericalMercator': true });
    };

    var createYahooSatellite = function() {
        return new OpenLayers.Layer.Yahoo(
        "Yahoo Satellite",
        { 'type': YAHOO_MAP_SAT, 'sphericalMercator': true });
    };

    var createVirtualEarthRoads = function() {
        return new OpenLayers.Layer.VirtualEarth(
        "Virtual Earth Roads",
        { 'type': VEMapStyle.Road, 'sphericalMercator': true });
    };

    var createVirtualEarthAerial = function() {
        return new OpenLayers.Layer.VirtualEarth(
        "Virtual Earth Aerial",
        { 'type': VEMapStyle.Aerial, 'sphericalMercator': true });
    };

    var createVirtualEarthHybrid = function() {
        return new OpenLayers.Layer.VirtualEarth(
        "Virtual Earth Hybrid",
        { 'type': VEMapStyle.Hybrid, 'sphericalMercator': true });
    };

    var createGoogleStreet = function() {
        return new OpenLayers.Layer.Google(
        "Google Streets",
        { 'sphericalMercator': true });
    };

    var createGooglePhysical = function() {
        return new OpenLayers.Layer.Google(
        "Google Physical",
        { type: G_PHYSICAL_MAP, 'sphericalMercator': true });
    };

    var createGoogleSatellite = function() {
        return new OpenLayers.Layer.Google(
        "Google Satellite",
        { type: G_SATELLITE_MAP, 'sphericalMercator': true });
    };

    var createGoogleHybrid = function() {
        return new OpenLayers.Layer.Google(
        "Google Hybrid",
        { type: G_HYBRID_MAP, 'sphericalMercator': true });
    };


    var DropdownListAdapter = Class.create();
    DropdownListAdapter.prototype = {
        initialize: function(drpList, controlProjection, mapProjection) {
            this.format = new OpenLayers.Format.WKT();
            this.list = drpList;
            this.controlProjection = controlProjection;
            this.mapProjection = mapProjection;
            this.feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(Places.Trondheim.lon, Places.Trondheim.lat));
        },

        truncateFeature: function(feature) {
            var vertices = feature.geometry.getVertices();
            for (var i = 0; i < vertices.length; i++) {
                vertices[i].x = Math.round(vertices[i].x);
                vertices[i].y = Math.round(vertices[i].y);
            }
        },

        getFeature: function() {
            return feature;
        },

        getGeometry: function() {
            return feature.geometry;
        },

        setFeature: function(feat) {
            this.feature = feat;
            truncateFeature(this.feature);
        },

        setGeometry: function(geometry) {
            var feature = new OpenLayers.Feature.Vector(geometry);
            this.setFeature(feature);
        },

        onChange: function(fun) {
            Event.observe(this.list, 'change', fun);
        }
    };




    var TextareaAdapter = Class.create();
    TextareaAdapter.prototype = {
        initialize: function(x, y, controlProjection, mapProjection) {
            this.format = new OpenLayers.Format.WKT();
            this.lat = y;
            this.lon = x;
            this.controlProjection = controlProjection;
            this.mapProjection = mapProjection;
        },
        truncateFeature: function(feature) {
            var vertices = feature.geometry.getVertices();
            for (var i = 0; i < vertices.length; i++) {
                vertices[i].x = Math.round(vertices[i].x);
                vertices[i].y = Math.round(vertices[i].y);
            }
        },
        getFeature: function() {
            var y = this.lat.value;
            var x = this.lon.value;
            var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(x, y));
            //feature.geometry.transform(this.controlProjection, this.mapProjection);
            return feature;
        },
        getGeometry: function() {
            var feature = this.getFeature();
            if (!feature)
                return;
            return feature.geometry;
        },
        removeSpace: function(old) {
            var n = old.replace(/([a-zA-Z]+)\s*/, "$1");
            n = n.replace(/,\s+/g, ",");
            return n;
        },
        setFeature: function(feature) {
            //feature.geometry.transform(this.mapProjection, this.controlProjection);
            this.truncateFeature(feature);
            //var oldval = this.removeSpace(this.el.value);
            //var newval = this.format.write(feature);
            //if (oldval !== newval) {
            //this.el.value = newval;
            //send_textbox_data();
            this.lat.value = feature.geometry.y;
            this.lon.value = feature.geometry.x;

        },
        setGeometry: function(geometry) {
            var feature = new OpenLayers.Feature.Vector(geometry);
            this.setFeature(feature);
        },
        onChange: function(fun) {
            Event.observe(this.lat, 'change', fun);
            Event.observe(this.lon, 'change', fun);
        }
    };

    var Projections = {
        Map: new OpenLayers.Projection("EPSG:900913"),
        Zone33: new OpenLayers.Projection("EPSG:32633"),
        Display: new OpenLayers.Projection("EPSG:4326")
    };

    var Places = {
        Trondheim: new OpenLayers.LonLat(270200, 7042000),
        Jomfruland: new OpenLayers.LonLat(187580, 6537208)
    };

    var Adapters = {
        TextareaAdapter: TextareaAdapter,
        DropdownListAdapter: DropdownListAdapter
    };

    var LastGeometry = Class.create();
    LastGeometry.prototype = {
        initialize: function() {
            this.reset();
        },
        reset: function() {
            this.geometry = null;
        },
        setGeometry: function(geometry) {
            this.geometry = geometry;
        }
    };

    var RoadInfo = Class.create();
    RoadInfo.prototype = {
        initialize: function(roadType, roadNumber, mainParcel, metersFrom, cause) {
            this.type = roadType;
            this.number = roadNumber;
            this.parsell = mainParcel;
            this.meters = metersFrom;
            this.cause = cause;
        },
        setInfo: function(info) {
            this.type.selectedIndex = this.causeIndexFromValue(info.type);
            this.number.value = info.number;
            this.parsell.value = info.parsell;
            this.meters.value = info.meters;
        },
        causeIndexFromValue: function(value) {
            var index = 0;
            var iterate = true;
            while (iterate) {
                if (this.type[index].value.substring(0, 1) == value) {
                    break;
                }

                index++;
            }

            return index;
        }
    };

    var ViewMapInfo = Class.create();
    ViewMapInfo.prototype = {
        initialize: function(countyList, municipalityList, speciesList, genderList, ageList, causeList, outcomeList, fromDate, toDate) {
            this.county = countyList;
            this.municipality = municipalityList;
            this.specie = speciesList;
            this.gender = genderList;
            this.age = ageList;
            this.cause = causeList;
            this.outcome = outcomeList;
            this.from = fromDate;
            this.to = toDate;
        }
    };

    var Objects = {
        RoadInfo: RoadInfo,
        ViewMapInfo: ViewMapInfo
    };



    var BaseMap = Class.create();
    BaseMap.prototype = {
        initialize: function(el, opts) {
            Object.extend(this.options, opts || {});

            this.map = new OpenLayers.Map(el, this.options);
            this.initLayers();
            this.initControls();

            //this.map.setCenter(Places.Jomfruland, 8);
        },

        settKartBlokkfarger: function() {
            var elScale = $$('.olControlScale')[0];
            var elScaleLine = $$('.olControlScaleLine')[0];
            var elMousePosition = $$('.olControlMousePosition')[0];

            // elScale
            var styleString = elScale.getAttribute('style');
            styleString += "; background: white; padding: 2px; bottom: 20px !important;";
            elScale.setAttribute('style', styleString);

            // elScaleLine
            styleString = elScaleLine.getAttribute('style');
            styleString += "; background: white; bottom: 4px;";
            elScaleLine.setAttribute('style', styleString);

            // elMousePosition
            styleString = elMousePosition.getAttribute('style');
            styleString += "; background: white; padding: 2px;";
            elMousePosition.setAttribute('style', styleString);
        },
        
        options: {
            projection: Projections.Z33,
            //displayProjection: Projections.Display,
            units: "m",
            numZoomLevels: 18,
            //maxResolution: 156543.0339,
            maxResolution: 'auto',
            //maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34) //gmap
            maxExtent: new OpenLayers.Bounds(-127998, 6377920, 1145510, 7976800), //Z33 EPSG:32633" minx="-127998" miny="6.37792e+06" maxx="1.14551e+06" maxy="7.9768e+06" />
            //maxExtent: new OpenLayers.Bounds(-847442,6424100,1885593,7966077)
            minResolution: .1
        },
        initLayers: function() {
            //this.initGoogleLayers();
            //this.initVirtualEarthLayers();
            this.initGeoNorgeLayers();
            //this.initVerneomradeLag();
            //this.initFallViltWMS();

        },
        initGeoNorgeLayers: function() {
            var ts = myTicket.split(",");

            if (ts[1]) {
                var toporaster = "http://wms.geonorge.no/skwms1/wms.topo2/TI_" + ts[1];
                this.dnwms = new OpenLayers.Layer.WMS.Untiled("Toporaster",
                    toporaster, {
                        //singleTile: 'True',
                        // ServiceName: 'WMS_Grunnkart',
                        Service: 'wms',
                        format: 'image/png',
                        //  wtmver: '1.1.1',
                        STYLES: 'default',
                        //layers      : "norgen5000,byverden,byeuropa,bynorge,latlong,latlongLab"
                        layers: 'Hoydelag,Arealdekkeflate,Fjellskygge,Vannflate,Bygninger,Vannkontur,Elver,Flomlop,AdministrativeGrenser,Skytefeltgrense,Veger,fkb_Samferdsel,Jernbane,Hoydekurver,Ferger,Anleggslinjer,fkb_naturinfo,Eiendom,Hoydepunkt,Jernbanestasjon,Vegbom,Turisthytte,Anleggspunkter,Bygningspunkter,Arealdekkepunkter,Tettsted,Tekst'
                    }, {
                        transitionEffect: 'resize',
                        'projection': Projections.Zone33
                        /*,                    
                        'maxExtent': new OpenLayers.Bounds(100000,6300000, 300000,8060000), //Z33
                        'maxResolution': "auto",
                        'units' : 'm'
                        */
                    });
                this.map.addLayer(this.dnwms);
            }

            if (ts[0]) {
                var norgeibilder = "http://wms.geonorge.no/skwms1/wms.norgeibilder/TI_" + ts[0];
                this.dnfoto = new OpenLayers.Layer.WMS.Untiled("Norge i bilder",
                    norgeibilder, {
                        //singleTile: 'True',
                        // ServiceName: 'WMS_Grunnkart',
                        Service: 'wms',
                        format: 'image/png',
                        //wtmver: '1.1.1',
                        STYLES: 'default',
                        layers: 'OrtofotoAlle'
                    }, {
                        //maxExtent: new OpenLayers.Bounds(-120683,6338570,1154623,8055520),
                        transitionEffect: 'resize',
                        'projection': Projections.Zone33
                    });
                this.map.addLayer(this.dnfoto);
            }
            if (ts[2]) {
                var sjokart = "http://wms.geonorge.no/skwms1/wms.sjo_hovedkart2/TI_" + ts[2];
                this.dnsjokart = new OpenLayers.Layer.WMS.Untiled("Sjøkart",
                    sjokart, {
                        //singleTile: 'True',
                        // ServiceName: 'WMS_Grunnkart',
                        Service: 'wms',
                        format: 'image/png',
                        STYLES: 'default',
                        layers: 'overview,hovedkart'
                    }, {
                        transitionEffect: 'resize',
                        'projection': Projections.Zone33
                    });
                this.map.addLayer(this.dnsjokart);
            }

            if (ts[3]) {
                var toporaster2 = "http://wms.geonorge.no/skwms1/wms.toporaster2/TI_" + ts[3];
                this.dntoporaster2 = new OpenLayers.Layer.WMS.Untiled("Toporaster 2",
                    toporaster2, {
                        //singleTile: 'True',
                        // ServiceName: 'WMS_Grunnkart',
                        Service: 'wms',
                        format: 'image/png',
                        wtmver: '1.1.1',
                        STYLES: 'default',
                        layers: 'topografiskraster'
                    }, {
                        transitionEffect: 'resize',
                        'projection': Projections.Zone33
                    });
                this.map.addLayer(this.dntoporaster2);
            }
        },
        initVerneomradeLag: function() {
            var vorwms = "http://dnweb12.dirnat.no/wmsconnector/com.esri.wms.Esrimap";
            this.verneomradelag = new OpenLayers.Layer.WMS.Untiled("Verneområder WMS",
                    vorwms, {
                        ServiceName: 'WMS_NB_Vern',
                        format: 'image/png',
                        Service: 'wms',
                        styles: 'default',
                        layers: 'Vernet omrade,Vernet enkeltobjekt',
                        transparent: 'true'
                    }, {
                        BGCOLOR: '0x23f3f5',
                        'projection': Projections.Zone33,

                        isBaseLayer: 0
                    });
            this.map.addLayer(this.verneomradelag);

            var kulturwms = "http://dnweb12.dirnat.no/wmsconnector/com.esri.wms.Esrimap";
            this.kulturomradelag = new OpenLayers.Layer.WMS.Untiled("Kulturlandskap WMS",
                    kulturwms, {
                        ServiceName: 'WMS_NB_Kulturlandskap',
                        format: 'image/png',
                        Service: 'wms',
                        styles: 'default',
                        layers: 'Kulturlandskap',
                        transparent: 'true'
                    }, {
                        BGCOLOR: '0x23f3f5',
                        'projection': Projections.Zone33,
                        isBaseLayer: 0
                    });
            this.map.addLayer(this.kulturomradelag);
        },
        ticketLoaded: function(resp) {
            var t = resp;
        },
        initGoogleLayers: function() {
            var gphy = createGooglePhysical();
            var gmap = createGoogleStreet();
            var gsat = createGoogleSatellite();
            var ghyb = createGoogleHybrid();

            this.map.addLayers([gmap, gphy, gsat, ghyb]);
        },
        initVirtualEarthLayers: function() {
            var vehyb = createVirtualEarthHybrid();
            this.map.addLayer(vehyb);
        },
        initEditLayer: function() {
            this.editLayer = new OpenLayers.Layer.Vector("Editable", this.options);
            this.map.addLayer(this.editLayer);
        },
        initControls: function() {
            this.map.addControl(new OpenLayers.Control.LayerSwitcher());
            this.map.addControl(new OpenLayers.Control.MousePosition({ displayProjection: Projections.Zone33 }));
            this.map.addControl(new OpenLayers.Control.ZoomBox());
            this.map.addControl(new OpenLayers.Control.Scale());
            this.map.addControl(new OpenLayers.Control.ScaleLine());
        },
        getCenter: function() {
            return Places.Jomfruland;
        },
        add: function(geom) {
            var feature = new OpenLayers.Feature.Vector(geom);
            this.editLayer.addFeatures([feature]);
            this.setCenterToPoint(geom);
            //this.map.zoomOut(4);
        },
        remove: function(geom) {
            var feature = new OpenLayers.Feature.Vector(geom);
            //this.editLayer.removeFeatures([feature]);
            this.editLayer.destroyFeatures();
            this.setCenterToPoint(geom);
        },
        setCenterToPoint: function(geom) {
            if (!geom)
                return;
            //var zfe = this.map.getZoomForExtent(geom.getBounds());
            //this.map.zoomTo(zfe - 4);
            this.map.zoomToExtent(geom.getBounds());
        }
    };


    var EditMap = Class.create(BaseMap, {
        initialize: function($super, el, adapter, listadapter, roadInfo, opts) {
            this.adapter = adapter;
            this.listadapter = listadapter;
            this.LastGeometry = new LastGeometry();
            this.RoadInfo = roadInfo;
            this.UnderInitialization = true;

            $super(el, opts);
            this.initEditLayer();
            this.initEventHandlers();
            this.initPanelControls();
            this.setCenterByListValue();
            this.plotCurrentGeometry();
            this.settKartBlokkfarger();
            this.UnderInitialization = false;
        },

        sampleToPoint: function(sample) {
            return new OpenLayers.Geometry.Point(sample.getLongitude(), sample.getLatitude());
            //return new OpenLayers.LonLat(sample.getLatitude(), sample.getLongitude());
        },

        getCenter: function($super) {
            var geom = this.adapter.getGeometry();
            if (!geom) return Places.Trondheim;
            return geom ? geom.getBounds().getCenterLonLat() : $super.getCenter();
        },

        setCenterByListValue: function() {
            var id = this.listadapter.list.options[this.listadapter.list.selectedIndex].value;

            if (id != "") {
                var koordinat = this.hentKommuneJsonData(id);

                if (koordinat != null) {
                    this.map.zoomToExtent(koordinat);
                }
            }
        },

        plotCurrentGeometry: function() {
            var geometry = this.adapter.getGeometry();
            if (geometry) {
                if (!isNaN(geometry.x) && !isNaN(geometry.y)) {
                    this.add(geometry);
                    this.LastGeometry.setGeometry(geometry);
                } else {
                    if (this.LastGeometry.geometry != null) {
                        this.remove(LastGeometry.geometry);
                        this.LastGeometry.reset();
                    }
                }
            }
        },

        hentKommuneJsonData: function(kommuneId) {
            var request = OpenLayers.Request.POST({ url: "/Fallvilt/HentKommuneKoordinat/" + kommuneId, async: false });
            var jsondata = eval("(" + request.responseText + ")");

            var minX = jsondata["minX"];
            var minY = jsondata["minY"];
            var maxX = jsondata["maxX"];
            var maxY = jsondata["maxY"];
            var hasValue = jsondata["HasValue"];

            if (hasValue) {
                return new OpenLayers.Bounds(minX, minY, maxX, maxY);
            }

            return null;
        },

        hentVegidentJsonData: function(x, y) {
            var request = OpenLayers.Request.POST({ url: "/Fallvilt/HentVegIdent?x=" + x + "&y=" + y, async: false });
            var jsondata = eval("(" + request.responseText + ")");

            var type = jsondata["VegType"];
            var vegnr = jsondata["VegNr"];
            var hp = jsondata["HP"];
            var meters = jsondata["Meterverdi"];
            var hasValue = jsondata["HasValue"];

            if (hasValue) {
                return new RoadInfo(type, vegnr, hp, meters);
            }

            return null;
        },

        sjekkZoom: function() {
            var verdi = $$('.olControlScale')[0].innerHTML;

            var kolonIndex = verdi.indexOf(":");
            var endtagIndex = verdi.indexOf("<", kolonIndex);
            var scalaverdi = verdi.substring(kolonIndex + 2, endtagIndex);

            var kIndeks = scalaverdi.indexOf("K");
            var mIndeks = scalaverdi.indexOf("M");

            if (kIndeks != -1 || mIndeks != -1) {
                return false;
            }

            if (scalaverdi >= 10000) {
                return false;
            }

            return true;
        },



        initEventHandlers: function() {
            this.editLayer.events.on({
                "featuremodified": function(event) {
                    var geometry = event.feature.geometry.clone();
                    this.adapter.setGeometry(geometry);
                    this.setCenterToPoint(geometry);

                    var index = this.RoadInfo.cause.selectedIndex;

                    if (this.RoadInfo.cause[index].value == "3" || this.RoadInfo.cause[index].value == "7") {
                        var info = this.hentVegidentJsonData(geometry.x, geometry.y);
                        if (info) {
                            this.RoadInfo.setInfo(info);
                        }
                    }
                } .bind(this),
                "beforefeaturemodified": function(event) {
                    if (!this.sjekkZoom()) {
                        alert("Vennligst naviger til en målestokk større enn 1:10000 før du kartfester!");
                        return false;
                    }
                } .bind(this),
                "featureadded": function(event) {
                    if (!this.UnderInitialization && !this.sjekkZoom()) {
                        if (this.editLayer.features.length > 1) {
                            var newFeature = this.editLayer.features[1];
                            this.editLayer.removeFeatures(newFeature);
                            this.editLayer.destroyFeatures(newFeature);
                        } else if (this.editLayer.features.length == 1) {
                            var newFeature = this.editLayer.features[0];
                            this.editLayer.removeFeatures(newFeature);
                            this.editLayer.destroyFeatures(newFeature);
                        }
                        alert("Vennligst naviger til en målestokk større enn 1:10000 før du kartfester!");
                        return;
                    }

                    // Remove old features if they exist.
                    if (this.editLayer.features.length > 1) {
                        var old = this.editLayer.features[0];
                        this.editLayer.removeFeatures(old);
                        this.editLayer.destroyFeatures(old);
                    }
                    if (!event.feature.geometry)
                        return;
                    var geometry = event.feature.geometry.clone();
                    this.adapter.setGeometry(geometry);
                    this.setCenterToPoint(geometry);

                    var index = this.RoadInfo.cause.selectedIndex;

                    if (this.RoadInfo.cause[index].value == 3 || this.RoadInfo.cause[index].value == 7) {
                        var info = this.hentVegidentJsonData(geometry.x, geometry.y);
                        if (info) {
                            this.RoadInfo.setInfo(info);
                        }
                    }
                } .bind(this)
            });

            this.adapter.onChange(function(evt) {
                this.plotCurrentGeometry();
            } .bind(this));

            this.listadapter.onChange(function(evt) {
                var target;

                if (evt.target) {
                    target = evt.target;
                } else if (evt.srcElement) {
                    target = evt.srcElement;
                }

                //if (target.nodeType == 3) // defeat Safari bug
                //    target = target.parentNode;

                var geo = this.hentKommuneJsonData(target.value);

                if (geo != null) {
                    this.map.zoomToExtent(geo);
                }

            } .bind(this));
        },
        initPanelControls: function() {
            var panelControls = [
                        new OpenLayers.Control.Navigation({ title: "Flytt kartet" }),
                        new OpenLayers.Control.ZoomBox({ title: "Zoom i kartet ved å tegne en boks" }),
                        new OpenLayers.Control.ModifyFeature(this.editLayer, { title: "Flytt kartet eller digitalisert punkt", 'displayClass': 'olControlModifyFeature' }),
                        new OpenLayers.Control.DrawFeature(this.editLayer, OpenLayers.Handler.Point, { title: "Digitaliser punkt", 'displayClass': 'olControlDrawFeaturePoint' })
                    ];

            var toolbar = new OpenLayers.Control.Panel({
                displayClass: 'olControlEditingToolbar',
                defaultControl: panelControls[0]
            });

            toolbar.addControls(panelControls);
            this.map.addControl(toolbar);

        }
    });


    var NavMap = Class.create(BaseMap, {
        initialize: function($super, el, viewMapInfo, opts) {
            $super(el, opts);
            //OpenLayers.IMAGE_RELOAD_ATTEMPTS = 10;
            this.ViewMapInfo = viewMapInfo;
            this.initFallViltWMS();
            this.map.zoomToExtent(this.bboxBounds());
            this.settKartBlokkfarger();
        },
        
//        settKartBlokkfarger: function() {
//            var elScale = $$('.olControlScale')[0];
//            var elScaleLine = $$('.olControlScaleLine')[0];
//            var elMousePosition = $$('.olControlMousePosition')[0];

//            // elScale
//            var styleString = elScale.getAttribute('style');
//            styleString += "; background: white; padding: 2px; bottom: 20px !important;";
//            elScale.setAttribute('style', styleString);

//            // elScaleLine
//            styleString = elScaleLine.getAttribute('style');
//            styleString += "; background: white; bottom: 4px;";
//            elScaleLine.setAttribute('style', styleString);

//            // elMousePosition
//            styleString = elMousePosition.getAttribute('style');
//            styleString += "; background: white; padding: 2px;";
//            elMousePosition.setAttribute('style', styleString);
//        },

        addNavLayer: function() {
        },

        initFallViltWMS: function() {
            var fvwms = "/WMSInnsynskart.ashx";
            this.fvwmslayer = new OpenLayers.Layer.WMS.Untiled("Irregulær avgang", fvwms,
                {
                    REQUEST: 'GetMap',
                    VERSION: '1.3.0',
                    SERVICE: 'WMS',
                    LAYERS: 'Radyr,Elg,Hjort,Bever,Villrein,Moskus,Honsehauk,Kongeorn,Oter,Grevling,Rev,Marhund,Villsvin,Havorn,UbestemtHjortedyr',
                    STYLES: '',
                    CRS: 'EPSG:32633',
                    BBOX: this.hentBBox(),
                    WIDTH: '500',
                    HEIGHT: '500',
                    FORMAT: "image/png",
                    TRANSPARENT: 'TRUE',
                    FYLKE: this.ViewMapInfo.county.options[this.ViewMapInfo.county.selectedIndex].value,
                    KOMMUNE: this.ViewMapInfo.municipality.options[this.ViewMapInfo.municipality.selectedIndex].value,
                    ART: this.ViewMapInfo.specie.value,
                    KJONN: this.ViewMapInfo.gender.value,
                    ALDER: this.ViewMapInfo.age.value,
                    ARSAK: this.ViewMapInfo.cause.value,
                    UTFALL: this.ViewMapInfo.outcome.value,
                    FRA: this.hentDato(this.ViewMapInfo.from.value),
                    TIL: this.hentDato(this.ViewMapInfo.to.value)
                }, {

                //'projection': Projections.Zone33,
                //isBaseLayer: true
            });
            this.map.addLayer(this.fvwmslayer);
        },

        bboxBounds: function() {
            var bbox = this.hentBBox().split(',');
            return new OpenLayers.Bounds(bbox[0], bbox[1], bbox[2], bbox[3]);
        },

        hentDato: function(verdi) {
            var pattern = new RegExp("[0-3][0-9]\056[0|1][0-9]\056[1|2][0-9][0-9][0-9]");
            if (pattern.test(verdi)) {
                return verdi;
            }

            return "";
        },

        hentBBox: function() {
            var countyIndex = this.ViewMapInfo.county.selectedIndex;
            var countyValue = this.ViewMapInfo.county.options[countyIndex].value;
            var municipalityIndex = this.ViewMapInfo.municipality.selectedIndex;
            var municipalityValue = this.ViewMapInfo.municipality.options[municipalityIndex].value;

            if (countyValue != "" && municipalityValue == "") {
                var bboxCounty = this.hentFylkeJsonData(countyValue);

                if (bboxCounty != null) {
                    return bboxCounty.toBBOX(5);
                }

            }
            else if (municipalityValue != "") {
                var bboxMunicipality = this.hentKommuneJsonData(municipalityValue);

                if (bboxMunicipality != null) {
                    return bboxMunicipality.toBBOX(5);
                }
            }

            return '-245923,6393909,1263711,7970475';
        },

        hentFylkeJsonData: function(fylkeId) {
            var request = OpenLayers.Request.POST({ url: "/Fallvilt/HentFylkeKoordinat/" + fylkeId, async: false });
            var jsondata = eval("(" + request.responseText + ")");

            var minX = jsondata["minX"];
            var minY = jsondata["minY"];
            var maxX = jsondata["maxX"];
            var maxY = jsondata["maxY"];
            var hasValue = jsondata["HasValue"];

            if (hasValue) {
                return new OpenLayers.Bounds(minX, minY, maxX, maxY);
            }

            return null;
        },

        hentKommuneJsonData: function(kommuneId) {
            var request = OpenLayers.Request.POST({ url: "/Fallvilt/HentKommuneKoordinat/" + kommuneId, async: false });
            var jsondata = eval("(" + request.responseText + ")");

            var minX = jsondata["minX"];
            var minY = jsondata["minY"];
            var maxX = jsondata["maxX"];
            var maxY = jsondata["maxY"];
            var hasValue = jsondata["HasValue"];

            if (hasValue) {
                return new OpenLayers.Bounds(minX, minY, maxX, maxY);
            }

            return null;
        },

        createCookie: function(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        },

        readCookie: function(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        },

        eraseCookie: function(name) {
            createCookie(name, "", -1);
        }

    });


    if (typeof (window.Bouvet) == "undefined") {
        window.Bouvet = {};
    }

    Bouvet.Map = {
        BaseMap: BaseMap,
        EditMap: EditMap,
        NavMap: NavMap,
        Adapters: Adapters,
        Projections: Projections,
        Places: Places,
        Objects: Objects
    };



})();
